📜  Python – 使用递归关系的勒让德多项式

📅  最后修改于: 2021-09-22 10:44:05             🧑  作者: Mango

勒让德多项式是一种经常出现在科学和工程中的正交多项式。因此,他们的产生对这些领域至关重要。有不同的方法来评估勒让德多项式,使用生成函数、罗德里格斯公式、递推关系、Gram-Schmidt 正交化等。 最简单也是最简单的方法之一
最准确的方法之一是使用递推关系。

这里我们使用了勒让德多项式的 Bonnet 递推关系,即——

     $$nP_n(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)$$

它可以通过以下操作使用Python实现 –

我们将勒让德多项式定义为一个名为 P(n, x) 的函数,其中 n 称为多项式的阶数,x 是求值点。基本情况是如果 n 为 0,则多项式的值始终为 1,而 order 为 1 时为 x。这些是递推关系所需的种子值。
对于 n 的其他值,函数是递归定义的,直接来自 Bonnet 的递归。因此,P(n, x) 通过递归方法返回勒让德多项式的值(一个函数有效地定义为同一函数本身的其他基本情况。)

下面是Python实现——

# Legendre polynomial
def P(n, x): 
    if(n == 0):
        return 1 # P0 = 1
    elif(n == 1):
        return x # P1 = x
    else:
        return (((2 * n)-1)*x * P(n-1, x)-(n-1)*P(n-2, x))/float(n)
  
# Suppose, we want to find the value of 
# 3rd order legendre polynomial at x = 5
# We can display the value by--
  
# Driver program
n = 3
X = 5
print("The value of the polynomial at given point is:", P(n, X))
输出:
The value of the polynomial at given point is: 305.0

我们现在还可以使用 matplotlib 绘制勒让德多项式(比如从一阶到四阶)。

import matplotlib
  
# This is for use in webbrowser, can be ignored.
matplotlib.use('Agg') 
  
import matplotlib.pyplot as plt
import numpy as np
  
# Creating an array of x values
x = np.linspace(-1, 1, 200) 
  
# for which polynomial values are evaluated and plotted
for i in range(1, 5):
  
    # Labelling according to order
    plt.plot(x, P(i, x), label ="P"+str(i)) 
  
plt.legend(loc ="best")
plt.xlabel("X")
plt.ylabel("Pn")
plt.show()