[PYTHON] Drawing a circle passing through two points

I played with a compass when I was in elementary school

It looks like a shellfish and I remember writing it all over. I drew it with python.

c.png

python


import matplotlib.pyplot as plt
import numpy as np


def cir_th2p(x,y,p1,p2,r,inv=False):
  def cal_center(p,q,r):
    pt3 = (p + q) * 0.5
    r =r**2
    l1 = (q[0] - pt3[0])**2 + (q[1] - pt3[1])**2
    d  = np.sqrt(r / l1 - 1.0)
    dy,dx= d * (q - pt3)
    pc1 = [pt3[0] + dx, pt3[1] - dy]
    pc2 = [pt3[0] - dx, pt3[1] + dy]
    return pc1,pc2

  def cir_eq(x,y,a,b,r):
    return (x-a)**2+(y-b)**2-r**2

  r=float(r)
  p1=np.array(p1).astype("float")
  p2=np.array(p2).astype("float")
  center=cal_center(p1,p2,r)
  if inv:center=center[0]
  else:center=center[1]
  return cir_eq(x,y,center[0],center[1],r)


delta = 0.1
xrange = np.arange(-3, 3, delta)
yrange = np.arange(-3, 3, delta)
X, Y = np.meshgrid(xrange,yrange)

x=np.logspace(np.log10(1) , np.log10(5) , num=5)

for i in x:
  plt.contour(X, Y, cir_th2p(X,Y,(-0.5,-0.5),(1,0),i),[0])
  plt.contour(X, Y, cir_th2p(X,Y,(-0.5,-0.5),(1,0),i,inv=True),[0])


plt.gca().set_aspect('equal', adjustable='box')
plt.savefig("c.pdf",bbox_inches='tight')

Note

cir_th2p(x,y,p1,p2,r,inv=False):

I wanted to write this function a little more elegantly, but I was in a hurry so it became a brute force implementation. I will organize it when I feel like it.

Recommended Posts

Drawing a circle passing through two points
Approximation by the least squares method of a circle with two fixed points
A sample for drawing points with PIL (Python Imaging Library).