mhmhsh
mhmhsh

Reputation: 161

speed up sympy solver by reducing the precision?

The solve functionality in sympy takes some time to come up with the solution. Is it possible to speed it up by reducing the required precision (I don't really need like 15 digit after the decimal point!)?

Upvotes: 1

Views: 1862

Answers (4)

Mostafa Farzán
Mostafa Farzán

Reputation: 1003

Note: This solution helped me get around the problem. However, I have not carefully studied the docs from sympy. So use this experience-based solution at your own risk, and please improve it if possible.


Assume that we have the following code:

import sympy as sp
import time

P = sp.symbols('P')

equation = -sp.log(P/22064) - 10.494012

t0 = time.time()
ans = sp.solve(equation)
t1 = time.time()
calculation_time = t1 - t0
print('Time = %s sec' % calculation_time)

Output:

Time = 1.6773369312286377 sec

Now this slow performance is caused by the 10.494012 in the equation. If I changed it to 10.494, the calculation would be done in less than 0.3 sec. Apparently, sympy is picking up the percision from my inputs, and using it to set the percision for solver. Anyway, I don't need such percision.

So the solution is to reduce my input number percisions; i.e. replace all the numbers in my equations with limited-percision numbers. To do this automatically, I use this code:

equation = equation.replace(
                    lambda expr: expr.func == sp.numbers.Float,
                    lambda x: round(x, 3))

(Note that I had included sympy as sp.)

Upvotes: 0

aka.nice
aka.nice

Reputation: 9382

Note that having 15 printed decimals does not mean that relative error bound is 10^-15.
I encourage to analyze the effective precision before switching to single precision float.
Using an arbitrary precision package like suggested above is a good way to check how the result are altered: double number of digits and see how your result vary. Also check effect of slight variation of your inputs.

Upvotes: 1

Arcturus
Arcturus

Reputation: 548

Going with float instead of double should reduce storage by 1/2, and probably speedup by atleast factor of 2 - moving from double to single precision has benefits when you're not doing anything nonlinear or with state.

Other paralleization, and algorithm optimization techniques may also help, depending on when you show us the code.

Upvotes: 0

Abhijit
Abhijit

Reputation: 63737

You can try to use mpmath (mulch-precision math with sympy). You can set the precision to the desired level as required. Integration with sympy is traight forward, and the examples under the Advanced Mathematics sections would help you to understand its usage.

Upvotes: 1

Related Questions