Python 计算辛函数
我找到了计算sympy函数f(.subs)的命令,但它似乎不起作用Python 计算辛函数,python,function,sympy,Python,Function,Sympy,我找到了计算sympy函数f(.subs)的命令,但它似乎不起作用 特别是,我定义了一个依赖于f的函数,我想在函数中对它求值 该函数的目标是计算给定节点和权重的高斯正交: def Gauss_Leg(f,weights,nodes,n, P = 'Legendre'): """P = Legendre by default, w = weights, x = nodes, n = degree of precision""" if P
特别是,我定义了一个依赖于f的函数,我想在函数中对它求值
该函数的目标是计算给定节点和权重的高斯正交:
def Gauss_Leg(f,weights,nodes,n, P = 'Legendre'):
"""P = Legendre by default,
w = weights,
x = nodes,
n = degree of precision"""
if P == 'Legendre':
measure = 1
a = -1
b = 1
integral = 0
for i in range(n):
integral += f.subs(x, nodes[i]) * weights[i]
print('Intergation boundaries: ', a, b)
print('integral of', f, '*', measure, '= ', integral)
return
x = sym.Symbol('x', real=True)
f = sym.exp(x)
#exact nodes and weights
[nodes,weights] = np.polynomial.legendre.leggauss(n)
Gauss_Leg(f,weights,nodes,5)
你的错误或结果是什么?乘以exp(x)的数字。因此,我尝试在每个循环中打印f.subs(x,nodes[I]),它总是返回exp(x):不发生替换。您将
x
作为两个不同的变量重用。您需要使用不同的变量名。@OscarBenjamin抱歉,我已经更改了。已编辑。在将np.polymonent.legendre.leggauss(n)
更改为np.polymonent.legendre.leggauss(5)
后,我没有收到任何错误。我也不明白你为什么需要同情。您可以创建一个Python lambda函数,并在节点[i]
处对其求值。