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[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.

3 comments

Manfred Moitzi 14 years, 6 months ago  # | flag

or ...

import math
def area(a, b, c):
    def distance(p1, p2):
        return math.hypot(p1[0]-p2[0], p1[1]-p2[1])

    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 14 years, 6 months ago  # | flag

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).

[1] http://en.wikipedia.org/wiki/Heron's_formula
Corentin Lapeyre 12 years, 10 months ago  # | flag

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)
Python recipes (4591)
Daniel Saha's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks