In python how to get intersection point of three or more circles with or without error

rebrid :

Given three circles as

(x - x1)**2 + (y - y1)**2 = r1**2
(x - x2)**2 + (y - y2)**2 = r2**2
(x - x3)**2 + (y - y3)**2 = r3**2

How do I find in python the (x,y) point of intersection of the three circles? More precisely, how can this be robust even when the three circles do not intersect exactly in one point but none?

I have tried by using least_squares from scipy but I am not sure it's working properly since even when the circles actually intercept in one point, it gives another result.

def intersectionPoint(p1,p2,p3):

    x1, y1, dist_1 = (p1[0], p1[1], p1[2])
    x2, y2, dist_2 = (p2[0], p2[1], p2[2])
    x3, y3, dist_3 = (p3[0], p3[1], p3[2])

    def eq(g):
        x, y, r = g

        return (
            (x - x1)**2 + (y - y1)**2 - (dist_1 - r )**2,
            (x - x2)**2 + (y - y2)**2 - (dist_2 - r )**2,
            (x - x3)**2 + (y - y3)**2 - (dist_3 - r )**2)

    guess = (100, 100, 0)

    ans = scipy.optimize.least_squares(eq, guess)

    return ans
ans = intersectionPoint((0,0,9962),(7228,0,9784),(4463,3109,6251))
Jacques Gaudin :

Whilst using least_squares to solve this problem is possible, there are a few things that need changing in the code.

  • The eq function should only take a point (x,y) as a parameter since you are looking for the intersection point.

  • The return value should be (x - x1)**2 + (y - y1)**2 - dist_1**2 for each circle (that's the square of the distance to the circle).

  • The call to least_squares should be done with some additional parameters to avoid false positives, namely ftol=None, xtol=None. Please refer to the docs to understand the role of these parameters. They avoid termination by the change of the cost function and the change of the independent variables.

  • I would change the guess to a point on the first circle, so that the algorithm starts in a relevant region, guess = (x1, y1 + dist_1)

Of course, don't forget to check the success attribute to check whether the algorithm converged!

The code then becomes:

from scipy.optimize import least_squares

def intersectionPoint(p1,p2,p3):

    x1, y1, dist_1 = (p1[0], p1[1], p1[2])
    x2, y2, dist_2 = (p2[0], p2[1], p2[2])
    x3, y3, dist_3 = (p3[0], p3[1], p3[2])

    def eq(g):
        x, y = g

        return (
            (x - x1)**2 + (y - y1)**2 - dist_1**2,
            (x - x2)**2 + (y - y2)**2 - dist_2**2,
            (x - x3)**2 + (y - y3)**2 - dist_3**2)

    guess = (x1, y1 + dist_1)

    ans = least_squares(eq, guess, ftol=None, xtol=None)

    return ans

ans = intersectionPoint((0,0,1),(2,0,1),(1,-1,1))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=336703&siteId=1