Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are sympy matrices really that slow?

I just had a look on sympy and it looks like it's extremely slow. Am I doing something wrong?

from sympy.matrices import zeros
from time import time
import numpy as np

t = time()
M = zeros(500,500)
print("Time", time()-t)

t = time()
M = np.zeros((500,500))
print("Time", time()-t)

Sympy takes 1.2s and numpy takes 0.0006s. There is nothing really going on here. What takes so long?

Edit: What I was really looking for was a library where I can use fast matrix stuff (Gauss eliminiation, multiplication) on fractional values without losing precision. I am now using numpy with dtype=object and Fraction from python. It's not super fast but better than this ;)

like image 895
Wikunia Avatar asked Aug 21 '17 12:08

Wikunia


1 Answers

Sympy, as its name shows is a package for symbolic mathematics, that is (emphasis mine):

[…] a scientific area that refers to the study and development of algorithms and software for manipulating mathematical expressions and other mathematical objects.

Wikipedia

So, Sympy is not optimized for matrix calculation.

As @Michelle pointed out in the comments SymPy matrices are symbolic; each entry (even zero) is a SymPy object, sympy.core.numbers.Zero to be precise.

Also, if you look at the source code, Sympy is a pure Python package, whereas Numpy has over 50% of its codebase written in C. That probably explains the performance issue you noticed with Sympy.

like image 59
filaton Avatar answered Oct 17 '22 13:10

filaton