简体   繁体   English

sympy:Lambdify 不转换 sqrt 表达式

[英]sympy: Lambdify doesn't convert sqrt expression

I try to lambdify some calculated eigenvalues but I get the following error.我尝试对一些计算出的特征值进行lambdify,但出现以下错误。

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 *为了避免命名空间冲突(在这篇文章中解释了什么导致此错误(AttributeError: 'Mul' object has no attribute 'cos') in Python? )我使用了以下导入命令而不是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 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如您所见,在我的代码中不起作用

How can I solve my problem?我该如何解决我的问题?

The problem is not sqrt. 问题不在于sqrt。 Your second eigenvalue involves Rzy which you did not include among the variables when lambdifying it. 您的第二个特征值涉及Rzy,在对它进行lambdized时未将其包括在变量中。 Fix that, and it will work simply with modules="numpy" . 解决此问题,它将仅与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. 无需重新映射sqrt:NumPy知道sqrt,只是不知道如何将其应用于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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM