HWIK
HWIK

Reputation: 69

Python's sympy struggling to solve simple equality

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!

Upvotes: 0

Views: 90

Answers (2)

Patricio Loncomilla
Patricio Loncomilla

Reputation: 1103

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.

Upvotes: 4

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

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.

Upvotes: 2

Related Questions