Ok, fair warning, this is far simpler than I anticipated. However, as with many things, the value for me was in the research. And I could find a particularly clear example with a simple Google search, so I figure I’d throw one into the ether and see if it can help someone in the future.
In a past career (I have a physics degree and was a mechanical engineer before switching to software engineering) I’d have been able to rattle off the geometric proofs, or slam this out with some calculus. But in this case I don’t need the calculus; I’m not concerned with curves, just lines and points.
I won’t bore you with the math or the proof, but if you feel the need feel free to check out this wiki post. What it boils down to is a simple formula that can easily be worked into a quick static method in C#.

For this demonstration I’m testing with values that were output from, the linear regression example from my last post. Just for the sake of continuity. The idea being (since I am after all still working on that stock analysis project I mentioned in that same post) that I could determine with simple math, how far above or below a trendline a particular price is.
For the given range of days mentioned in my earlier example with MSFT stock, I received values describing a line like:
0.67765x + 1y – 159.01825 = 0
To ask the question “how far off trend is a valuation of 160.00 dollars 5 days on the last day of measurement?”, I’ve implemented a static method in a bone stock console .Net Core 3.1 console application and made the call as in the following:
static void Main(string[] args)
{
var distance = ShortestDistance(0.67765f, 1f, -159.01825f, 4f, 160f);
Console.WriteLine($"160 is {distance} off of the trend line.");
}
static double ShortestDistance(float a, float b, float c, float x0, float y0)
{
double d = Math.Abs(a * x0 + b * y0 + c) /
Math.Sqrt(a * a + b * b);
return d;
}
I calculated with 4 days, thus the point in the above code is at (4,160.00). It yields an answer of $3.06 (I rounded here, it’s money after all).
Simple enough in practice. Rather anticlimactic, but this code will be called a few thousand times in the code that is to come, so it is important to my own uses.
Cheers.