0

I understand how the PiP algorithm works on a high level, but I am having a little bit of a hard time understanding this implementation (from here) works, specifically what the math of second part of the if statement is doing. Thanks in advance for any help.

def point_in_polygon(polygon, point):
    """
    Raycasting Algorithm to find out whether a point is in a given polygon.
    Performs the even-odd-rule Algorithm to find out whether a point is in a given polygon.
    This runs in O(n) where n is the number of edges of the polygon.
     *
    :param polygon: an array representation of the polygon where polygon[i][0] is the x Value of the i-th point and polygon[i][1] is the y Value.
    :param point:   an array representation of the point where point[0] is its x Value and point[1] is its y Value
    :return: whether the point is in the polygon (not on the edge, just turn < into <= and > into >= for that)
    """

    # A point is in a polygon if a line from the point to infinity crosses the polygon an odd number of times
    odd = False
    # For each edge (In this case for each point of the polygon and the previous one)
    i = 0
    j = len(polygon) - 1
    while i < len(polygon) - 1:
        i = i + 1
        # If a line from the point into infinity crosses this edge
        # One point needs to be above, one below our y coordinate
        # ...and the edge doesn't cross our Y corrdinate before our x coordinate (but between our x coordinate and infinity)

        if (((polygon[i][1] > point[1]) != (polygon[j][1] > point[1])) and (point[0] < (
                (polygon[j][0] - polygon[i][0]) * (point[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1])) +
                                                                            polygon[i][0])):
            # Invert odd
            odd = not odd
        j = i
    # If the number of crossings was odd, the point is in the polygon
    return odd
Jake S
  • 13
  • 2
  • Stackoverflow is to help solve specific technical problems, not open-ended requests for code, advice, or explanations. – martineau Mar 27 '22 at 02:11
  • maybe use `print()` to see what you ahve in variables what values it compares - ie. `print( polygon[i][1], point[1], (polygon[i][1] > point[1]) )` – furas Mar 27 '22 at 04:57
  • 3
    This code is amazingly well commented, if you don't get it then I'm not sure what any of us could add that would help. – Mark Ransom Mar 27 '22 at 06:05
  • what part of the comment do you not understand? I think this is a math question not a programming one. – qwr Mar 27 '22 at 07:35
  • I understand what the algorithm is doing. You are right, @qwr, it is more of a math question. I am curious what the math in the if-statement is doing, specifically the second part, and how that determines how many times it crosses a line. – Jake S Mar 27 '22 at 15:41

0 Answers0