Reputation: 43
I try to lambdify some calculated eigenvalues but I get the following error.
File "<string>", line 1, in <lambda>
AttributeError: 'Symbol' object has no attribute 'sqrt'
To avoid a namespace clash (explained in this post What causes this error (AttributeError: 'Mul' object has no attribute 'cos') in Python?) I used the following import command instead of from sympy import *
import sympy as sp
import numpy as np
def calculate_general_eigenvalues():
Y, Z = sp.symbols("Y,Z")
Rzy = sp.symbols("Rzy", positive=True)
eigenvalues = [Y + Z,Rzy*Y + sp.sqrt(Rzy*Z)]
print("eigenvalues of the system ")
print(eigenvalues[0])
print(eigenvalues[1])
lam1 = sp.lambdify((Y,Z), eigenvalues[0] ,modules=['numpy'])
lam2 = sp.lambdify((Y,Z), eigenvalues[1] ,modules=["numpy", {'sqrt': np.sqrt}])
print(lam1(1,1))
print(lam2(1,1))
return (lam1,lam2)
l1,l2 = calculate_general_eigenvalues()
I also found a second hint here (Python: SymPy lambdify abs for use with NumPy) were they include the command lambdify(x, f(x), ["numpy", {'Abs': numpy.abs}])
but it doesn't work in my code as you can see
How can I solve my problem?
Upvotes: 1
Views: 1208
Reputation:
The problem is not sqrt. Your second eigenvalue involves Rzy which you did not include among the variables when lambdifying it. Fix that, and it will work simply with modules="numpy"
. There is no need to remap sqrt: NumPy knows about sqrt, it just does not know how to apply it to a symbol such as Rzy.
lam1 = sp.lambdify((Y,Z), eigenvalues[0], modules='numpy')
lam2 = sp.lambdify((Y,Z,Rzy), eigenvalues[1], modules='numpy')
print(lam1(1,1))
print(lam2(1,1,1))
Upvotes: 2