Article Directory
Determining whether a point inside the triangle
topic
In the two-dimensional coordinate system, all values are double type, a triangle may be represented by three points,
given three points represented by triangles, give Given a point (x, Y), is determined (x, y) is in a triangle.
Solution 1: Area Method
Algorithm thinking
If a point inside the triangle ABC O, shown in Figure 9-1, then the area has an area ABC = area ABO + BCO + CAO area;
if outside the triangle ABC point O, shown in Figure 9-2, then, it has an area ABC <ABO + area area area BCO + CAO.
The Heron's formula , using the triangle side length determined area thereof .
Corresponding code
# 解法1:面积法
def getSideLength(x1, y1, x2, y2):
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
def getArea(x1, y1, x2, y2, x3, y3):
# 海伦公式:三角形边长求面积
a = getSideLength(x1, y1, x2, y2)
b = getSideLength(x1, y1, x3, y3)
c = getSideLength(x2, y2, x3, y3)
p = (a + b + c) / 2
return (p * (p - a) * (p - b) * (p - c)) ** 0.5
def isInTri1(x1, y1, x2, y2, x3, y3, x, y):
s = getArea(x1, y1, x2, y2, x3, y3)
s1 = getArea(x1, y1, x2, y2, x, y)
s2 = getArea(x1, y1, x3, y3, x, y)
s3 = getArea(x2, y2, x3, y3, x, y)
eps = 1e-6 # eps抵消浮点数计算过程的误差
# 面积相等,有可能在三角形边上,因此需要排除
if s1 < eps and s2 < eps and s3 < eps and s1 + s2 + s3 - s < eps:
return True
else:
return False
defect
Prescribing other floating-point operations , the accuracy of the results led to deviations.
We need to specify eps e.g. 1e-6
mitigation area aligned with the situation.
Solution 2: Vector
Algorithm thinking
If the point O in the triangle ABC, then if a little from the triangle counterclockwise through the process all sides, the point O always traveled in the left side. If the outside point O in the triangle ABC, this relationship is not satisfied. As shown below.
Using the vector product (cross product) determining the relative orientation of ( inside and outside ).
Note: maintaining the relative position of three points in the counterclockwise direction .
First need to with Cross product operation, its relative position is determined, if the result is greater than 0, then the switch B, C position.
Corresponding code
# 解法2:叉积法
def crossProduct(x1, y1, x2, y2):
return x1 * y2 - x2 * y1
def isInTri2(x1, y1, x2, y2, x3, y3, x, y):
# 保证三个点相对位置为逆时针方向:1 -> 2 -> 3
if crossProduct(x2 - x1, y2 - y1, x3 - x1, y3 - y1) >= 0:
x2, x3 = x3, x2
y2, y3 = y3, y2
if crossProduct(x2 - x1, y2 - y1, x - x1, y - y1) <= 0:
return False
if crossProduct(x3 - x2, y3 - y2, x - x2, y - y2) <= 0:
return False
if crossProduct(x1 - x3, y1 - y3, x - x3, y - y3) <= 0:
return False
return True
Have any questions or suggestions, please leave a message in the comments section and correct me!
We appreciate the time and effort you spend!