Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Turn out right solution in Clear category for Inside Block by carel.anthonissen
from math import acos,sqrt,pi
def is_inside(polygon, point):
# Add the angles between the point and consecutive vertices on the polygon.
# The sum of the angels will add up to 2pi (360 deg) if it is on the inside,
# zero if it is on the outside, and somewhere in between on the boundary.
# Credit to Mary Rose Cook for making me aware of this method :)
def angle(v1,v2):
'''
Calculates the angle (+-pi) between two vectors (zero if one is a zero vector)
'''
dot = v1[0]*v2[0]+v1[1]*v2[1]
cross = v1[0]*v2[1]-v1[1]*v2[0]
mag = sqrt(v1[0]**2+v1[1]**2)*sqrt(v2[0]**2+v2[1]**2)
return 0 if mag == 0 else acos(dot/mag) if cross >=0 else -acos(dot/mag)
# Determine the consective vectors from the point to the vertices of the polygon.
vectors = [(p[0]-point[0],p[1]-point[1]) for p in polygon]
vectors.append(vectors[0])
# Sum the angles between consecutive vectors.
total_angle = sum((angle(*pair) for pair in zip(vectors[1:],vectors[:-1])))
# Return True if larger than zero (accounting for floating point imprecision)
return abs(total_angle)>=1e-10
May 3, 2020
Comments: