Skip to content

Instantly share code, notes, and snippets.

@uwezi
Created May 29, 2024 22:54
Show Gist options
  • Save uwezi/b563abd9350578220ae89bf4bf1fc1ec to your computer and use it in GitHub Desktop.
Save uwezi/b563abd9350578220ae89bf4bf1fc1ec to your computer and use it in GitHub Desktop.
[triangle centers] calculate different center points for a triangle. #geometry #python
def H(z,a,b,l):
'''
from https://codegolf.stackexchange.com/questions/11767/the-centers-of-a-triangle
1 - Incenter
2 - Centroid
3 - Circumcenter
4 - Orthocenter
5 - Equation of Euler Line
(if the Euler Line is vertical, output the `x` value of the line
(e.g. output `5` if the equation of the line is `x = 5`))
'''
c=complex
T=lambda A,B: abs(c(*A)-c(*B))
d=T(z,a)
e=T(z,b)
f=T(a,b)
g=[((a[0]+b[0])/2,(a[1]+b[1])/2)
for a,b in[[a,b],[z,a],[b,z]]
]
E=(z[0]+a[0]+b[0])/3
F=(z[1]+a[1]+b[1])/3
m=lambda f:[(a,0) if (b[1][0]-b[0][0])==0 else (a,-1/((b[1][1]-b[0][1])/(b[1][0]-b[0][0])))if(b[1][1]-b[0][1])else''for a,b in zip(f,[[a,b],[z,a],[b,z]])]
i=[u for u in m(g)if u!='']
C=i[0][1]
D=i[0][0][1]-(C*i[0][0][0])
A=i[1][1]
B=i[1][0][1]-(A*i[1][0][0])
G=(B-D)/(C-A)
H=C*G+D
j=[u for u in m([z,b,a])if u!='']
C=j[0][1]
D=j[0][0][1]-(C*j[0][0][0])
A=j[1][1]
B=j[1][0][1]-(A*j[1][0][0])
I=(B-D)/(C-A)
J=C*I+D
K,L=[((d*b[o])+(e*a[o])+(f*z[o]))/sum([d,e,f]) for o in [0,1]]
a=(H-J)/(G-I) if (G-I) else ''
b=H-(a*G) if a!=''else G
print(['',(K,L),(E,F),(G,H),(I,J),[b,'%sx+%s'%(a,b)][a!='']][l])
return (I,J)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment