Python's sympy struggling to solve simple equality

Question:

I’m solving a problem and have a simple equality which I can solve on my calculator. Sympy, for some reason, struggles. These are the problematic lines of code:

import sympy 
V = sympy.symbols('V')
eq = sympy.Eq(1.0 - 1.0*sympy.exp(-0.00489945895346184*V), 0.98)
sol = sympy.solve(eq,V)

I get no errors or warnings, it just keeps trying to compute the solution.

Anyone able to run that? Any ideas what could be causing this issue?

Thanks!

Asked By: HWIK

||

Answers:

If you use brackets when passing arguments to solve you will get a solution:

import sympy 
V = sympy.symbols('V')
eq = sympy.Eq(1.0 - 1.0*sympy.exp(-0.00489945895346184*V), 0.98)
sol = sympy.solve([eq],[V])

Best regards.

Answered By: Patricio Loncomilla

It looks like it might take some time to compute it, depending on the complexity of the equation and the power of your computer

Output is

[0.00445593995439053]

Here is no game changer advice.
Just make sure that you have the latest version of SymPy installed. But that is the problem by design sympy.solve() and how it solving it

Answered By: di.bezrukov

The problem is that by default solve converts floats into rationals:

In [4]: eq
Out[4]: 
       -0.00489945895346184⋅V       
1.0 - ℯ                       = 0.98

In [5]: nsimplify(eq)
Out[5]: 
     -61243236918273⋅V      
     ──────────────────     
     12500000000000000    49
1 - ℯ                   = ──
                          50

Then large rational number leads to trying to solve a very high degree polynomial equation which would take a long time.

You can disable the rational conversion:

In [20]: solve(eq, V, rational=False)
Out[20]: [798.460206032342]

Also if you are only interested in numeric solutions like this it is usually faster to use SymPy’s nsolve function:

In [22]: nsolve(eq, V, 1)
Out[22]: 798.460206032342

The 1 here is an initial guess for the solution.

Answered By: Oscar Benjamin
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.