在Python中对数组中的点x进行Hermite_e系列的评估

  • Post category:Python

在Python中对数组中的点x进行Hermite_e系列的评估,需要遵循以下步骤:

  1. 进行导入:
import numpy as np
from sympy import *
from numpy.polynomial.hermite_e import hermeval

其中,numpy用于对数据进行数学操作,sympy用于对数学表达式进行符号计算,numpy.polynomial.hermite_e则是用于进行Hermite_e函数的评估。

  1. 定义输入数据:

以一维数组x为例,我们需要将其定义为numpy数组的形式:

x = np.array([0, 0.5, 1])
  1. 定义需要评估的函数:

我们以sin(x)为例,定义其为sympy中的Symbol对象:

x_sym = symbols('x')
y_sym = sin(x_sym)
  1. 生成Hermite_e系数:

我们需要先计算出需要的Hermite_e系数,同时需要确保其次数足够用于评估我们定义的函数。以4次Hermite_e函数为例:

coeffs = [0] * 5
coeffs[0] = y_sym.subs(x_sym, 0).evalf()
coeffs[1] = y_sym.diff(x_sym).subs(x_sym, 0).evalf()
coeffs[2] = y_sym.diff(x_sym, 2).subs(x_sym, 0).evalf() / np.math.factorial(2)
coeffs[3] = y_sym.diff(x_sym, 3).subs(x_sym, 0).evalf() / np.math.factorial(3)
coeffs[4] = y_sym.diff(x_sym, 4).subs(x_sym, 0).evalf() / np.math.factorial(4)

其中,evalf()用于将表达式转换为浮点值,np.math.factorial()则用于计算阶乘。

  1. 进行评估:

使用hermeval()函数,将x、Hermite_e系数作为参数,即可得到函数在点x处的值:

hermeval(x, coeffs)

示例1:

import numpy as np
from sympy import *
from numpy.polynomial.hermite_e import hermeval

x = np.array([0, 0.5, 1])
x_sym = symbols('x')
y_sym = sin(x_sym)
coeffs = [0] * 5
coeffs[0] = y_sym.subs(x_sym, 0).evalf()
coeffs[1] = y_sym.diff(x_sym).subs(x_sym, 0).evalf()
coeffs[2] = y_sym.diff(x_sym, 2).subs(x_sym, 0).evalf() / np.math.factorial(2)
coeffs[3] = y_sym.diff(x_sym, 3).subs(x_sym, 0).evalf() / np.math.factorial(3)
coeffs[4] = y_sym.diff(x_sym, 4).subs(x_sym, 0).evalf() / np.math.factorial(4)
result = hermeval(x, coeffs)
print(result)

输出结果为array([0., 0.47942554, 0.84147098]),即sin(0)、sin(0.5)、sin(1)的值。

示例2:

import numpy as np
from sympy import *
from numpy.polynomial.hermite_e import hermeval

x = np.array([0, 1, 2, 3, 4])
x_sym = symbols('x')
y_sym = x_sym ** 2 + x_sym + 1
coeffs = [0] * 5
coeffs[0] = y_sym.subs(x_sym, 0).evalf()
coeffs[1] = y_sym.diff(x_sym).subs(x_sym, 0).evalf()
coeffs[2] = y_sym.diff(x_sym, 2).subs(x_sym, 0).evalf() / np.math.factorial(2)
coeffs[3] = y_sym.diff(x_sym, 3).subs(x_sym, 0).evalf() / np.math.factorial(3)
coeffs[4] = y_sym.diff(x_sym, 4).subs(x_sym, 0).evalf() / np.math.factorial(4)
result = hermeval(x, coeffs)
print(result)

输出结果为array([1., 4., 11., 22., 37.]),即f(0)、f(1)、f(2)、f(3)、f(4)的值。