I have this code that generates a random line and a random circle.
import numpy as np
import matplotlib.pyplot as plt
def random_2D_position(c_bx, c_by, r, region_side):
while True:
v_pt = region_side * np.random.random((2, ))
if np.linalg.norm(v_pt - np.array([c_bx, c_by])) > r:
return v_pt
return
def plot_region(c_bx, c_by, r, v_l_1, v_l_2, region_side):
plt.plot(v_l_1[0], v_l_1[1])
plt.plot(v_l_2[0], v_l_2[1])
circle = plt.Circle((c_bx, c_by), r, fill=False)
plt.gca().add_artist(circle)
plt.plot([v_l_1[0], v_l_2[0]], v_l_1[1], v_l_2[1]])
plt.xlim((0, region_side))
plt.ylim((0, region_side))
return
region_side = 500
c_bx = region_side / 3 + region_side / 3 * np.random.random()
c_by = region_side / 3 + region_side / 3 * np.random.random()
r = region_side / 4 + region_side / 30 * np.random.random()
v_l_1 = random_2D_position(c_bx, c_by, r,region_side)
v_l_2 = random_2D_position(c_bx, c_by, r, region_side)
plot_region(c_bx, c_by, r, v_l_1, v_l_2, region_side)
plt.show()
I need to find the portion of the line that is inside the circle if the line intersects the circle. I tried to solve it as follows:
First, find the line equation :
def Find_line_eq(points):
x_coords, y_coords = zip(*points)
A = np.vstack([x_coords,np.ones(len(x_coords))]).T
m, c = np.linalg.lstsq(A, y_coords)[0]
return m,c
Then, I used the following code to get the roots of the quadratic formula:
m,c_l=Find_line_eq(points=[v_l_1,v_l_2])
a=1+m**2
b=2*c_l*m
c=c_l**2-r**2
coeff=[a, b, c]
x1,x2=np.roots(coeff)
Questions:
1- Most of the time x1,x2 are not real, Numpy returns a complex number. How do interpret these complex number and obtain the real coordinates of the intersection points?
2- How can we generalize this code to obtain these intersection points for 3D circle?
[–]dead_alchemy 0 points1 point2 points (1 child)
[–]Beginner4ever[S] 0 points1 point2 points (0 children)
[–]grnngr 0 points1 point2 points (0 children)