TypeError: cannot create mpf from x

Question:

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:UserscyjacPycharmProjectspharmacomescrap.py", line 5, in <module>
    u = nsolve(log(x/0.06) / (x-0.06) - 8,x)
  File "C:UserscyjacPycharmProjectspharmacomevenvlibsite-packagessympyutilitiesdecorator.py", line 88, in func_wrapper
    return func(*args, **kwargs)
  File "C:UserscyjacPycharmProjectspharmacomevenvlibsite-packagessympysolverssolvers.py", line 2979, in nsolve
    x = sympify(findroot(f, x0, **kwargs))
  File "C:UserscyjacPycharmProjectspharmacomevenvlibsite-packagesmpmathcalculusoptimization.py", line 920, in findroot
    x0 = [ctx.convert(x0)]
  File "C:UserscyjacPycharmProjectspharmacomevenvlibsite-packagesmpmathctx_mp_python.py", line 671, in convert
    return ctx._convert_fallback(x, strings)
  File "C:UserscyjacPycharmProjectspharmacomevenvlibsite-packagesmpmathctx_mp.py", line 634, in _convert_fallback
    raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from x
Asked By: Jacob Wheeler

||

Answers:

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:

enter image description here

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.
Answered By: Davide_sd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.