Plug in three coordinates to triArea(a,b,c), and it will return the area of the triangle. some common variable letters transfer into these meanings: m: slope y,c: y intercept a: x's coefficient b: y's coefficient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | def dis(a,b):
return ( (b[0]-a[0])**2 + (b[1]-a[1])**2 )**.5
def lineDis(m,y,point):
"""slope in decimal, y intercept, (x,y)"""
a = m
b = -1
c = y
m = point[0]
n = point[1]
return abs(a*m+b*n+c)/((a)**2+(b)**2)**.5
def findMY(a,b):
"""return slope(m), y intercept(y)"""
x1,y1,x2,y2 = a[0],a[1],b[0],b[1]
x1 = float(x1)
y1 = float(y1)
slope = (x2-x1)/(y2-y1)
x,y=a[0],a[1]
while x != 0:
if x < 0:
x+=1
y += slope
if x > 0:
x-=1
y-=slope
yint = y
return slope, yint
def triArea(a,b,c):
h=dis(a,b)
m,y = findMY(a,b)
b=lineDis(m,y,c)
return .5*h*b
|
No real practical use as of right now, but was a fun task to code and thought I would share. I know there are many imperfections such as naming a variable then returning it, instead of just returning the expression, but it made it easier to read the code.
or ...
In case someone wonders where the formula in the above comment comes from, it's from Heron of Alexandria. The Wikipedia article [1] shows a variant of the same formula that is more numerically stable for thin triangles (and would be the preferred way to do the computation).
or ...
providing that a,b,c are numpy arrays. This is because the area of the abc triangle is equal to 0.5 * ||AB ^ AC|| where ||.|| is the euclidian norm and ^ is the cross product, AB and AC being vectors.