-2

I need to return the two coordinates of intersection between a circle: f[0] = (x-h)^2 + (y-k)^2 -r^2 And a line: f[1] = y - y1 - m*(x - x1)

I have tried using fsolve, but I cannot pass the variables for (h,k,r,x1,y1), which I have. Is there a better way to solve these equations or is fsolve the standard.

Also, how do I get fsolve to return both coordinates of intersection rather than just the one.

AHB1997
  • 1
  • 2

3 Answers3

2

As @taras said in the comments in this case you can work out an exact equation.

If you substitute f[1] into f[0] and rearrange you get (if I didn't mess up my algebra)

x^2(1+m^2) + x(-2*h + 2*m*y1 - 2*(m^2)*x1 - 2*m*k) + ((y1-m*x1 - k)^2 -r^2) = 0

You can use the standard equation x = (-b +- sqrt(b^2 - 4*a*c))/(2*a) where a is the coefficient of x^2, b is the coefficient of x^1 and c is the constant.

It is worth noting that you are not guaranteed to get two real answers. You will get 2 complex answers if the line doesn't pass through the circle, two identical answers of the line touches the circle tangentially, or two real answers if the bisects the circle.

roelofs
  • 2,132
  • 20
  • 25
Spoonless
  • 561
  • 5
  • 14
1

There can be zero, one or two intersection points. Are you accounting for all three possibilities? Wolfram Alpha shows you the three cases.

The solver will give you one point at a time.

A non-linear solver will take an initial guess and iterate to convergence to the solution if it can. If you guess well, convergence will be fast. If you guess badly, you may not get a solution at all.

Searching Stack Exchange more carefully would be fruitful. Math Exchange has this.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

You can solve this problem using fsolve,

from scipy.optimize import fsolve


def f1(x, y, h, k, r):
    return (x - h)**2 + (y - k)**2 - r**2

def f2(x, y, x1, y1, m):
    return y - y1 - m * (x - x1)

# Combine the functions in a form that can be consumed by fsolve
def f(x, x1, y1, m, h, k, r):
    return (f1(x[0], x[1], h, k, r), f2(x[0], x[1], x1, y1, m))

h = 1
k = 2
r = 4

x1 = 0
y1 = 1
m = 3

# Using a made up initial starting point of (1,1)
x, y = fsolve(f, (1,1), (x1, y1, m, h, k, r))

# Verify that the solution results in zeros
print(f1(x, y, h, k, r))
print(f2(x, y, x1, y1, m))

One thing to watch for is that the f() function returns the output from f1 and f2 as a tuple because it is required to match the dimension of the input.

The result of fsolve will be one of the solutions to the equations (assuming success). The solution found will depend upon the initial condition used.

jdowner
  • 718
  • 1
  • 8
  • 21