Skip to content

Instantly share code, notes, and snippets.

@wootfish
Last active August 29, 2015 14:15
Show Gist options
  • Save wootfish/74114158a367cfd8356b to your computer and use it in GitHub Desktop.
Save wootfish/74114158a367cfd8356b to your computer and use it in GitHub Desktop.
Heron's Formula with SymPy
Python 2.7.8 (default, Oct 18 2014, 12:50:18)
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sympy
>>> x1, x2, x3 = sympy.symbols('x1 x2 x3')
>>> y1, y2, y3 = sympy.symbols('y1 y2 y3')
>>>
>>> def distance(p1, p2):
... # still using the Pythagorean Theorem
... x = (p1[0] - p2[0]) ** 2
... y = (p1[1] - p2[1]) ** 2
... return sympy.sqrt(x+y)
...
>>> def herons(a, b, c):
... s = (a+b+c) / 2
... return sympy.sqrt(s*(s-a)*(s-b)*(s-c))
...
>>> s1 = distance((x1, y1), (x2, y2))
>>> s2 = distance((x1, y1), (x3, y3))
>>> s3 = distance((x2, y2), (x3, y3))
>>> A = herons(s1, s2, s3)
>>>
>>> subs = {x1:3, y1:4, x2:7, y2:10, x3:11, y3:161}
>>> A.subs(subs)
sqrt(-sqrt(13) + sqrt(22817)/2 + sqrt(24713)/2)*sqrt(sqrt(13) + sqrt(22817)/2 + sqrt(24713)/2)*sqrt(-sqrt(22817)/2 + sqrt(13) + sqrt(24713)/2)*sqrt(-sqrt(24713)/2 + sqrt(13) + sqrt(22817)/2)
>>> # Notice how none of the irreducible sqrts have been approximated.
...
>>> sympy.simplify(A.subs(subs))
290
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment