0

I found a code to check if a point is inside a polygon from here but it seems not to be working even though the comments say it works.

#include <stdio.h>

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);

int pnpoly(int nvert, float *vertx, float *verty, float testx, float 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;
}
int main()
{
    int numb = 4;
    float lat[4] = {1.0,2.0,1.0,2.0};
    float lon[4] = {1.0,1.0,2.0,2.0};
    float mex = 1.5;
    float mey = 1.5;


    int a = pnpoly(numb, lat, lon, mex, mey);
    printf("%d", a);


    return 0;
}

I tried the code with some test points but it does not work correctly, any suggestions?

Narek
  • 55
  • 1
  • 5
  • Have you made *any* attempt to debug this code? – Scott Hunter Feb 15 '19 at 17:00
  • what is the goal of `j = i++` in the _for_ ? – bruno Feb 15 '19 at 17:02
  • @bruno I guess it is to index the adjacent vertex. `j` starts at the last vertex. – Weather Vane Feb 15 '19 at 17:03
  • Aside: you should avoid divisions as it's a matter of time until you get a divide by 0. Problems like this can be solved by cross-multiplying. – Weather Vane Feb 15 '19 at 17:05
  • @WeatherVane if you say, the `c =!c;` is also so strange for me, but I miss the theory ^^ – bruno Feb 15 '19 at 17:08
  • [Edit] the question and tell us why you think it is not working. How do you know this? SO is a terrible debugger, as well. See: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –  Feb 15 '19 at 17:52

1 Answers1

1

Your coordinates were wrong:

#include <stdio.h>

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);

int pnpoly(int nvert, float *vertx, float *verty, float testx, float 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;
}
int main()
{
    int numb = 4;
    float lat[4] = {1.0, 2.0, 2.0, 1.0}; // was 1.0, 2.0, 1.0, 2.0
    float lon[4] = {1.0, 1.0, 2.0, 2.0};
    float mex = 1.5;
    float mey = 1.5;

    int a = pnpoly(numb, lat, lon, mex, mey);
    printf("%d\n", a);

    return 0;
}

And thus the point was correctly classified as outside.

I have only now tested with a few points and the algorithm seems to work. However, I will not completely check it.

Lukas Koestler
  • 328
  • 3
  • 10