【发布时间】:2013-10-09 06:53:53
【问题描述】:
我想对一个已定义的函数进行分段积分,该函数乘以勒让德多项式。
不幸的是,我在documentation 中找不到如何使用 x 的第 n 个勒让德多项式。我想在n = 1,..., 50 时对x 的每个勒让德多项式进行积分,所以我设置了n = np.arange(1, 51, 1)。
import numpy as np
import pylab
from scipy import integrate
n = np.arange(1, 51, 1)
def f(x):
if 0 <= x <= 1:
return 1
if -1 <= x <= 0:
return -1
我想我需要定义另一个函数,比如说u(x)。
c = []
def u(x):
c.append((2. * n + 1) / 2. * integrate.quad(f(x) * insert Legendre polynomials here, -1., 1.))
return sum(c * Legendre poly, for nn in range(1, 51))
所以我会返回一些 u(x),前 50 个项通过勒让德多项式扩展我的分段函数。
编辑 1:
如果这不能完成,我可以使用罗德里格斯公式来计算第 n 个勒让德多项式。但是,当我在 Python 中寻找计算 n 次导数时,我找不到任何有用的东西。
P_n(x) = \frac{1}{2^n n!}\frac{d^n}{dx^n}(x^2 - 1)^n
所以如果有人知道如何在 Python 中实现这样的方案,这是一个选择。
编辑 2:
使用 Saullo Castro 的回答,我有:
import numpy as np
from scipy.integrate import quad
def f(x, coef):
global p
p = np.polynomial.legendre.Legendre(coef=coef)
if 0 <= x <= 1:
return 1*p(x)
if -1 <= x <= 0:
return -1*p(x)
c = []
for n in range(1, 51):
c.append((2. * n + 1.) / 2. * quad(f, -1, 1, args=range(1,n+1))[0])
def g(x)
return sum(c * p(x) for n in range(1, 51))
但是,如果我打印 c,则值是错误的。值应为1.5, 0, -7/8, 0, ...
另外,当我绘制g时,我想做x = np.linspace(-1, 1, 500000),所以情节很详细,但c只有50。如何实现?
【问题讨论】:
标签: python numpy scipy numerical-integration