Reputation: 751
I'm not quite sure what I'm doing wrong, as this should be fairly simple... I have 2 given points plus X from the third - and now I need Y from that third line.
That's a really simple equation: y = mx + b. But because I can't use this in my C#-program (well, I'm sure there's a library for that, but performance matters here), I'm trying to "write the formula out".
My function looks like this:
public static float GetY(Vector2 point1, Vector2 point2, float x)
{
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
var b = point1.Y - (m * point1.X);
return m*x + b;
}
Now something in this formula is wrong, because sometimes I don't get the right value. Do you have any idea what I'm doing wrong?
Upvotes: 7
Views: 13168
Reputation: 1
Why you do not try to write a separate function that calculate m so it just be passed as a parameter to this new function that is like predicting the y of the passed x . M should be constant and also b for all x being passed and y being calculated . Is not it?
Upvotes: 0
Reputation: 18474
You've put point1.y twice in the formula for m. Additionally as noticed by Jacob it should be a minus!
Think you want
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
Upvotes: 1
Reputation: 68848
You want this:
public static float GetY(Vector2 point1, Vector2 point2, float x)
{
var dx = point2.X - point1.x; //This part has problem in your code
if (dx == 0)
return float.NaN;
var m = (point2.Y - point1.Y) / dx;
var b = point1.Y - (m * point1.X);
return m*x + b;
}
Upvotes: 5
Reputation: 11840
I would have thought that:
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
should be
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
Gradient is the delta in Y divided by the delta in X.
Upvotes: 3
Reputation: 78890
In your posted code, you seem to have made a typo. This:
var m = (point2.Y - point1.Y) / (point2.X + point1.Y);
...should be:
var m = (point2.Y - point1.Y) / (point2.X - point1.X);
Upvotes: 12