I'm trying to solve a system with three nonlinear equations in Python 3.8. I'm using the function sympy.nonlinsolve(). However, I received the error message "convergence to root failed; try n < 15 or maxsteps > 50".
This is my code:
import sympy as sp
x_1 = 0.0
z_1 = 1.0
x_2 = 15.81
z_2 = 0.99
x_3 = 23.8
z_3 = 0.98
r, x_m, z_m = sp.symbols('r, x_m, z_m', real=True)
Eq_1 = sp.Eq((x_1 - x_m) ** 2 (z_1 - z_m) ** 2 - r ** 2, 0)
Eq_2 = sp.Eq((x_2 - x_m) ** 2 (z_2 - z_m) ** 2 - r ** 2, 0)
Eq_3 = sp.Eq((x_3 - x_m) ** 2 (z_3 - z_m) ** 2 - r ** 2, 0)
ans = sp.nonlinsolve([Eq_1, Eq_2, Eq_3], [r, x_m, z_m])
I would welcome every help. Thanks in advance.
CodePudding user response:
I get an answer from solve
:
In [56]: sp.solve([Eq_1, Eq_2, Eq_3], [r, x_m, z_m])
Out[56]:
[(-5.71609538434502e 18, -4.80343980343979e 15, -5.71609336609336e 18), (-19222.9235141152, -4.2537
0843989772, -19221.9230434783), (19222.9235141152, -4.25370843989772, -19221.9230434783), (5.716095
38434502e 18, -4.80343980343979e 15, -5.71609336609336e 18)]
I'm not sure why nonlinsolve
works but from the large numbers in the answer I guess that this isn't well conditioned.
If you use exact rational numbers then you can get the same solution from both solve
and nonlinsolve
:
In [59]: import sympy as sp
...:
...: x_1 = 0
...: z_1 = 1
...: x_2 = sp.Rational('15.81')
...: z_2 = sp.Rational('0.99')
...: x_3 = sp.Rational('23.8')
...: z_3 = sp.Rational('0.98')
...:
...: r, x_m, z_m = sp.symbols('r, x_m, z_m', real=True)
...: Eq_1 = sp.Eq((x_1 - x_m) ** 2 (z_1 - z_m) ** 2 - r ** 2, 0)
...: Eq_2 = sp.Eq((x_2 - x_m) ** 2 (z_2 - z_m) ** 2 - r ** 2, 0)
...: Eq_3 = sp.Eq((x_3 - x_m) ** 2 (z_3 - z_m) ** 2 - r ** 2, 0)
...: ans = sp.solve([Eq_1, Eq_2, Eq_3], [r, x_m, z_m])
In [60]: ans
Out[60]:
⎡⎛-√564927076558939081 -8316 -44210423 ⎞ ⎛√564927076558939081 -8316 -44210423 ⎞⎤
⎢⎜─────────────────────, ──────, ──────────⎟, ⎜───────────────────, ──────, ──────────⎟⎥
⎣⎝ 39100 1955 2300 ⎠ ⎝ 39100 1955 2300 ⎠⎦