简体   繁体   中英

how to determine point is up or down of a line in C#

I want to determine position of Point for a giving line in c#. I read this link and this link . I test them but it seems that my code is wrong. For some points close (not very close) to line it return wrong values. Here is my code:

    public static PointToLineSituation WhereIsPoint(Line l, Point p)
    {
        var x = p.X;
        var y = p.Y;
        var x1 = l.X1;
        var x2 = l.X2;
        var y1 = l.Y1;
        var y2 = l.Y2;

        var d = (x - x1) * (y1 - y2) - (y - y1) * (x2 - x1);

        if (d > 0)
            return PointToLineSituation.Up;

        if (d < 0)
            return PointToLineSituation.Down;

        return PointToLineSituation.OnLine;
    }

I want to use in graphical coordination. Is it my problem? Any help will be appreciated.

Here is an example of coordination system, an up point, and a down point as depicted below:

在此处输入图片说明

Your formula is almost (you swapped y1, y2) correct. What matters is not the result of this formula, but the sign of the result.

The accuracy on the result depends on the type the data, prefer double .

This

double d = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1);

should be enough... but numerical issues may yield a wrong result.

More about floating-point at What Every Computer Scientist Should Know About Floating-Point Arithmetic

Cross-product approach does not tell us - whether point is up or down, it just determines orientation of triplet P1-P2-P . To get needed information, you must also be sure in line direction. The simplest way - negate result sign when X2 < X1 (note that vertical line case X1=X2 is special or illegal for you).

Also note that line point differences should be consistent

var d = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1);
if (x2 < x1)
        d = -d;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM