Skip to content

Instantly share code, notes, and snippets.

@villares
Created April 13, 2019 01:47
Show Gist options
  • Save villares/21931e3dfe17e1d91c78e2013f6a3468 to your computer and use it in GitHub Desktop.
Save villares/21931e3dfe17e1d91c78e2013f6a3468 to your computer and use it in GitHub Desktop.
Fin the third point of a triangle, knowing all the side lengths
def third_point(a, b, ac_len, bc_len):
"""
Adapted from code by Monkut https://stackoverflow.com/users/24718/monkut
at https://stackoverflow.com/questions/4001948/drawing-a-triangle-in-a-coordinate-plane-given-its-three-sides
For use with Processing Python Mode - using PVectors
Returns two point c options given:
point a, point b, ac length, bc length
"""
class NoTrianglePossible(BaseException):
pass
# To allow use of tuples, creates or recreates PVectors
a, b = PVector(*a), PVector(*b)
# check if a triangle is possible
ab_len = a.dist(b)
if ab_len > (ac_len + bc_len) or ab_len < abs(ac_len - bc_len):
raise NoTrianglePossible("The sides do not form a triangle")
# get the length to the vertex of the right triangle formed,
# by the intersection formed by circles a and b
ad_len = (ab_len ** 2 + ac_len ** 2 - bc_len ** 2) / (2.0 * ab_len)
# get the height of the line at a right angle from a_len
h = sqrt(abs(ac_len ** 2 - ad_len ** 2))
# Calculate the mid point d, needed to calculate point c(1|2)
d = PVector(a.x + ad_len * (b.x - a.x) / ab_len,
a.y + ad_len * (b.y - a.y) / ab_len)
# get point c locations
c1 = PVector(d.x + h * (b.y - a.y) / ab_len,
d.y - h * (b.x - a.x) / ab_len)
c2 = PVector(d.y + h * (b.x - a.x) / ab_len,
d.x - h * (b.y - a.y) / ab_len)
return c1, c2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment