import matplotlib.
pyplot as plt
from sympy import symbols, Eq, solve
import numpy as np
from matplotlib.patches import Circle
A = (0, 5)
B = (-4, 0)
C = (3, 0)
def midpoint(p1, p2):
return [(p1[0] + p2[0])/2, (p1[1] + p2[1])/2]
def line_intersection(p1, p2, p3, p4):
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
x4, y4 = p4
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if denominator == 0:
return None
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator
x = x1 + t * (x2 - x1)
y = y1 + t * (y2 - y1)
return [x, y]
def circumcenter(A, B, C):
D = 2 * (A[0] * (B[1] - C[1]) + B[0] * (C[1] - A[1]) + C[0] * (A[1] - B[1]))
Ux = ((A[0]**2 + A[1]**2) * (B[1] - C[1]) +
(B[0]**2 + B[1]**2) * (C[1] - A[1]) +
(C[0]**2 + C[1]**2) * (A[1] - B[1])) / D
Uy = ((A[0]**2 + A[1]**2) * (C[0] - B[0]) +
(B[0]**2 + B[1]**2) * (A[0] - C[0]) +
(C[0]**2 + C[1]**2) * (B[0] - A[0])) / D
return (Ux, Uy)
def orthocenter(A, B, C):
x, y = symbols('x y')
altitude1 = Eq((B[0] - A[0]) * (y - A[1]) - (B[1] - A[1]) * (x - A[0]), 0)
altitude2 = Eq((C[0] - B[0]) * (y - B[1]) - (C[1] - B[1]) * (x - B[0]), 0)
sol = solve([altitude1, altitude2], (x, y))
return (float(sol[x]), float(sol[y]))
def incenter(A, B, C):
a = ((B[0] - C[0])**2 + (B[1] - C[1])**2)**0.5
b = ((A[0] - C[0])**2 + (A[1] - C[1])**2)**0.5
c = ((A[0] - B[0])**2 + (A[1] - B[1])**2)**0.5
Px = (a * A[0] + b * B[0] + c * C[0]) / (a + b + c)
Py = (a * A[1] + b * B[1] + c * C[1]) / (a + b + c)
return (Px, Py)
O = circumcenter(A, B, C)
H = orthocenter(A, B, C)
I = incenter(A, B, C)
D = midpoint(B, C)
F = midpoint(C, I)
E = line_intersection(O, D, A, H)
fig, ax = plt.subplots(figsize=(8, 8))
ax.plot([A[0], B[0]], [A[1], B[1]], 'k-')
ax.plot([B[0], C[0]], [B[1], C[1]], 'k-')
ax.plot([C[0], A[0]], [C[1], A[1]], 'k-')
ax.plot(*A, 'ro')
ax.plot(*B, 'bo')
ax.plot(*C, 'go')
ax.plot(*O, 'yo')
ax.plot(*H, 'co')
ax.plot(*I, 'mo')
ax.plot(*D, 'ko')
if E: ax.plot(*E, 'purple')
ax.plot(*F, 'brown')
ax.plot([A[0], O[0]], [A[1], O[1]], 'r--')
ax.plot([H[0], D[0]], [H[1], D[1]], 'b--')
ax.set_aspect('equal', adjustable='datalim')
ax.grid(True)
def get_incircle_radius(A, B, C):
a = np.linalg.norm(B - C)
b = np.linalg.norm(C - A)
c = np.linalg.norm(A - B)
s = (a + b + c) / 2
area = np.sqrt(s * (s - a) * (s - b) * (s - c))
return area / s
def get_circumcircle_radius(A, B, C):
a = np.linalg.norm(B - C)
b = np.linalg.norm(C - A)
c = np.linalg.norm(A - B)
s = (a + b + c) / 2
area = np.sqrt(s * (s - a) * (s - b) * (s - c))
return (a * b * c) / (4 * area)
A = np.array(A)
B = np.array(B)
C = np.array(C)
I = np.array(I)
O = np.array(O)
incircle_radius = get_incircle_radius(A, B, C)
incircle = Circle((I[0], I[1]), incircle_radius, fill=False, linestyle='--',
color='green')
ax.add_patch(incircle)
circumcircle_radius = get_circumcircle_radius(A, B, C)
circumcircle = Circle((O[0], O[1]), circumcircle_radius, fill=False,
linestyle='--', color='blue')
ax.add_patch(circumcircle)
plt.show()