Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 31 lines
 ``` 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-a)**2 + (b-a)**2 )**.5 def lineDis(m,y,point): """slope in decimal, y intercept, (x,y)""" a = m b = -1 c = y m = point n = point 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,a,b,b x1 = float(x1) y1 = float(y1) slope = (x2-x1)/(y2-y1) x,y=a,a 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. Manfred Moitzi 12 years, 10 months ago

or ...

``````import math
def area(a, b, c):
def distance(p1, p2):
return math.hypot(p1-p2, p1-p2)

side_a = distance(a, b)
side_b = distance(b, c)
side_c = distance(c, a)
s = 0.5 * ( side_a + side_b + side_c)
return math.sqrt(s * (s - side_a) * (s - side_b) * (s - side_c))
`````` Gabriel Genellina 12 years, 10 months ago

In case someone wonders where the formula in the above comment comes from, it's from Heron of Alexandria. The Wikipedia article  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).

`````` http://en.wikipedia.org/wiki/Heron's_formula
`````` Corentin Lapeyre 11 years, 2 months ago

or ...

``````import numpy as np
from numpy.linalg import norm

def area(a, b, c) :
return 0.5 * norm( np.cross( b-a, c-a ) )
``````

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. Created by Daniel Saha on Tue, 8 Sep 2009 (MIT)

### Required Modules

• (none specified)