Search code examples
pythonmathsympyequationalgebra

How can I get values from NotImplementedError in sympy?


I'm using this code:

from sympy.solvers import solve
from sympy import Symbol

x = Symbol('x')

function = input("Insert function: ")

def gx(function,x):
    return solve(function,x,dict=True)

print(gx(function,x))

When I write cos(x)+x I get this error msg:

Traceback (most recent call last):
  File "/home/raulpenate/Documents/pyhton/MetodosNumericos/Tareas/testing.py", line 11, in <module>
    print(gx(function,x))
  File "/home/raulpenate/Documents/pyhton/MetodosNumericos/Tareas/testing.py", line 9, in gx
    return solve(function,x)
  File "/home/raulpenate/.local/lib/python3.9/site-packages/sympy/solvers/solvers.py", line 1095, in solve
    solution = _solve(f[0], *symbols, **flags)
  File "/home/raulpenate/.local/lib/python3.9/site-packages/sympy/solvers/solvers.py", line 1714, in _solve
    raise NotImplementedError('\n'.join([msg, not_impl_msg % f]))
NotImplementedError: multiple generators [x, cos(x)]
No algorithms are implemented to solve equation x + cos(x)

And I want to get that value from the

NotImplementedError: multiple generators [x, cos(x)]

Especifically that cos(x), how can I get that value from there?. I can't find that part in the documentation.


Solution

  • NotImplementedError will occur if sympy can't find an analytic solution. You can solve this numerically instead:

    from sympy import nsolve, cos, Symbol
    x = Symbol("x")
    nsolve(cos(x) + x, 0) # -0.739085133215161
    

    This problem won't is unlikely to have a closed form in terms of elementary functions, see https://math.stackexchange.com/questions/46934/what-is-the-solution-of-cosx-x/1174794#1174794 and https://mathworld.wolfram.com/DottieNumber.html