0

I have this C code of an alogrithm checking whether a given point is inside a polygon. It is supposed to be correct, I also keep seeing this code in various places. However when I use it doesn't work perfectly - about 20% of the answers are wrong.

int pnpoly(int nvert, double *vertx, double *verty, double testx, double testy)
{
    int i, j, c = 0;
    for (i = 0, j = nvert-1; i < nvert; j = i++) {
        if ( ((verty[i]>testy) != (verty[j]>testy)) &&
        (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
        c = !c;
    }
    return c;
}

Maybe there is something wrong with my main function. Could somone give me a main function to check this algorthm?


This is my main function

int main(){

    double vertx[4] = {10, 10, 0, 0};
    double verty[4] = {10, 0, 10, 0};

    // for those two it returns "Inside"
    double testx = 6;
    double testy = 4;

    /* for those two it returns "Outside"
    double testx = 5;
    double testy = 4;
    */

    int result = pnpoly(4, vertx, verty, testx, testy);

    if (result) {
        printf("\nInside\n");
    }

    else {
        printf("\nOutside\n");
    }

    return 0;
}
Fryderyk
  • 1
  • 1
  • 1
    Show us an example of wrong output. – PM 77-1 May 04 '15 at 19:02
  • 1
    You might also find that an algorithm that works with a convex polygon fails with a concave one. – Weather Vane May 04 '15 at 19:03
  • 1
    You are passing doubles to a function defined to accept floats, which the compiler should have warned you about. The figure, presumed to be a square, described by vertx/verty is not a closed path. This could possibly play a role in your amazing convoluted comparison giving inconsistent answers. – Erik May 05 '15 at 16:55
  • I changed it to double, the same thing happens. Erik, do you think I should add a 5th point (10,10) to close the path? – Fryderyk May 05 '15 at 17:50

1 Answers1

1

Your polygon is self intersecting. It's normal that (5,4) is "Outside"

I think you thought that your polygon was a square, the algo works perfectly even with self intersecting polygons.

Eric Biron
  • 77
  • 7