I've checked multiple other answers for this error, but can't figure out why this is occuring.
from sympy.solvers import nsolve
from sympy import Symbol, log
x = Symbol('x')
u = nsolve(log(x/0.06) / (x-0.06) - 8,x)
print(u)
Traceback (most recent call last):
File "C:\Users\cyjac\PycharmProjects\pharmacome\scrap.py", line 5, in <module>
u = nsolve(log(x/0.06) / (x-0.06) - 8,x)
File "C:\Users\cyjac\PycharmProjects\pharmacome\venv\lib\site-packages\sympy\utilities\decorator.py", line 88, in func_wrapper
return func(*args, **kwargs)
File "C:\Users\cyjac\PycharmProjects\pharmacome\venv\lib\site-packages\sympy\solvers\solvers.py", line 2979, in nsolve
x = sympify(findroot(f, x0, **kwargs))
File "C:\Users\cyjac\PycharmProjects\pharmacome\venv\lib\site-packages\mpmath\calculus\optimization.py", line 920, in findroot
x0 = [ctx.convert(x0)]
File "C:\Users\cyjac\PycharmProjects\pharmacome\venv\lib\site-packages\mpmath\ctx_mp_python.py", line 671, in convert
return ctx._convert_fallback(x, strings)
File "C:\Users\cyjac\PycharmProjects\pharmacome\venv\lib\site-packages\mpmath\ctx_mp.py", line 634, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from x
When you use nsolve
you must provide an appropriate initial guess. For example:
expr = log(x/0.06) / (x-0.06) - 8
nsolve(expr, x, 1)
# ValueError: Could not find root within given tolerance. (64.0 > 2.16840434497100886801e-19)
# Try another starting point or tweak arguments.
This error happens quite often. Hence, when we are dealing with functions of 1 or 2 variables it is a good idea to plot the functions in order to get a proper initial guess:
Then:
nsolve(expr, x, 0.25)
# 0.225493155418687
Since you are solving a single equation, it is worth to point out the following:
nsolve(expr, x, 0.25)
by default is going to use the secant method. As seen above, it is really sensitive on the choice of the initial guess.nsolve([expr], [x], 10)
(note that I wrapped the expression and symbol into lists) is going to use the multidimensional Newton method, which uses the Jacobian. It tends to be less sensitive to the choice of the initial guess.