using fsolve to find the solution
numpy, python, scipy
Solution
Because `sqrt` returns `NaN` for negative argument, your function f(x) is not calculable for all real x. I changed your function to use `numpy.emath.sqrt()` which can output complex values when the argument < 0, and returns the absolute value of the expression.
import numpy as np
from scipy.optimize import fsolve
sqrt = np.emath.sqrt
musun = 132712000000
T = 365.25 * 86400 * 2 / 3
e = 581.2392124070273
def f(x):
return np.abs((T * musun ** 2 / (2 * np.pi)) ** (1 / 3) * sqrt(1 - x ** 2)
- sqrt(.5 * musun ** 2 / e * (1 - x ** 2)))
x = fsolve(f, 0.01)
x, f(x)
Then you can get the right result:
(array([ 1.]), array([ 121341.22302275]))
the solution is very close to the true root, but f(x) is still very large because f(x) has a very large factor: musun.
Problem
``` import numpy as np from scipy.optimize import fsolve musun = 132712000000 T = 365.25 * 86400 * 2 / 3 e = 581.2392124070273 def f(x): return ((T * musun ** 2 / (2 * np.pi)) ** (1 / 3) * np.sqrt(1 - x ** 2) - np.sqrt(.5 * musun ** 2 / e * (1 - x ** 2))) x = fsolve(f, 0.01) f(x) print x ``` What is wrong with this code? It seems to not work.