Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linear Function: y = mx + b (2 points given) in code

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?

like image 557
Richard Avatar asked Nov 16 '13 10:11

Richard


4 Answers

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);
like image 55
Jacob Avatar answered Oct 31 '22 21:10

Jacob


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;
    }
like image 5
Shital Shah Avatar answered Oct 31 '22 20:10

Shital Shah


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.

like image 3
Baldrick Avatar answered Oct 31 '22 21:10

Baldrick


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);
like image 1
Bob Vale Avatar answered Oct 31 '22 21:10

Bob Vale