I'm implementing a data processing flow in python. I'm trying to use symbolic calculations (sympy
and numpy
) as much as possible to have clear documentation consistent with the code. So when I try to get dot product and use it for real matrices (by means of lambdify
) I get something else:
import numpy as np
from sympy import *
init_printing()
A = Matrix([[1, 2], [1, 100]])
B = Matrix([[3, 4], [10, 1000]])
AA = MatrixSymbol('A',2,2)
BB = MatrixSymbol('B',2,2)
mulab = lambdify([AA,BB],AA*BB)
print(mulab(A,B))
print(A*B)
gives
[7, 1010, 406, 100020]
Matrix([[23, 2004], [1003, 100004]])
Link to the live version of code
Did anybody face similar issues? Are there workarounds known?
Thank you in advance.
lambdify
creates a function that should be used on NumPy arrays. If you pass a SymPy object to this function, the resulting behavior is undefined. If you want to evaluate SymPy expressions on SymPy expressions, just use the SymPy expression, using subs
to replace the expression.
>>> (AA*BB).subs({AA: A, BB: B}).doit()
⎡ 23 2004 ⎤
⎢ ⎥
⎣1003 100004⎦
If you have NumPy arrays, that is when you want to use lambdify:
>>> mulab(np.array([[1,2],[1,100]]), np.array([[3,4],[10,1000]]))
[[ 23 2004]
[ 1003 100004]]