如何访问 numpy legendre 多项式基函数

问题描述 投票:0回答:2

我不知道如何使用

numpy.polynomial.legendre
访问勒让德基函数 L_i(x)。我只能访问它们的加权和,即 c_i L_i 之和,其中 c 是常数系数。如何访问底层基本函数?我肯定错过了什么。我在下面提供了一个简单的问题示例。我手动编码了正确的多项式,并将它们与我使用 Numpy 访问的内容进行比较。显然,加权和不是所需的单独基函数。如何使用 numpy 的多项式模块使顶部图与底部图匹配?

import numpy as np
import matplotlib.pyplot as plt
f, ax = plt.subplots(2)
x = np.linspace(-1, 1, 1000)
def correct_legs(x, c):
   if c == 0: return(np.ones(len(x)))
   if c == 1: return(x)
   if c == 2: return(0.5 * (3 * x ** 2 - 1))
   if c == 3: return(0.5 * (5 * x ** 3 - 3 * x))
   if c == 4: return((1. / 8.) * (35 * x ** 4 - 30 * x ** 2 + 3))
   if c > 4 or c < 0 or type(c)!=int: return(np.nan)
for order in range(5):
   # Attempt to generate legendre polynomials with numpy
   ax[0].plot(x, np.polynomial.legendre.legval(x, np.ones(order + 1)), label=order)

   # plot propper legendre polynomials
   ax[1].plot(x, correct_legs(x, order))
ax[0].legend()
plt.savefig('simpleExample')

python numpy polynomials
2个回答
3
投票

当然,所需的解决方案取决于您希望如何使用多项式。为了“绘图”的目的,您可以查看 Legendre 系列类。它可以通过 Legendre.basis 方法生成所需域中的基函数。

对于绘图来说它工作正常

import numpy as np
import matplotlib.pyplot as plt

for order in range(5):
   # Attempt to generate legendre polynomials with numpy
   x, y = np.polynomial.legendre.Legendre.basis(order, [-1, 1]).linspace(100)
   plt.plot(x, y, label=order)

plt.legend()
plt.plot()


0
投票

这是一种方法。

from numpy import cos, arange, pi
from scipy.special import legendre
import matplotlib.pyplot as plt

def P(l,chi ) :
  polynom = legendre(l)
  return polynom(chi)


CHI = arange(-1,1, 0.01)

plt.plot(CHI, P(1,CHI), lw=2, ls = '-', color = 'k')
plt.plot(CHI, P(2,CHI), lw=2, ls = '--', color = 'g')
plt.plot(CHI, P(3,CHI), lw=2, ls = '-.', color = 'b')
plt.plot(CHI, P(4,CHI), lw=2, ls = ':', color = 'r')

plt.legend(['$P_1(\chi)$','$P_2(\chi)$','$P_3(\chi)$','$P_4(\chi)$'])
plt.title(' Polynômes de Legendre ')
plt.xlabel(' $\chi = \cos\phi$ ')
plt.ylabel(' $P_l(\chi)$ ')

这是输出 Output

© www.soinside.com 2019 - 2024. All rights reserved.