NumPy-源码解析-三十二-

97 阅读1小时+

NumPy 源码解析(三十二)

.\numpy\numpy\polynomial\chebyshev.pyi

# 导入必要的类型引用
from typing import Any
# 导入必要的函数和类
from numpy import int_
from numpy.typing import NDArray
from numpy.polynomial._polybase import ABCPolyBase
from numpy.polynomial.polyutils import trimcoef

# 指定在模块中公开的对象列表
__all__: list[str]

# 将 trimcoef 函数赋值给 chebtrim 变量
chebtrim = trimcoef

# 定义 poly2cheb 函数,将多项式转换为切比雪夫多项式
def poly2cheb(pol): ...

# 定义 cheb2poly 函数,将切比雪夫多项式转换为多项式
def cheb2poly(c): ...

# 定义切比雪夫多项式的定义域、零多项式和单位多项式的数组
chebdomain: NDArray[int_]
chebzero: NDArray[int_]
chebone: NDArray[int_]
chebx: NDArray[int_]

# 定义生成线性切比雪夫多项式的函数
def chebline(off, scl): ...

# 定义根据给定根生成切比雪夫多项式的函数
def chebfromroots(roots): ...

# 定义切比雪夫多项式加法运算
def chebadd(c1, c2): ...

# 定义切比雪夫多项式减法运算
def chebsub(c1, c2): ...

# 定义切比雪夫多项式乘以 x 的函数
def chebmulx(c): ...

# 定义切比雪夫多项式乘法运算
def chebmul(c1, c2): ...

# 定义切比雪夫多项式除法运算
def chebdiv(c1, c2): ...

# 定义切比雪夫多项式的幂运算
def chebpow(c, pow, maxpower=...): ...

# 定义切比雪夫多项式的导数计算
def chebder(c, m=..., scl=..., axis=...): ...

# 定义切比雪夫多项式的积分计算
def chebint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...

# 定义对切比雪夫多项式进行求值的函数
def chebval(x, c, tensor=...): ...

# 定义在二维平面上对切比雪夫多项式进行求值的函数
def chebval2d(x, y, c): ...

# 定义在二维平面上生成切比雪夫网格的函数
def chebgrid2d(x, y, c): ...

# 定义在三维空间上对切比雪夫多项式进行求值的函数
def chebval3d(x, y, z, c): ...

# 定义在三维空间上生成切比雪夫网格的函数
def chebgrid3d(x, y, z, c): ...

# 定义生成切比雪夫范德蒙德矩阵的函数
def chebvander(x, deg): ...

# 定义在二维平面上生成切比雪夫范德蒙德矩阵的函数
def chebvander2d(x, y, deg): ...

# 定义在三维空间上生成切比雪夫范德蒙德矩阵的函数
def chebvander3d(x, y, z, deg): ...

# 定义使用最小二乘法拟合数据生成切比雪夫多项式的函数
def chebfit(x, y, deg, rcond=..., full=..., w=...): ...

# 定义生成切比雪夫多项式的伴随矩阵的函数
def chebcompanion(c): ...

# 定义计算切比雪夫多项式的根的函数
def chebroots(c): ...

# 定义使用插值法生成切比雪夫多项式的函数
def chebinterpolate(func, deg, args = ...): ...

# 定义生成切比雪夫-高斯积分节点和权重的函数
def chebgauss(deg): ...

# 定义计算切比雪夫多项式在给定点的权重的函数
def chebweight(x): ...

# 定义生成一维切比雪夫积分节点的函数
def chebpts1(npts): ...

# 定义生成二维切比雪夫积分节点的函数
def chebpts2(npts): ...

# 定义一个继承自 ABCPolyBase 类的切比雪夫多项式类
class Chebyshev(ABCPolyBase):
    # 根据函数插值生成切比雪夫多项式的类方法
    @classmethod
    def interpolate(cls, func, deg, domain=..., args = ...): ...
    
    # 切比雪夫多项式的定义域属性
    domain: Any
    # 切比雪夫多项式的窗口属性
    window: Any
    # 切比雪夫多项式的基函数名称属性
    basis_name: Any

.\numpy\numpy\polynomial\hermite.py

# 导入NumPy库并指定别名np,导入NumPy的线性代数模块别名为la
import numpy as np
import numpy.linalg as la
# 从NumPy库中的数组工具模块导入normalize_axis_index函数
from numpy.lib.array_utils import normalize_axis_index

# 从当前目录下的polyutils模块导入trimcoef函数并赋给hermtrim变量
from . import polyutils as pu

# 从当前目录下的_polybase模块导入ABCPolyBase类
from ._polybase import ABCPolyBase

# 定义__all__列表,列出模块中公开的函数和类的名称
__all__ = [
    'hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd',
    'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval',
    'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots',
    'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite',
    'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d',
    'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight']

# 将pu.trimcoef函数赋给hermtrim变量,用于多项式系数的裁剪
hermtrim = pu.trimcoef


def poly2herm(pol):
    """
    poly2herm(pol)

    Convert a polynomial to a Hermite series.

    Convert an array representing the coefficients of a polynomial (relative
    to the "standard" basis) ordered from lowest degree to highest, to an
    array of the coefficients of the equivalent Hermite series, ordered
    from lowest to highest degree.

    Parameters
    ----------
    pol : array_like
        1-D array containing the polynomial coefficients

    Returns
    -------
    c : ndarray
        1-D array containing the coefficients of the equivalent Hermite
        series.

    See Also
    --------
    herm2poly

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.hermite import poly2herm
    >>> poly2herm(np.arange(4))
    array([1.   ,  2.75 ,  0.5  ,  0.375])

    """
    # 将输入的多项式系数数组转换为NumPy的多项式系数表示形式
    [pol] = pu.as_series([pol])
    # 获取多项式的最高次数
    deg = len(pol) - 1
    # 初始化结果为0
    res = 0
    # 从最高次数到最低次数迭代
    for i in range(deg, -1, -1):
        # 逐步构建Hermite系数,hermadd为Hermite系数的加法操作,hermmulx为乘以x的操作
        res = hermadd(hermmulx(res), pol[i])
    # 返回函数中定义的变量 res
    return res
def herm2poly(c):
    """
    Convert a Hermite series to a polynomial.

    Convert an array representing the coefficients of a Hermite series,
    ordered from lowest degree to highest, to an array of the coefficients
    of the equivalent polynomial (relative to the "standard" basis) ordered
    from lowest to highest degree.

    Parameters
    ----------
    c : array_like
        1-D array containing the Hermite series coefficients, ordered
        from lowest order term to highest.

    Returns
    -------
    pol : ndarray
        1-D array containing the coefficients of the equivalent polynomial
        (relative to the "standard" basis) ordered from lowest order term
        to highest.

    See Also
    --------
    poly2herm

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.hermite import herm2poly
    >>> herm2poly([ 1.   ,  2.75 ,  0.5  ,  0.375])
    array([0., 1., 2., 3.])

    """
    from .polynomial import polyadd, polysub, polymulx  # 导入所需的多项式运算函数

    [c] = pu.as_series([c])  # 将输入的系数转换为数组表示
    n = len(c)  # 系数数组的长度
    if n == 1:
        return c  # 如果数组长度为1,直接返回该数组作为多项式系数
    if n == 2:
        c[1] *= 2  # 如果数组长度为2,将第二项乘以2
        return c  # 返回修改后的系数数组作为多项式系数
    else:
        c0 = c[-2]  # 初始化 c0 为倒数第二项系数
        c1 = c[-1]  # 初始化 c1 为最后一项系数
        # i 是当前 c1 的次数
        for i in range(n - 1, 1, -1):
            tmp = c0
            c0 = polysub(c[i - 2], c1*(2*(i - 1)))  # 更新 c0 的值
            c1 = polyadd(tmp, polymulx(c1)*2)  # 更新 c1 的值
        return polyadd(c0, polymulx(c1)*2)  # 返回多项式的系数数组


"""
These are constant arrays are of integer type so as to be compatible
with the widest range of other types, such as Decimal.
"""

# Hermite
hermdomain = np.array([-1., 1.])  # Hermite 多项式的定义域

# Hermite coefficients representing zero.
hermzero = np.array([0])  # 表示零的 Hermite 系数

# Hermite coefficients representing one.
hermone = np.array([1])  # 表示一的 Hermite 系数

# Hermite coefficients representing the identity x.
hermx = np.array([0, 1/2])  # 表示恒等函数 x 的 Hermite 系数


def hermline(off, scl):
    """
    Hermite series whose graph is a straight line.

    Parameters
    ----------
    off, scl : scalars
        The specified line is given by ``off + scl*x``.

    Returns
    -------
    y : ndarray
        This module's representation of the Hermite series for
        ``off + scl*x``.

    See Also
    --------
    numpy.polynomial.polynomial.polyline
    numpy.polynomial.chebyshev.chebline
    numpy.polynomial.legendre.legline
    numpy.polynomial.laguerre.lagline
    numpy.polynomial.hermite_e.hermeline

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermline, hermval
    >>> hermval(0,hermline(3, 2))
    3.0
    >>> hermval(1,hermline(3, 2))
    5.0

    """
    if scl != 0:
        return np.array([off, scl/2])  # 如果斜率不为零,返回 Hermite 系数数组
    else:
        return np.array([off])  # 如果斜率为零,返回 Hermite 系数数组


def hermfromroots(roots):
    """
    Generate a Hermite series with given roots.

    The function returns the coefficients of the polynomial

    .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),

    ```
    # 返回 Hermite 多项式的系数,这些系数定义了一个多项式,其根由参数 `roots` 指定
    # 如果一个零点具有多重度 n,则它在 `roots` 中必须出现 n 次
    # 例如,如果 2 是一个三重根,3 是一个双重根,则 `roots` 可能是 [2, 2, 2, 3, 3]
    # 根可以以任何顺序出现

    # 如果返回的系数是 `c`,则 Hermite 多项式 `p(x)` 定义为:
    # p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x)
    # 其中 `H_i(x)` 是 Hermite 多项式的基函数

    # 最后一项的系数通常不为 1,即使 Hermite 多项式是首一的(monic)

    # 参数:
    # roots : array_like
    #     包含根的序列

    # 返回:
    # out : ndarray
    #     1-D 系数数组。如果所有的根都是实数,则 `out` 是实数组;如果其中一些根是复数,则 `out` 是复数数组,
    #     即使结果中的所有系数都是实数(参见下面的示例)

    # 参见:
    # numpy.polynomial.polynomial.polyfromroots
    # numpy.polynomial.legendre.legfromroots
    # numpy.polynomial.laguerre.lagfromroots
    # numpy.polynomial.chebyshev.chebfromroots
    # numpy.polynomial.hermite_e.hermefromroots

    # 示例:
    # >>> from numpy.polynomial.hermite import hermfromroots, hermval
    # >>> coef = hermfromroots((-1, 0, 1))
    # >>> hermval((-1, 0, 1), coef)
    # array([0.,  0.,  0.])
    # >>> coef = hermfromroots((-1j, 1j))
    # >>> hermval((-1j, 1j), coef)
    # array([0.+0.j, 0.+0.j])

    # 返回通过 `_fromroots` 函数计算得到的 Hermite 多项式的系数
    return pu._fromroots(hermline, hermmul, roots)
# 定义函数 hermadd,用于将两个 Hermite 级数相加
def hermadd(c1, c2):
    # 调用私有函数 _add,返回两个 Hermite 级数的和
    return pu._add(c1, c2)


# 定义函数 hermsub,用于从一个 Hermite 级数中减去另一个 Hermite 级数
def hermsub(c1, c2):
    # 调用私有函数 _sub,返回两个 Hermite 级数的差
    return pu._sub(c1, c2)


# 定义函数 hermmulx,用于将 Hermite 级数乘以自变量 x
def hermmulx(c):
    """
    Multiply a Hermite series by x.

    Multiply the Hermite series `c` by x, where x is the independent
    variable.

    Parameters
    ----------
    c : array_like
        1-D array of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the result of the multiplication.

    See Also
    --------
    hermadd, hermsub, hermmul, hermdiv, hermpow

    Notes
    -----
    The multiplication uses the recursion relationship for Hermite
    polynomials in the form

    .. math::

        xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermmulx
    >>> hermmulx([1, 2, 3])
    array([2. , 6.5, 1. , 1.5])

    """
    # 使用 pu.as_series([c]) 将 c 转换为 Hermite 级数,并返回其修剪版本
    [c] = pu.as_series([c])
    # 如果列表 c 的长度为 1 并且唯一的元素是 0,则直接返回 c,因为零系列需要特殊处理
    if len(c) == 1 and c[0] == 0:
        return c

    # 创建一个新的 NumPy 数组 prd,长度比 c 多 1,数据类型与 c 相同
    prd = np.empty(len(c) + 1, dtype=c.dtype)
    
    # 计算 prd 的第一个元素,设为 c 的第一个元素乘以 0
    prd[0] = c[0]*0
    
    # 计算 prd 的第二个元素,设为 c 的第一个元素除以 2
    prd[1] = c[0]/2
    
    # 遍历列表 c 的每个元素(从第二个到最后一个)
    for i in range(1, len(c)):
        # 计算 prd 的第 i+1 个元素,设为 c 的第 i 个元素除以 2
        prd[i + 1] = c[i]/2
        
        # 计算 prd 的第 i-1 个元素,加上 c 的第 i 个元素乘以 i
        prd[i - 1] += c[i]*i
    
    # 返回计算后的数组 prd
    return prd
def hermmul(c1, c2):
    """
    Multiply one Hermite series by another.

    Returns the product of two Hermite series `c1` * `c2`.  The arguments
    are sequences of coefficients, from lowest order "term" to highest,
    e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Of Hermite series coefficients representing their product.

    See Also
    --------
    hermadd, hermsub, hermmulx, hermdiv, hermpow

    Notes
    -----
    In general, the (polynomial) product of two C-series results in terms
    that are not in the Hermite polynomial basis set.  Thus, to express
    the product as a Hermite series, it is necessary to "reproject" the
    product onto said basis set, which may produce "unintuitive" (but
    correct) results; see Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermmul
    >>> hermmul([1, 2, 3], [0, 1, 2])
    array([52.,  29.,  52.,   7.,   6.])

    """
    # 将输入的系数序列转换为标准的 Hermite 系列格式
    [c1, c2] = pu.as_series([c1, c2])

    # 选择较短的系数序列进行计算
    if len(c1) > len(c2):
        c = c2
        xs = c1
    else:
        c = c1
        xs = c2

    # 根据系数序列的长度选择不同的计算方式
    if len(c) == 1:
        # 如果系数序列长度为1,直接计算乘积
        c0 = c[0]*xs
        c1 = 0
    elif len(c) == 2:
        # 如果系数序列长度为2,按照二阶 Hermite 系列的计算方式进行乘积计算
        c0 = c[0]*xs
        c1 = c[1]*xs
    else:
        # 对于长度大于2的系数序列,采用递推计算 Hermite 系列的乘积
        nd = len(c)
        c0 = c[-2]*xs
        c1 = c[-1]*xs
        for i in range(3, len(c) + 1):
            tmp = c0
            nd = nd - 1
            c0 = hermsub(c[-i]*xs, c1*(2*(nd - 1)))
            c1 = hermadd(tmp, hermmulx(c1)*2)

    # 返回计算得到的 Hermite 系列乘积
    return hermadd(c0, hermmulx(c1)*2)


def hermdiv(c1, c2):
    """
    Divide one Hermite series by another.

    Returns the quotient-with-remainder of two Hermite series
    `c1` / `c2`.  The arguments are sequences of coefficients from lowest
    order "term" to highest, e.g., [1,2,3] represents the series
    ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    [quo, rem] : ndarrays
        Of Hermite series coefficients representing the quotient and
        remainder.

    See Also
    --------
    hermadd, hermsub, hermmulx, hermmul, hermpow

    Notes
    -----
    In general, the (polynomial) division of one Hermite series by another
    results in quotient and remainder terms that are not in the Hermite
    polynomial basis set.  Thus, to express these results as a Hermite
    series, it is necessary to "reproject" the results onto the Hermite
    basis set, which may produce "unintuitive" (but correct) results; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermdiv
    >>> hermdiv([ 52.,  29.,  52.,   7.,   6.], [0, 1, 2])
    (array([1., 2., 3.]), array([0.]))

    """
    # 将输入的系数序列转换为标准的 Hermite 系列格式
    [c1, c2] = pu.as_series([c1, c2])

    # 计算商和余数
    quo, rem = np.polydiv(c1, c2)

    # 返回计算得到的 Hermite 系列商和余数
    return quo, rem
    # 调用 hermdiv 函数,传入参数 [54., 31., 52., 7., 6.] 和 [0, 1, 2]
    # 返回结果为 (array([1., 2., 3.]), array([2., 2.]))
    >>> hermdiv([ 54.,  31.,  52.,   7.,   6.], [0, 1, 2])
    (array([1., 2., 3.]), array([2., 2.]))

    # 调用 hermdiv 函数,传入参数 [53., 30., 52., 7., 6.] 和 [0, 1, 2]
    # 返回结果为 (array([1., 2., 3.]), array([1., 1.]))
    >>> hermdiv([ 53.,  30.,  52.,   7.,   6.], [0, 1, 2])
    (array([1., 2., 3.]), array([1., 1.]))

    """
    # 返回 pu._div(hermmul, c1, c2) 的结果
    return pu._div(hermmul, c1, c2)
# 定义函数 hermder,用于对 Hermite 级数进行求导操作
def hermder(c, m=1, scl=1, axis=0):
    """
    Differentiate a Hermite series.

    Returns the Hermite series coefficients `c` differentiated `m` times
    along `axis`.  At each iteration the result is multiplied by `scl` (the
    scaling factor is for use in a linear change of variable). The argument
    `c` is an array of coefficients from low to high degree along each
    axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2``
    while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) +
    2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is
    ``y``.

    Parameters
    ----------
    c : array_like
        Array of Hermite series coefficients. If `c` is multidimensional the
        different axis correspond to different variables with the degree in
        each axis given by the corresponding index.
    m : int, optional
        Number of derivatives taken, must be non-negative. (Default: 1)
    scl : scalar, optional
        Each differentiation is multiplied by `scl`.  The end result is
        multiplication by ``scl**m``.  This is for use in a linear change of
        variable. (Default: 1)
    axis : int, optional
        Axis over which the derivative is taken. (Default: 0).

        .. versionadded:: 1.7.0

    Returns
    -------
    der : ndarray
        Hermite series of the derivative.

    See Also
    --------
    hermint

    Notes
    -----
    In general, the result of differentiating a Hermite series does not
    resemble the same operation on a power series. Thus the result of this
    function may be "unintuitive," albeit correct; see Examples section
    below.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermder
    >>> hermder([ 1. ,  0.5,  0.5,  0.5])
    array([1., 2., 3.])
    >>> hermder([-0.5,  1./2.,  1./8.,  1./12.,  1./16.], m=2)
    array([1., 2., 3.])

    """
    # 将输入的 Hermite 系数数组转换为至少为一维的 numpy 数组,并进行深拷贝
    c = np.array(c, ndmin=1, copy=True)
    # 如果输入数组的数据类型是布尔型或整数型,则转换为双精度浮点型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    # 将 m 转换为整数,表示导数的阶数 cnt
    cnt = pu._as_int(m, "the order of derivation")
    # 将 axis 转换为整数,表示操作的轴向 iaxis
    iaxis = pu._as_int(axis, "the axis")
    # 如果导数阶数 cnt 小于 0,则抛出数值错误异常
    if cnt < 0:
        raise ValueError("The order of derivation must be non-negative")
    # 根据数组 c 的维度调整轴向 iaxis,确保其在有效范围内
    iaxis = normalize_axis_index(iaxis, c.ndim)

    # 如果导数阶数 cnt 为 0,则直接返回数组 c
    if cnt == 0:
        return c

    # 将轴向 iaxis 移动到数组 c 的第一个维度
    c = np.moveaxis(c, iaxis, 0)
    # 获取数组 c 的长度
    n = len(c)
    # 如果导数阶数 cnt 大于等于数组长度 n,则将数组 c 的前一项乘以 0
    if cnt >= n:
        c = c[:1]*0
    else:
        # 否则,进行 cnt 次导数运算
        for i in range(cnt):
            n = n - 1
            # 将数组 c 每一项乘以缩放因子 scl
            c *= scl
            # 创建一个空的数组 der,用于存储导数结果
            der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
            # 计算每一阶导数的值并存储在 der 中
            for j in range(n, 0, -1):
                der[j - 1] = (2*j)*c[j]
            # 将计算得到的导数结果赋值给数组 c
            c = der
    # 将第一个维度移动回原来的轴向 iaxis
    c = np.moveaxis(c, 0, iaxis)
    # 返回最终的导数结果数组 c
    return c
# 定义函数 hermint,用于对 Hermite 级数进行积分处理
def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
    """
    Integrate a Hermite series.

    Returns the Hermite series coefficients `c` integrated `m` times from
    `lbnd` along `axis`. At each iteration the resulting series is
    **multiplied** by `scl` and an integration constant, `k`, is added.
    The scaling factor is for use in a linear change of variable.  ("Buyer
    beware": note that, depending on what one is doing, one may want `scl`
    to be the reciprocal of what one might expect; for more information,
    see the Notes section below.)  The argument `c` is an array of
    coefficients from low to high degree along each axis, e.g., [1,2,3]
    represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
    represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
    2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.

    Parameters
    ----------
    c : array_like
        Array of Hermite series coefficients. If c is multidimensional the
        different axis correspond to different variables with the degree in
        each axis given by the corresponding index.
    m : int, optional
        Order of integration, must be positive. (Default: 1)
    k : {[], list, scalar}, optional
        Integration constant(s).  The value of the first integral at
        ``lbnd`` is the first value in the list, the value of the second
        integral at ``lbnd`` is the second value, etc.  If ``k == []`` (the
        default), all constants are set to zero.  If ``m == 1``, a single
        scalar can be given instead of a list.
    lbnd : scalar, optional
        The lower bound of the integral. (Default: 0)
    scl : scalar, optional
        Following each integration the result is *multiplied* by `scl`
        before the integration constant is added. (Default: 1)
    axis : int, optional
        Axis over which the integral is taken. (Default: 0).

        .. versionadded:: 1.7.0

    Returns
    -------
    S : ndarray
        Hermite series coefficients of the integral.

    Raises
    ------
    ValueError
        If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
        ``np.ndim(scl) != 0``.

    See Also
    --------
    hermder

    Notes
    -----
    Note that the result of each integration is *multiplied* by `scl`.
    Why is this important to note?  Say one is making a linear change of
    variable :math:`u = ax + b` in an integral relative to `x`.  Then
    :math:`dx = du/a`, so one will need to set `scl` equal to
    :math:`1/a` - perhaps not what one would have first thought.

    Also note that, in general, the result of integrating a C-series needs
    to be "reprojected" onto the C-series basis set.  Thus, typically,
    the result of this function is "unintuitive," albeit correct; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermint
    >>> hermint([1,2,3]) # integrate once, value 0 at 0.
    array([1. , 0.5, 0.5, 0.5])
    """
    c = np.array(c, ndmin=1, copy=True)
    # 将输入的数组 c 转换为 NumPy 数组,确保至少是一维的,并且进行复制以防止原始数据被修改
    if c.dtype.char in '?bBhHiIlLqQpP':
        # 检查数组 c 的数据类型是否属于布尔型、整型或指针类型之一,如果是,则将其转换为双精度浮点数
        c = c.astype(np.double)
    if not np.iterable(k):
        # 如果 k 不可迭代(即不是列表、元组等),则将其转换为包含 k 的列表
        k = [k]
    cnt = pu._as_int(m, "the order of integration")
    # 将 m 转换为整数,如果无法转换则会引发错误,用于表示积分的阶数
    iaxis = pu._as_int(axis, "the axis")
    # 将 axis 转换为整数,用于表示数组的轴
    if cnt < 0:
        # 如果积分的阶数小于 0,则引发 ValueError
        raise ValueError("The order of integration must be non-negative")
    if len(k) > cnt:
        # 如果 k 中的积分常数个数多于阶数 cnt,则引发 ValueError
        raise ValueError("Too many integration constants")
    if np.ndim(lbnd) != 0:
        # 如果 lbnd 的维度不为 0(即不是标量),则引发 ValueError
        raise ValueError("lbnd must be a scalar.")
    if np.ndim(scl) != 0:
        # 如果 scl 的维度不为 0(即不是标量),则引发 ValueError
        raise ValueError("scl must be a scalar.")
    iaxis = normalize_axis_index(iaxis, c.ndim)
    # 根据数组 c 的维度和指定的轴值对 iaxis 进行标准化处理

    if cnt == 0:
        # 如果积分的阶数为 0,则直接返回数组 c,不进行积分计算
        return c

    c = np.moveaxis(c, iaxis, 0)
    # 将数组 c 的轴移动到指定位置,这里是将第 iaxis 轴移动到第 0 位置
    k = list(k) + [0]*(cnt - len(k))
    # 将 k 扩展到长度为 cnt,不足部分用 0 填充
    for i in range(cnt):
        # 循环进行 cnt 次积分操作
        n = len(c)
        c *= scl
        # 将数组 c 的每个元素乘以 scl
        if n == 1 and np.all(c[0] == 0):
            # 如果数组 c 只有一个元素且该元素全为 0,则在第一个元素上加上 k[i]
            c[0] += k[i]
        else:
            # 否则,创建临时数组 tmp,并进行 Hermite 插值
            tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
            tmp[0] = c[0]*0
            tmp[1] = c[0]/2
            for j in range(1, n):
                tmp[j + 1] = c[j]/(2*(j + 1))
            tmp[0] += k[i] - hermval(lbnd, tmp)
            c = tmp
    c = np.moveaxis(c, 0, iaxis)
    # 将数组 c 的轴移回原始位置
    return c
    # 返回积分结果的数组 c
def hermval(x, c, tensor=True):
    """
    Evaluate an Hermite series at points x.

    If `c` is of length ``n + 1``, this function returns the value:

    .. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x)

    The parameter `x` is converted to an array only if it is a tuple or a
    list, otherwise it is treated as a scalar. In either case, either `x`
    or its elements must support multiplication and addition both with
    themselves and with the elements of `c`.

    If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`.  If
    `c` is multidimensional, then the shape of the result depends on the
    value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
    x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
    scalars have shape (,).

    Trailing zeros in the coefficients will be used in the evaluation, so
    they should be avoided if efficiency is a concern.

    Parameters
    ----------
    x : array_like, compatible object
        If `x` is a list or tuple, it is converted to an ndarray, otherwise
        it is left unchanged and treated as a scalar. In either case, `x`
        or its elements must support addition and multiplication with
        themselves and with the elements of `c`.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree n are contained in c[n]. If `c` is multidimensional the
        remaining indices enumerate multiple polynomials. In the two
        dimensional case the coefficients may be thought of as stored in
        the columns of `c`.
    tensor : boolean, optional
        If True, the shape of the coefficient array is extended with ones
        on the right, one for each dimension of `x`. Scalars have dimension 0
        for this action. The result is that every column of coefficients in
        `c` is evaluated for every element of `x`. If False, `x` is broadcast
        over the columns of `c` for the evaluation.  This keyword is useful
        when `c` is multidimensional. The default value is True.

        .. versionadded:: 1.7.0

    Returns
    -------
    values : ndarray, algebra_like
        The shape of the return value is described above.

    See Also
    --------
    hermval2d, hermgrid2d, hermval3d, hermgrid3d

    Notes
    -----
    The evaluation uses Clenshaw recursion, aka synthetic division.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermval
    >>> coef = [1,2,3]
    >>> hermval(1, coef)
    11.0
    >>> hermval([[1,2],[3,4]], coef)
    array([[ 11.,   51.],
           [115.,  203.]])

    """
    # 将系数数组 `c` 转换为至少为一维的 numpy 数组
    c = np.array(c, ndmin=1, copy=None)
    # 如果 `c` 的数据类型是布尔类型或整数类型,则转换为双精度浮点数类型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    # 如果 `x` 是 tuple 或 list 类型,则将其转换为 numpy 数组
    if isinstance(x, (tuple, list)):
        x = np.asarray(x)
    # 如果 `x` 是 numpy 数组且 `tensor` 参数为 True,则调整 `c` 的形状
    if isinstance(x, np.ndarray) and tensor:
        c = c.reshape(c.shape + (1,)*x.ndim)

    # 计算 `x` 的两倍
    x2 = x * 2
    # 如果系数数组 `c` 的长度为 1
    if len(c) == 1:
        # 取出第一个系数和设置第二个系数为 0
        c0 = c[0]
        c1 = 0
    elif len(c) == 2:
        # 如果列表 c 的长度为 2,则执行以下操作
        c0 = c[0]
        # 取列表 c 的第一个元素赋值给 c0
        c1 = c[1]
        # 取列表 c 的第二个元素赋值给 c1
    else:
        # 如果列表 c 的长度不为 2,则执行以下操作
        nd = len(c)
        # 获取列表 c 的长度并赋值给 nd
        c0 = c[-2]
        # 取列表 c 的倒数第二个元素赋值给 c0
        c1 = c[-1]
        # 取列表 c 的最后一个元素赋值给 c1
        for i in range(3, len(c) + 1):
            # 循环迭代,从 3 到列表 c 的长度(加 1)
            tmp = c0
            # 将 c0 的值赋给临时变量 tmp
            nd = nd - 1
            # nd 减 1
            c0 = c[-i] - c1*(2*(nd - 1))
            # 更新 c0 的值,使用列表 c 的倒数第 i 个元素减去 c1 乘以表达式结果
            c1 = tmp + c1*x2
            # 更新 c1 的值,将 tmp 加上 c1 乘以 x2
    return c0 + c1*x2
    # 返回 c0 加上 c1 乘以 x2 的结果
# 根据给定的 Hermite 系数和输入的 x, y 值,计算二维 Hermite 级数的值
def hermval2d(x, y, c):
    # 使用内部函数 _valnd 对 hermval 进行求值,并返回结果
    return pu._valnd(hermval, c, x, y)


def hermgrid2d(x, y, c):
    """
    Evaluate a 2-D Hermite series on the Cartesian product of x and y.

    This function returns the values:

    .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)

    where the points ``(a, b)`` consist of all pairs formed by taking
    `a` from `x` and `b` from `y`. The resulting points form a grid with
    `x` in the first dimension and `y` in the second.

    The parameters `x` and `y` are converted to arrays only if they are
    tuples or a lists, otherwise they are treated as scalars. In either
    case, either `x` and `y` or their elements must support multiplication
    and addition both with themselves and with the elements of `c`.

    If `c` has fewer than two dimensions, ones are implicitly appended to
    its shape to make it 2-D. The shape of the result will be c.shape[2:] +
    x.shape.

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points ``(x, y)``,
        where `x` and `y` must have the same shape. If `x` or `y` is a list
        or tuple, it is first converted to an ndarray, otherwise it is left
        unchanged and if it isn't an ndarray it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficient of the term
        of multi-degree i,j is contained in ``c[i,j]``. If `c` has
        dimension greater than two the remaining indices enumerate multiple
        sets of coefficients.

    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points formed with
        pairs of corresponding values from `x` and `y`.

    See Also
    --------
    hermval, hermval2d, hermval3d, hermgrid3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermval2d
    >>> x = [1, 2]
    >>> y = [4, 5]
    >>> c = [[1, 2, 3], [4, 5, 6]]
    >>> hermval2d(x, y, c)
    array ([1035., 2883.])

    """
    # 定义函数 hermgrid2d,用于计算二维埃尔米特多项式在给定点上的值
    # x, y : array_like, 兼容的对象,表示二维系列在笛卡尔积上的点的评估
    # 如果 x 或 y 是列表或元组,则首先转换为 ndarray;否则保持不变,如果不是 ndarray,则视为标量处理
    # c : array_like,系数数组,按照度 i,j 的顺序排列,系数为 ``c[i,j]``。如果 `c` 的维度大于二,则其余索引用于枚举多组系数

    # 返回值
    # ------
    # values : ndarray,兼容的对象
    # 在 `x` 和 `y` 的笛卡尔积上的二维多项式的值

    # 参见
    # --------
    # hermval, hermval2d, hermval3d, hermgrid3d

    # 注意
    # -----
    # .. versionadded:: 1.7.0

    # 示例
    # --------
    # >>> from numpy.polynomial.hermite import hermgrid2d
    # >>> x = [1, 2, 3]
    # >>> y = [4, 5]
    # >>> c = [[1, 2, 3], [4, 5, 6]]
    # >>> hermgrid2d(x, y, c)
    # array([[1035., 1599.],
    #        [1867., 2883.],
    #        [2699., 4167.]])
    """
    调用 _gridnd 函数来计算二维埃尔米特多项式在给定点 (x, y) 上的值,使用了 hermval 函数和系数 c
    """
    return pu._gridnd(hermval, c, x, y)
# 导入 pu 模块的 _valnd 函数,用于计算多维 Hermite 多项式的值
# 返回 _valnd 函数的结果,该函数计算 hermval 函数的值
def hermval3d(x, y, z, c):
    return pu._valnd(hermval, c, x, y, z)


# 在三维笛卡尔积上评估三维 Hermite 级数
# 返回结果是三维 Hermite 级数在点对 (x, y, z) 组成的笛卡尔积上的值
# x, y, z 参数被转换为数组,如果它们是元组或列表;否则被视为标量
# 如果 c 的维数少于三维,会隐式添加维度使其成为三维
# 结果的形状将是 c.shape[3:] + x.shape
def hermgrid3d(x, y, z, c):
    # 返回三维多项式的值在给定点的笛卡尔乘积中
    Parameters
    ----------
    x, y, z : array_like, compatible objects
        在`x`、`y`、`z`的笛卡尔乘积中评估三维系列。如果`x`、`y`或`z`是列表或元组,则首先转换为ndarray;否则保持不变,并且如果它不是ndarray,则视为标量。
    c : array_like
        系数数组,按照i、j度项的系数包含在`c[i,j]`中。如果`c`的维度大于两,则剩余索引列举多组系数。

    Returns
    -------
    values : ndarray, compatible object
        三维多项式在`x`和`y`的笛卡尔乘积中的值。

    See Also
    --------
    hermval, hermval2d, hermgrid2d, hermval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermgrid3d
    >>> x = [1, 2]
    >>> y = [4, 5]
    >>> z = [6, 7]
    >>> c = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
    >>> hermgrid3d(x, y, z, c)
    返回三维Hermite多项式在给定点处的值。
    array([[[ 40077.,  54117.],
            [ 49293.,  66561.]],
           [[ 72375.,  97719.],
            [ 88975., 120131.]]])

    """
    return pu._gridnd(hermval, c, x, y, z)
def hermvander(x, deg):
    """Pseudo-Vandermonde matrix of given degree.

    Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
    `x`. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., i] = H_i(x),

    where ``0 <= i <= deg``. The leading indices of `V` index the elements of
    `x` and the last index is the degree of the Hermite polynomial.

    If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the
    array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and
    ``hermval(x, c)`` are the same up to roundoff. This equivalence is
    useful both for least squares fitting and for the evaluation of a large
    number of Hermite series of the same degree and sample points.

    Parameters
    ----------
    x : array_like
        Array of points. The dtype is converted to float64 or complex128
        depending on whether any of the elements are complex. If `x` is
        scalar it is converted to a 1-D array.
    deg : int
        Degree of the resulting matrix.

    Returns
    -------
    vander : ndarray
        The pseudo-Vandermonde matrix. The shape of the returned matrix is
        ``x.shape + (deg + 1,)``, where The last index is the degree of the
        corresponding Hermite polynomial.  The dtype will be the same as
        the converted `x`.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermvander
    >>> x = np.array([-1, 0, 1])
    >>> hermvander(x, 3)
    array([[ 1., -2.,  2.,  4.],
           [ 1.,  0., -2., -0.],
           [ 1.,  2.,  2., -4.]])

    """
    # Convert deg to an integer if possible
    ideg = pu._as_int(deg, "deg")
    # Raise ValueError if deg is negative
    if ideg < 0:
        raise ValueError("deg must be non-negative")

    # Ensure x is converted to a 1-D array of type float64 or complex128
    x = np.array(x, copy=None, ndmin=1) + 0.0
    # Determine the dimensions of the output matrix
    dims = (ideg + 1,) + x.shape
    # Determine the dtype for the output matrix
    dtyp = x.dtype
    # Create an empty array with the determined dimensions and dtype
    v = np.empty(dims, dtype=dtyp)
    # Initialize the first row of v to be 1s
    v[0] = x*0 + 1
    # Compute subsequent rows using Hermite polynomial recurrence relations
    if ideg > 0:
        x2 = x*2
        v[1] = x2
        for i in range(2, ideg + 1):
            v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1)))
    # Return the pseudo-Vandermonde matrix with the first axis moved to the last
    return np.moveaxis(v, 0, -1)


def hermvander2d(x, y, deg):
    """Pseudo-Vandermonde matrix of given degrees.

    Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
    points ``(x, y)``. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., (deg[1] + 1)*i + j] = H_i(x) * H_j(y),

    where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of
    `V` index the points ``(x, y)`` and the last index encodes the degrees of
    the Hermite polynomials.

    If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
    correspond to the elements of a 2-D coefficient array `c` of shape
    (xdeg + 1, ydeg + 1) in the order

    .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...

    and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same
    up to roundoff. This equivalence is useful both for least squares
    fitting and for the evaluation of a large number of 2-D Hermite

    """
    # Function definition for computing a pseudo-Vandermonde matrix for 2D Hermite polynomials
    # The detailed mathematical description is provided in the docstring
    # 返回一个二维埃尔米特(Hermite)Vandermonde 矩阵,用于给定的一系列点和最大度数。

    Parameters
    ----------
    x, y : array_like
        表示点的坐标数组,形状相同。元素的数据类型将转换为float64或complex128,取决于是否有复数元素。
        标量将转换为1维数组。
    deg : list of ints
        最大度数的列表,形式为 [x_deg, y_deg]。

    Returns
    -------
    vander2d : ndarray
        返回的矩阵形状为 ``x.shape + (order,)``,其中 :math:`order = (deg[0]+1)*(deg[1]+1)`。
        数据类型与转换后的 `x` 和 `y` 相同。

    See Also
    --------
    hermvander, hermvander3d, hermval2d, hermval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermvander2d
    >>> x = np.array([-1, 0, 1])
    >>> y = np.array([-1, 0, 1])
    >>> hermvander2d(x, y, [2, 2])
    array([[ 1., -2.,  2., -2.,  4., -4.,  2., -4.,  4.],
           [ 1.,  0., -2.,  0.,  0., -0., -2., -0.,  4.],
           [ 1.,  2.,  2.,  2.,  4.,  4.,  2.,  4.,  4.]])

    """
    return pu._vander_nd_flat((hermvander, hermvander), (x, y), deg)
def hermvander3d(x, y, z, deg):
    """
    Pseudo-Vandermonde matrix of given degrees.

    Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
    points ``(x, y, z)``. If `l`, `m`, `n` are the given degrees in `x`, `y`, `z`,
    then The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z),

    where ``0 <= i <= l``, ``0 <= j <= m``, and ``0 <= j <= n``.  The leading
    indices of `V` index the points ``(x, y, z)`` and the last index encodes
    the degrees of the Hermite polynomials.

    If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
    of `V` correspond to the elements of a 3-D coefficient array `c` of
    shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order

    .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...

    and  ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the
    same up to roundoff. This equivalence is useful both for least squares
    fitting and for the evaluation of a large number of 3-D Hermite
    series of the same degrees and sample points.

    Parameters
    ----------
    x, y, z : array_like
        Arrays of point coordinates, all of the same shape. The dtypes will
        be converted to either float64 or complex128 depending on whether
        any of the elements are complex. Scalars are converted to 1-D
        arrays.
    deg : list of ints
        List of maximum degrees of the form [x_deg, y_deg, z_deg].

    Returns
    -------
    vander3d : ndarray
        The shape of the returned matrix is ``x.shape + (order,)``, where
        :math:`order = (deg[0]+1)*(deg[1]+1)*(deg[2]+1)`.  The dtype will
        be the same as the converted `x`, `y`, and `z`.

    See Also
    --------
    hermvander, hermvander3d, hermval2d, hermval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermvander3d
    >>> x = np.array([-1, 0, 1])
    >>> y = np.array([-1, 0, 1])
    >>> z = np.array([-1, 0, 1])
    >>> hermvander3d(x, y, z, [0, 1, 2])
    array([[ 1., -2.,  2., -2.,  4., -4.],
           [ 1.,  0., -2.,  0.,  0., -0.],
           [ 1.,  2.,  2.,  2.,  4.,  4.]])

    """
    return pu._vander_nd_flat((hermvander, hermvander, hermvander), (x, y, z), deg)
    x : array_like, shape (M,)
        # M个样本点的x坐标,形状为(M,),即(x[i], y[i])中的x[i]。
    y : array_like, shape (M,) or (M, K)
        # 样本点的y坐标。可以是形状为(M,)或(M, K)的数组,多组共享相同x坐标的样本点可以一次性拟合,
        # 通过传入一个包含每列数据集的2D数组来实现。
    deg : int or 1-D array_like
        # 拟合多项式的次数。如果deg是一个整数,则包括到第deg阶的所有项。对于NumPy版本 >= 1.11.0,
        # 可以使用包含要包括的项的次数的整数列表。
    rcond : float, optional
        # 拟合条件数的相对值。比最大奇异值小于这个值的奇异值将被忽略。默认值为len(x)*eps,
        # 其中eps是浮点类型的相对精度,大多数情况下约为2e-16。
    full : bool, optional
        # 决定返回值类型的开关。当为False(默认)时,只返回系数;当为True时,还返回奇异值分解的诊断信息。
    w : array_like, shape (`M`,), optional
        # 权重。如果不为None,则权重``w[i]``适用于在``x[i]``处的未平方残差``y[i] - y_hat[i]``。
        # 理想情况下,选择权重使得所有产品``w[i]*y[i]``的误差具有相同的方差。当使用逆方差加权时,
        # 使用``w[i] = 1/sigma(y[i])``。默认值为None。

    Returns
    -------
    coef : ndarray, shape (M,) or (M, K)
        # 按从低到高排序的Hermite系数。如果`y`是2D的,则列k中的数据的系数位于列`k`中。

    [residuals, rank, singular_values, rcond] : list
        # 仅在`full == True`时返回这些值

        - residuals -- 最小二乘拟合的残差平方和
        - rank -- 缩放的Vandermonde矩阵的数值秩
        - singular_values -- 缩放的Vandermonde矩阵的奇异值
        - rcond -- `rcond`的值

        有关更多详细信息,请参阅`numpy.linalg.lstsq`。

    Warns
    -----
    RankWarning
        # 最小二乘拟合中的系数矩阵的秩不足。仅当`full == False`时才会引发警告。
        # 可以通过以下方式关闭警告:

        >>> import warnings
        >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)

    See Also
    --------
    numpy.polynomial.chebyshev.chebfit
    numpy.polynomial.legendre.legfit
    numpy.polynomial.laguerre.lagfit
    numpy.polynomial.polynomial.polyfit
    numpy.polynomial.hermite_e.hermefit
    hermval : 评估Hermite级数。
    hermvander : Hermite级数的Vandermonde矩阵。
    hermweight : Hermite权重函数
    numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
    scipy.interpolate.UnivariateSpline : Computes spline fits.

    Notes
    -----
    The solution is the coefficients of the Hermite series `p` that
    minimizes the sum of the weighted squared errors

    .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,

    where the :math:`w_j` are the weights. This problem is solved by
    setting up the (typically) overdetermined matrix equation

    .. math:: V(x) * c = w * y,

    where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
    coefficients to be solved for, `w` are the weights, `y` are the
    observed values.  This equation is then solved using the singular value
    decomposition of `V`.

    If some of the singular values of `V` are so small that they are
    neglected, then a `~exceptions.RankWarning` will be issued. This means that
    the coefficient values may be poorly determined. Using a lower order fit
    will usually get rid of the warning.  The `rcond` parameter can also be
    set to a value smaller than its default, but the resulting fit may be
    spurious and have large contributions from roundoff error.

    Fits using Hermite series are probably most useful when the data can be
    approximated by ``sqrt(w(x)) * p(x)``, where ``w(x)`` is the Hermite
    weight. In that case the weight ``sqrt(w(x[i]))`` should be used
    together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is
    available as `hermweight`.

    References
    ----------
    .. [1] Wikipedia, "Curve fitting",
           https://en.wikipedia.org/wiki/Curve_fitting

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermfit, hermval
    >>> x = np.linspace(-10, 10)
    >>> rng = np.random.default_rng()
    >>> err = rng.normal(scale=1./10, size=len(x))
    >>> y = hermval(x, [1, 2, 3]) + err
    >>> hermfit(x, y, 2)
    array([1.02294967, 2.00016403, 2.99994614]) # may vary

    """
    return pu._fit(hermvander, x, y, deg, rcond, full, w)


注释:


    # 调用 `_fit` 函数进行曲线拟合,使用 Hermite 系列作为基础
    return pu._fit(hermvander, x, y, deg, rcond, full, w)


这段代码是一个函数的返回语句,返回了 `_fit` 函数的调用结果,该函数用于进行曲线拟合,其中使用了 Hermite 系列作为基础。
def hermcompanion(c):
    """Return the scaled companion matrix of c.

    The basis polynomials are scaled so that the companion matrix is
    symmetric when `c` is an Hermite basis polynomial. This provides
    better eigenvalue estimates than the unscaled case and for basis
    polynomials the eigenvalues are guaranteed to be real if
    `numpy.linalg.eigvalsh` is used to obtain them.

    Parameters
    ----------
    c : array_like
        1-D array of Hermite series coefficients ordered from low to high
        degree.

    Returns
    -------
    mat : ndarray
        Scaled companion matrix of dimensions (deg, deg).

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermcompanion
    >>> hermcompanion([1, 0, 1])
    array([[0.        , 0.35355339],
           [0.70710678, 0.        ]])

    """
    # c is a trimmed copy
    [c] = pu.as_series([c])  # 将输入的系数数组c转换为多项式对象
    if len(c) < 2:
        raise ValueError('Series must have maximum degree of at least 1.')
    if len(c) == 2:
        return np.array([[-.5*c[0]/c[1]]])  # 对于一阶多项式,返回其伴随矩阵的特殊形式

    n = len(c) - 1
    mat = np.zeros((n, n), dtype=c.dtype)  # 创建一个全零的方阵,数据类型与输入系数数组c相同
    scl = np.hstack((1., 1./np.sqrt(2.*np.arange(n - 1, 0, -1))))  # 创建一个缩放系数向量
    scl = np.multiply.accumulate(scl)[::-1]  # 对缩放系数向量进行累积乘积并反向排序
    top = mat.reshape(-1)[1::n+1]  # 提取伴随矩阵中的上三角元素
    bot = mat.reshape(-1)[n::n+1]  # 提取伴随矩阵中的下三角元素
    top[...] = np.sqrt(.5*np.arange(1, n))  # 设置上三角元素的值
    bot[...] = top  # 设置下三角元素的值
    mat[:, -1] -= scl*c[:-1]/(2.0*c[-1])  # 修改伴随矩阵的最后一列
    return mat  # 返回计算得到的伴随矩阵


def hermroots(c):
    """
    Compute the roots of a Hermite series.

    Return the roots (a.k.a. "zeros") of the polynomial

    .. math:: p(x) = \\sum_i c[i] * H_i(x).

    Parameters
    ----------
    c : 1-D array_like
        1-D array of coefficients.

    Returns
    -------
    out : ndarray
        Array of the roots of the series. If all the roots are real,
        then `out` is also real, otherwise it is complex.

    See Also
    --------
    numpy.polynomial.polynomial.polyroots
    numpy.polynomial.legendre.legroots
    numpy.polynomial.laguerre.lagroots
    numpy.polynomial.chebyshev.chebroots
    numpy.polynomial.hermite_e.hermeroots

    Notes
    -----
    The root estimates are obtained as the eigenvalues of the companion
    matrix, Roots far from the origin of the complex plane may have large
    errors due to the numerical instability of the series for such
    values. Roots with multiplicity greater than 1 will also show larger
    errors as the value of the series near such points is relatively
    insensitive to errors in the roots. Isolated roots near the origin can
    be improved by a few iterations of Newton's method.

    The Hermite series basis polynomials aren't powers of `x` so the
    results of this function may seem unintuitive.

    Examples
    --------
    >>> from numpy.polynomial.hermite import hermroots, hermfromroots
    >>> coef = hermfromroots([-1, 0, 1])
    >>> coef
    array([0.   ,  0.25 ,  0.   ,  0.125])
    >>> hermroots(coef)
    """
    # Compute roots of the Hermite series using the companion matrix
    return np.linalg.eigvals(hermcompanion(c))  # 使用伴随矩阵计算 Hermite 系列的根,并返回根的数组
    array([-1.00000000e+00, -1.38777878e-17,  1.00000000e+00])

    """
    # 将输入的数组 c 复制一份,并转换为一维数组
    [c] = pu.as_series([c])
    # 如果 c 的长度小于等于 1,则返回一个空的 NumPy 数组,其数据类型与 c 相同
    if len(c) <= 1:
        return np.array([], dtype=c.dtype)
    # 如果 c 的长度为 2,则计算并返回一个包含单个元素的 NumPy 数组,值为 -.5*c[0]/c[1]
    if len(c) == 2:
        return np.array([-.5*c[0]/c[1]])

    # 创建旋转后的伴随矩阵以减少误差
    # 使用 hermcompanion 函数生成 c 的伴随矩阵,并对其进行逆序排列
    m = hermcompanion(c)[::-1,::-1]
    # 计算矩阵 m 的特征值
    r = la.eigvals(m)
    # 对特征值数组 r 进行排序
    r.sort()
    # 返回排序后的特征值数组
    return r
    ```py
    # 将给定的 x 和 n 作为参数,计算规范化 Hermite 多项式的值
    def _normed_hermite_n(x, n):
        """
        Evaluate a normalized Hermite polynomial.

        Compute the value of the normalized Hermite polynomial of degree ``n``
        at the points ``x``.

        Parameters
        ----------
        x : ndarray of double.
            Points at which to evaluate the function
        n : int
            Degree of the normalized Hermite function to be evaluated.

        Returns
        -------
        values : ndarray
            The shape of the return value is described above.

        Notes
        -----
        .. versionadded:: 1.10.0

        This function is needed for finding the Gauss points and integration
        weights for high degrees. The values of the standard Hermite functions
        overflow when n >= 207.

        """
        if n == 0:
            # Return a constant value if n is 0
            return np.full(x.shape, 1/np.sqrt(np.sqrt(np.pi)))

        c0 = 0.
        c1 = 1./np.sqrt(np.sqrt(np.pi))
        nd = float(n)
        for i in range(n - 1):
            # Recurrence relation to compute the Hermite polynomial coefficients
            tmp = c0
            c0 = -c1*np.sqrt((nd - 1.)/nd)
            c1 = tmp + c1*x*np.sqrt(2./nd)
            nd = nd - 1.0
        # Return the computed Hermite polynomial value
        return c0 + c1*x*np.sqrt(2)


    # 计算 Gauss-Hermite 积分的采样点和权重
    def hermgauss(deg):
        """
        Gauss-Hermite quadrature.

        Computes the sample points and weights for Gauss-Hermite quadrature.
        These sample points and weights will correctly integrate polynomials of
        degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
        with the weight function :math:`f(x) = \\exp(-x^2)`.

        Parameters
        ----------
        deg : int
            Number of sample points and weights. It must be >= 1.

        Returns
        -------
        x : ndarray
            1-D ndarray containing the sample points.
        y : ndarray
            1-D ndarray containing the weights.

        Notes
        -----

        .. versionadded:: 1.7.0

        The results have only been tested up to degree 100, higher degrees may
        be problematic. The weights are determined by using the fact that

        .. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))

        where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
        is the k'th root of :math:`H_n`, and then scaling the results to get
        the right value when integrating 1.

        Examples
        --------
        >>> from numpy.polynomial.hermite import hermgauss
        >>> hermgauss(2)
        (array([-0.70710678,  0.70710678]), array([0.88622693, 0.88622693]))

        """
        ideg = pu._as_int(deg, "deg")  # Convert deg to integer
        if ideg <= 0:
            raise ValueError("deg must be a positive integer")

        # first approximation of roots. We use the fact that the companion
        # matrix is symmetric in this case in order to obtain better zeros.
        c = np.array([0]*deg + [1], dtype=np.float64)
        m = hermcompanion(c)
        x = la.eigvalsh(m)

        # improve roots by one application of Newton
        dy = _normed_hermite_n(x, ideg)
        df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2*ideg)
        x -= dy/df

        # compute the weights. We scale the factor to avoid possible numerical
        # overflow.
        fm = _normed_hermite_n(x, ideg - 1)
        fm /= np.abs(fm).max()
        w = 1/(fm * fm)

        # for Hermite we can also symmetrize
    # 将 w 扩展为 w 与其反转的平均值
    w = (w + w[::-1]) / 2
    # 将 x 缩放以获得正确的值
    x = (x - x[::-1]) / 2

    # 将 w 缩放以使其具有正确的值
    w *= np.sqrt(np.pi) / w.sum()

    # 返回处理后的 x 和 w
    return x, w
class Hermite(ABCPolyBase):
    """An Hermite series class.

    The Hermite class provides the standard Python numerical methods
    '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
    attributes and methods listed below.

    Parameters
    ----------
    coef : array_like
        Hermite coefficients in order of increasing degree, i.e,
        ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(x) + 3*H_2(x)``.
    domain : (2,) array_like, optional
        Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
        to the interval ``[window[0], window[1]]`` by shifting and scaling.
        The default value is [-1, 1].
    window : (2,) array_like, optional
        Window, see `domain` for its use. The default value is [-1, 1].

        .. versionadded:: 1.6.0
    symbol : str, optional
        Symbol used to represent the independent variable in string
        representations of the polynomial expression, e.g. for printing.
        The symbol must be a valid Python identifier. Default value is 'x'.

        .. versionadded:: 1.24

    """
    # 设置静态方法为对应的Hermite多项式操作
    _add = staticmethod(hermadd)
    _sub = staticmethod(hermsub)
    _mul = staticmethod(hermmul)
    _div = staticmethod(hermdiv)
    _pow = staticmethod(hermpow)
    _val = staticmethod(hermval)
    _int = staticmethod(hermint)
    _der = staticmethod(hermder)
    _fit = staticmethod(hermfit)
    _line = staticmethod(hermline)
    _roots = staticmethod(hermroots)
    _fromroots = staticmethod(hermfromroots)

    # 定义虚拟属性
    domain = np.array(hermdomain)
    window = np.array(hermdomain)
    basis_name = 'H'

.\numpy\numpy\polynomial\hermite.pyi

# 导入必要的类型注解
from typing import Any

# 导入所需的 numpy 类型
from numpy import int_, float64

# 导入 numpy 的类型注解
from numpy.typing import NDArray

# 导入多项式基类和系数修剪函数
from numpy.polynomial._polybase import ABCPolyBase
from numpy.polynomial.polyutils import trimcoef

# 声明 __all__ 变量,并初始化为空列表
__all__: list[str]

# 将 trimcoef 函数别名为 hermtrim
hermtrim = trimcoef

# 定义两个函数 poly2herm 和 herm2poly,但具体实现部分未显示,用 ... 表示
def poly2herm(pol): ...
def herm2poly(c): ...

# 声明一些全局变量,类型为 numpy 数组
hermdomain: NDArray[int_]
hermzero: NDArray[int_]
hermone: NDArray[int_]
hermx: NDArray[float64]

# 定义一系列 Hermite 多项式的操作函数
def hermline(off, scl): ...
def hermfromroots(roots): ...
def hermadd(c1, c2): ...
def hermsub(c1, c2): ...
def hermmulx(c): ...
def hermmul(c1, c2): ...
def hermdiv(c1, c2): ...
def hermpow(c, pow, maxpower=...): ...
def hermder(c, m=..., scl=..., axis=...): ...
def hermint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
def hermval(x, c, tensor=...): ...
def hermval2d(x, y, c): ...
def hermgrid2d(x, y, c): ...
def hermval3d(x, y, z, c): ...
def hermgrid3d(x, y, z, c): ...
def hermvander(x, deg): ...
def hermvander2d(x, y, deg): ...
def hermvander3d(x, y, z, deg): ...
def hermfit(x, y, deg, rcond=..., full=..., w=...): ...
def hermcompanion(c): ...
def hermroots(c): ...
def hermgauss(deg): ...
def hermweight(x): ...

# 定义 Hermite 类,继承自 ABCPolyBase 类
class Hermite(ABCPolyBase):
    domain: Any      # 定义 domain 属性
    window: Any      # 定义 window 属性
    basis_name: Any  # 定义 basis_name 属性

.\numpy\numpy\polynomial\hermite_e.py

"""
===================================================================
HermiteE Series, "Probabilists" (:mod:`numpy.polynomial.hermite_e`)
===================================================================

This module provides a number of objects (mostly functions) useful for
dealing with Hermite_e series, including a `HermiteE` class that
encapsulates the usual arithmetic operations.  (General information
on how this module represents and works with such polynomials is in the
docstring for its "parent" sub-package, `numpy.polynomial`).

Classes
-------
.. autosummary::
   :toctree: generated/

   HermiteE

Constants
---------
.. autosummary::
   :toctree: generated/

   hermedomain
   hermezero
   hermeone
   hermex

Arithmetic
----------
.. autosummary::
   :toctree: generated/

   hermeadd
   hermesub
   hermemulx
   hermemul
   hermediv
   hermepow
   hermeval
   hermeval2d
   hermeval3d
   hermegrid2d
   hermegrid3d

Calculus
--------
.. autosummary::
   :toctree: generated/

   hermeder
   hermeint

Misc Functions
--------------
.. autosummary::
   :toctree: generated/

   hermefromroots
   hermeroots
   hermevander
   hermevander2d
   hermevander3d
   hermegauss
   hermeweight
   hermecompanion
   hermefit
   hermetrim
   hermeline
   herme2poly
   poly2herme

See also
--------
`numpy.polynomial`

"""
import numpy as np
import numpy.linalg as la
from numpy.lib.array_utils import normalize_axis_index

from . import polyutils as pu
from ._polybase import ABCPolyBase

__all__ = [
    'hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline',
    'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv',
    'hermepow', 'hermeval', 'hermeder', 'hermeint', 'herme2poly',
    'poly2herme', 'hermefromroots', 'hermevander', 'hermefit', 'hermetrim',
    'hermeroots', 'HermiteE', 'hermeval2d', 'hermeval3d', 'hermegrid2d',
    'hermegrid3d', 'hermevander2d', 'hermevander3d', 'hermecompanion',
    'hermegauss', 'hermeweight']

# Alias for the trimcoef function from polyutils
hermetrim = pu.trimcoef


def poly2herme(pol):
    """
    poly2herme(pol)

    Convert a polynomial to a Hermite series.

    Convert an array representing the coefficients of a polynomial (relative
    to the "standard" basis) ordered from lowest degree to highest, to an
    array of the coefficients of the equivalent Hermite series, ordered
    from lowest to highest degree.

    Parameters
    ----------
    pol : array_like
        1-D array containing the polynomial coefficients

    Returns
    -------
    c : ndarray
        1-D array containing the coefficients of the equivalent Hermite
        series.

    See Also
    --------
    herme2poly

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import poly2herme
    >>> poly2herme(np.arange(4))
    array([  2.,  10.,   2.,   3.])

    """
    [pol] = pu.as_series([pol])  # Ensure pol is a 1-D polynomial array
    deg = len(pol) - 1  # Degree of the polynomial
    res = 0  # Initialize result variable as 0
    # 从最高次数 deg 开始到常数项 0 的范围,逐次进行多项式运算
    for i in range(deg, -1, -1):
        # 调用 hermemulx 函数,将 res 与 x 的 Hermite 多项式相乘,并将结果赋给 res
        res = hermeadd(hermemulx(res), pol[i])
    # 返回最终的多项式计算结果 res
    return res
def herme2poly(c):
    """
    Convert a Hermite series to a polynomial.

    Convert an array representing the coefficients of a Hermite series,
    ordered from lowest degree to highest, to an array of the coefficients
    of the equivalent polynomial (relative to the "standard" basis) ordered
    from lowest to highest degree.

    Parameters
    ----------
    c : array_like
        1-D array containing the Hermite series coefficients, ordered
        from lowest order term to highest.

    Returns
    -------
    pol : ndarray
        1-D array containing the coefficients of the equivalent polynomial
        (relative to the "standard" basis) ordered from lowest order term
        to highest.

    See Also
    --------
    poly2herme

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import herme2poly
    >>> herme2poly([  2.,  10.,   2.,   3.])
    array([0.,  1.,  2.,  3.])

    """
    # 导入多项式操作函数
    from .polynomial import polyadd, polysub, polymulx
    # 将输入的系数数组转换为多项式系数表示
    [c] = pu.as_series([c])
    # 获取系数数组的长度
    n = len(c)
    # 如果长度为1或2,直接返回系数数组
    if n == 1:
        return c
    if n == 2:
        return c
    else:
        # 初始化多项式的高阶系数和次高阶系数
        c0 = c[-2]
        c1 = c[-1]
        # 从最高阶次逐步计算多项式系数
        # i 是当前 c1 的阶数
        for i in range(n - 1, 1, -1):
            tmp = c0
            # 更新 c0 和 c1 的值
            c0 = polysub(c[i - 2], c1*(i - 1))
            c1 = polyadd(tmp, polymulx(c1))
        # 返回最终计算得到的多项式系数数组
        return polyadd(c0, polymulx(c1))


#
# These are constant arrays are of integer type so as to be compatible
# with the widest range of other types, such as Decimal.
#

# Hermite
hermedomain = np.array([-1., 1.])

# Hermite coefficients representing zero.
hermezero = np.array([0])

# Hermite coefficients representing one.
hermeone = np.array([1])

# Hermite coefficients representing the identity x.
hermex = np.array([0, 1])


def hermeline(off, scl):
    """
    Hermite series whose graph is a straight line.

    Parameters
    ----------
    off, scl : scalars
        The specified line is given by ``off + scl*x``.

    Returns
    -------
    y : ndarray
        This module's representation of the Hermite series for
        ``off + scl*x``.

    See Also
    --------
    numpy.polynomial.polynomial.polyline
    numpy.polynomial.chebyshev.chebline
    numpy.polynomial.legendre.legline
    numpy.polynomial.laguerre.lagline
    numpy.polynomial.hermite.hermline

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermeline
    >>> from numpy.polynomial.hermite_e import hermeline, hermeval
    >>> hermeval(0,hermeline(3, 2))
    3.0
    >>> hermeval(1,hermeline(3, 2))
    5.0

    """
    # 如果 scl 不为零,返回表示直线的 Hermite 系列
    if scl != 0:
        return np.array([off, scl])
    else:
        # 如果 scl 为零,返回只包含常数 off 的 Hermite 系列
        return np.array([off])


def hermefromroots(roots):
    """
    Generate a HermiteE series with given roots.

    The function returns the coefficients of the polynomial

    .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),

    where `roots` is a list of roots.

    Parameters
    ----------
    roots : array_like
        1-D array containing the roots of the HermiteE series polynomial.

    Returns
    -------
    c : ndarray
        1-D array containing the coefficients of the HermiteE series polynomial.

    """
    # 实现从给定根生成 HermiteE 系列的系数
    return np.poly(roots)
    # 返回 HermiteE 形式的多项式的系数,根据给定的根 `roots`。
    # `roots` 参数是一个数组,包含多项式的根。
    # 如果某个零点的重数是 n,则它在 `roots` 中出现 n 次。
    # 例如,如果数字 2 的重数是 3,数字 3 的重数是 2,则 `roots` 可能是 [2, 2, 2, 3, 3]。
    # 根可以以任何顺序出现。
    
    # 如果返回的系数是 `c`,则多项式 p(x) 表示为:
    # p(x) = c_0 + c_1 * He_1(x) + ... + c_n * He_n(x)
    # 其中 He_i(x) 是 HermiteE 多项式的基函数。
    
    # 最后一项的系数通常不为 1,因为 HermiteE 形式的多项式不一定是首一的。
    
    # Parameters
    # ----------
    # roots : array_like
    #     包含多项式根的序列。
    
    # Returns
    # -------
    # out : ndarray
    #     系数的一维数组。如果所有的根都是实数,则 `out` 是实数组;如果有一些根是复数,则 `out` 是复数数组,即使结果中所有的系数都是实数(参见下面的示例)。
    
    # See Also
    # --------
    # numpy.polynomial.polynomial.polyfromroots
    # numpy.polynomial.legendre.legfromroots
    # numpy.polynomial.laguerre.lagfromroots
    # numpy.polynomial.hermite.hermfromroots
    # numpy.polynomial.chebyshev.chebfromroots
    
    # Examples
    # --------
    # >>> from numpy.polynomial.hermite_e import hermefromroots, hermeval
    # >>> coef = hermefromroots((-1, 0, 1))
    # >>> hermeval((-1, 0, 1), coef)
    # array([0., 0., 0.])
    # >>> coef = hermefromroots((-1j, 1j))
    # >>> hermeval((-1j, 1j), coef)
    # array([0.+0.j, 0.+0.j])
def hermeadd(c1, c2):
    """
    Add one Hermite series to another.

    Returns the sum of two Hermite series `c1` + `c2`.  The arguments
    are sequences of coefficients ordered from lowest order term to
    highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the Hermite series of their sum.

    See Also
    --------
    hermesub, hermemulx, hermemul, hermediv, hermepow

    Notes
    -----
    Unlike multiplication, division, etc., the sum of two Hermite series
    is a Hermite series (without having to "reproject" the result onto
    the basis set) so addition, just like that of "standard" polynomials,
    is simply "component-wise."

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermeadd
    >>> hermeadd([1, 2, 3], [1, 2, 3, 4])
    array([2.,  4.,  6.,  4.])

    """
    # 使用私有模块 pu 中的 _add 函数来执行 Hermite 级数的加法
    return pu._add(c1, c2)


def hermesub(c1, c2):
    """
    Subtract one Hermite series from another.

    Returns the difference of two Hermite series `c1` - `c2`.  The
    sequences of coefficients are from lowest order term to highest, i.e.,
    [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Of Hermite series coefficients representing their difference.

    See Also
    --------
    hermeadd, hermemulx, hermemul, hermediv, hermepow

    Notes
    -----
    Unlike multiplication, division, etc., the difference of two Hermite
    series is a Hermite series (without having to "reproject" the result
    onto the basis set) so subtraction, just like that of "standard"
    polynomials, is simply "component-wise."

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermesub
    >>> hermesub([1, 2, 3, 4], [1, 2, 3])
    array([0., 0., 0., 4.])

    """
    # 使用私有模块 pu 中的 _sub 函数来执行 Hermite 级数的减法
    return pu._sub(c1, c2)


def hermemulx(c):
    """Multiply a Hermite series by x.

    Multiply the Hermite series `c` by x, where x is the independent
    variable.


    Parameters
    ----------
    c : array_like
        1-D array of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the result of the multiplication.

    See Also
    --------
    hermeadd, hermesub, hermemul, hermediv, hermepow

    Notes
    -----
    The multiplication uses the recursion relationship for Hermite
    polynomials in the form

    .. math::

        xP_i(x) = (P_{i + 1}(x) + iP_{i - 1}(x)))

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermemulx
    >>> hermemulx([1, 2, 3])
    array([2.,  7.,  2.,  3.])

    """
    # c 是 Hermite 级数系数的一维数组,函数返回乘以 x 后的结果
    # c is a trimmed copy
    # 将输入列表转换为 Pandas Series,并且确保只取其中的第一个元素
    [c] = pu.as_series([c])
    # 处理特殊情况:如果输入列表只包含一个元素且该元素为0,则直接返回该元素作为结果
    if len(c) == 1 and c[0] == 0:
        return c

    # 创建一个长度比输入列表 c 长度多一的空数组,数据类型与 c 相同
    prd = np.empty(len(c) + 1, dtype=c.dtype)
    # 设置 prd 数组的第一个元素为 c 的第一个元素乘以 0
    prd[0] = c[0]*0
    # 设置 prd 数组的第二个元素为 c 的第一个元素
    prd[1] = c[0]
    # 遍历输入列表 c 中的每个元素(除了第一个和最后一个元素),计算 prd 数组中每个位置的值
    for i in range(1, len(c)):
        prd[i + 1] = c[i]   # 当前位置的值为 c 中对应位置的值
        prd[i - 1] += c[i]*i  # 前一个位置的值加上 c 中对应位置的值乘以当前位置的索引值 i
    # 返回计算后的 prd 数组作为结果
    return prd
def hermemul(c1, c2):
    """
    Multiply one Hermite series by another.

    Returns the product of two Hermite series `c1` * `c2`.  The arguments
    are sequences of coefficients, from lowest order "term" to highest,
    e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Of Hermite series coefficients representing their product.

    See Also
    --------
    hermeadd, hermesub, hermemulx, hermediv, hermepow

    Notes
    -----
    In general, the (polynomial) product of two C-series results in terms
    that are not in the Hermite polynomial basis set.  Thus, to express
    the product as a Hermite series, it is necessary to "reproject" the
    product onto said basis set, which may produce "unintuitive" (but
    correct) results; see Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermemul
    >>> hermemul([1, 2, 3], [0, 1, 2])
    array([14.,  15.,  28.,   7.,   6.])

    """

    # s1, s2 are trimmed copies
    # Trim c1 and c2 to remove leading coefficients all of whose terms are zero
    [c1, c2] = pu.as_series([c1, c2])

    # Compare the lengths of the two arrays and swap them accordingly
    if len(c1) > len(c2):
        c = c2
        xs = c1
    else:
        c = c1
        xs = c2

    # Initialize c0 and c1
    if len(c) == 1:
        c0 = c[0]*xs
        c1 = 0
    elif len(c) == 2:
        c0 = c[0]*xs
        c1 = c[1]*xs
    else:
        nd = len(c)
        c0 = c[-2]*xs
        c1 = c[-1]*xs

        # Loop through the remaining coefficients to calculate c0 and c1
        for i in range(3, len(c) + 1):
            tmp = c0
            nd = nd - 1
            c0 = hermesub(c[-i]*xs, c1*(nd - 1))
            c1 = hermeadd(tmp, hermemulx(c1))

    # Return the sum of c0 and the product of c1 and the highest order sequence 
    return hermeadd(c0, hermemulx(c1))


def hermediv(c1, c2):
    """
    Divide one Hermite series by another.

    Returns the quotient-with-remainder of two Hermite series
    `c1` / `c2`.  The arguments are sequences of coefficients from lowest
    order "term" to highest, e.g., [1,2,3] represents the series
    ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Hermite series coefficients ordered from low to
        high.

    Returns
    -------
    [quo, rem] : ndarrays
        Of Hermite series coefficients representing the quotient and
        remainder.

    See Also
    --------
    hermeadd, hermesub, hermemulx, hermemul, hermepow

    Notes
    -----
    In general, the (polynomial) division of one Hermite series by another
    results in quotient and remainder terms that are not in the Hermite
    polynomial basis set.  Thus, to express these results as a Hermite
    series, it is necessary to "reproject" the results onto the Hermite
    basis set, which may produce "unintuitive" (but correct) results; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermediv
    >>> hermediv([ 14.,  15.,  28.,   7.,   6.], [0, 1, 2])
    (array([1., 2., 3.]), array([0.]))

    """
    # 调用 hermediv 函数,计算两个数组的除法操作,并返回结果
    >>> hermediv([ 15.,  17.,  28.,   7.,   6.], [0, 1, 2])
    # 返回一个元组,包含两个数组:第一个数组是除法运算后的结果,第二个数组是部分结果
    (array([1., 2., 3.]), array([1., 2.]))

    """
    # 返回一个调用 pu 模块中 _div 函数的结果,传递 hermemul, c1, c2 作为参数
    return pu._div(hermemul, c1, c2)
# 定义函数 hermepow,用于计算 Hermite 级数的幂次方
def hermepow(c, pow, maxpower=16):
    """Raise a Hermite series to a power.

    Returns the Hermite series `c` raised to the power `pow`. The
    argument `c` is a sequence of coefficients ordered from low to high.
    i.e., [1,2,3] is the series  ``P_0 + 2*P_1 + 3*P_2.``

    Parameters
    ----------
    c : array_like
        1-D array of Hermite series coefficients ordered from low to
        high.
    pow : integer
        Power to which the series will be raised
    maxpower : integer, optional
        Maximum power allowed. This is mainly to limit growth of the series
        to unmanageable size. Default is 16

    Returns
    -------
    coef : ndarray
        Hermite series of power.

    See Also
    --------
    hermeadd, hermesub, hermemulx, hermemul, hermediv

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermepow
    >>> hermepow([1, 2, 3], 2)
    array([23.,  28.,  46.,  12.,   9.])

    """
    # 调用内部函数 _pow 进行 Hermite 级数的乘幂操作
    return pu._pow(hermemul, c, pow, maxpower)


# 定义函数 hermeder,用于计算 Hermite_e 级数的微分
def hermeder(c, m=1, scl=1, axis=0):
    """
    Differentiate a Hermite_e series.

    Returns the series coefficients `c` differentiated `m` times along
    `axis`.  At each iteration the result is multiplied by `scl` (the
    scaling factor is for use in a linear change of variable). The argument
    `c` is an array of coefficients from low to high degree along each
    axis, e.g., [1,2,3] represents the series ``1*He_0 + 2*He_1 + 3*He_2``
    while [[1,2],[1,2]] represents ``1*He_0(x)*He_0(y) + 1*He_1(x)*He_0(y)
    + 2*He_0(x)*He_1(y) + 2*He_1(x)*He_1(y)`` if axis=0 is ``x`` and axis=1
    is ``y``.

    Parameters
    ----------
    c : array_like
        Array of Hermite_e series coefficients. If `c` is multidimensional
        the different axis correspond to different variables with the
        degree in each axis given by the corresponding index.
    m : int, optional
        Number of derivatives taken, must be non-negative. (Default: 1)
    scl : scalar, optional
        Each differentiation is multiplied by `scl`.  The end result is
        multiplication by ``scl**m``.  This is for use in a linear change of
        variable. (Default: 1)
    axis : int, optional
        Axis over which the derivative is taken. (Default: 0).

        .. versionadded:: 1.7.0

    Returns
    -------
    der : ndarray
        Hermite series of the derivative.

    See Also
    --------
    hermeint

    Notes
    -----
    In general, the result of differentiating a Hermite series does not
    resemble the same operation on a power series. Thus the result of this
    function may be "unintuitive," albeit correct; see Examples section
    below.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermeder
    >>> hermeder([ 1.,  1.,  1.,  1.])
    array([1.,  2.,  3.])
    >>> hermeder([-0.25,  1.,  1./2.,  1./3.,  1./4 ], m=2)
    array([1.,  2.,  3.])

    """
    # 将输入的 Hermite 系数数组 c 转换为至少是 1 维的 ndarray 对象
    c = np.array(c, ndmin=1, copy=True)
    # 如果数组 c 的数据类型字符在 '?bBhHiIlLqQpP' 中的任意一个,将其转换为 np.double 类型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    
    # 将 m 转换为整数,并赋给 cnt,用作求导的阶数
    cnt = pu._as_int(m, "the order of derivation")
    
    # 将 axis 转换为整数,并赋给 iaxis,表示操作的轴
    iaxis = pu._as_int(axis, "the axis")
    
    # 如果 cnt 小于 0,抛出值错误异常,要求求导的阶数必须是非负数
    if cnt < 0:
        raise ValueError("The order of derivation must be non-negative")
    
    # 根据数组 c 的维度调整 iaxis,确保其值在有效范围内
    iaxis = normalize_axis_index(iaxis, c.ndim)
    
    # 如果求导的阶数 cnt 为 0,直接返回原始数组 c
    if cnt == 0:
        return c
    
    # 将操作轴 iaxis 移动到数组 c 的最前面
    c = np.moveaxis(c, iaxis, 0)
    
    # 计算数组 c 的长度 n
    n = len(c)
    
    # 如果求导的阶数 cnt 大于等于数组长度 n,返回数组 c 的第一个元素乘以 0
    if cnt >= n:
        return c[:1] * 0
    else:
        # 否则,进行 cnt 次求导操作
        for i in range(cnt):
            n = n - 1  # 更新数组长度
            c *= scl  # 数组 c 每个元素乘以 scl
            # 创建一个空数组 der,用来存储求导后的结果
            der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
            # 按照求导的顺序计算每一阶导数
            for j in range(n, 0, -1):
                der[j - 1] = j * c[j]
            c = der  # 更新 c 为当前求导阶数的结果数组
    
    # 将操作轴 iaxis 移回到数组 c 的原始位置
    c = np.moveaxis(c, 0, iaxis)
    
    # 返回求导后的结果数组 c
    return c
# 定义函数 hermeint,用于对 Hermite_e 级数进行积分
def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
    """
    Integrate a Hermite_e series.

    Returns the Hermite_e series coefficients `c` integrated `m` times from
    `lbnd` along `axis`. At each iteration the resulting series is
    **multiplied** by `scl` and an integration constant, `k`, is added.
    The scaling factor is for use in a linear change of variable.  ("Buyer
    beware": note that, depending on what one is doing, one may want `scl`
    to be the reciprocal of what one might expect; for more information,
    see the Notes section below.)  The argument `c` is an array of
    coefficients from low to high degree along each axis, e.g., [1,2,3]
    represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
    represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
    2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.

    Parameters
    ----------
    c : array_like
        Array of Hermite_e series coefficients. If c is multidimensional
        the different axis correspond to different variables with the
        degree in each axis given by the corresponding index.
    m : int, optional
        Order of integration, must be positive. (Default: 1)
    k : {[], list, scalar}, optional
        Integration constant(s).  The value of the first integral at
        ``lbnd`` is the first value in the list, the value of the second
        integral at ``lbnd`` is the second value, etc.  If ``k == []`` (the
        default), all constants are set to zero.  If ``m == 1``, a single
        scalar can be given instead of a list.
    lbnd : scalar, optional
        The lower bound of the integral. (Default: 0)
    scl : scalar, optional
        Following each integration the result is *multiplied* by `scl`
        before the integration constant is added. (Default: 1)
    axis : int, optional
        Axis over which the integral is taken. (Default: 0).

        .. versionadded:: 1.7.0

    Returns
    -------
    S : ndarray
        Hermite_e series coefficients of the integral.

    Raises
    ------
    ValueError
        If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
        ``np.ndim(scl) != 0``.

    See Also
    --------
    hermeder

    Notes
    -----
    Note that the result of each integration is *multiplied* by `scl`.
    Why is this important to note?  Say one is making a linear change of
    variable :math:`u = ax + b` in an integral relative to `x`.  Then
    :math:`dx = du/a`, so one will need to set `scl` equal to
    :math:`1/a` - perhaps not what one would have first thought.

    Also note that, in general, the result of integrating a C-series needs
    to be "reprojected" onto the C-series basis set.  Thus, typically,
    the result of this function is "unintuitive," albeit correct; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermeint
    >>> hermeint([1, 2, 3]) # integrate once, value 0 at 0.
    array([1., 1., 1., 1.])
    """
    c = np.array(c, ndmin=1, copy=True)
    # 将输入的参数 c 转换为 numpy 数组,确保至少是一维的,并且是拷贝副本
    if c.dtype.char in '?bBhHiIlLqQpP':
        # 如果数组的数据类型是布尔型或整数型(有符号或无符号),则转换为双精度浮点型
        c = c.astype(np.double)
    if not np.iterable(k):
        # 如果 k 不可迭代,则将其转换为列表
        k = [k]
    cnt = pu._as_int(m, "the order of integration")
    # 将 m 转换为整数,用作积分的阶数
    iaxis = pu._as_int(axis, "the axis")
    # 将 axis 转换为整数,表示操作的轴向
    if cnt < 0:
        raise ValueError("The order of integration must be non-negative")
        # 如果积分的阶数小于 0,则抛出值错误异常
    if len(k) > cnt:
        raise ValueError("Too many integration constants")
        # 如果积分常数 k 的数量超过了积分的阶数 cnt,则抛出值错误异常
    if np.ndim(lbnd) != 0:
        raise ValueError("lbnd must be a scalar.")
        # 如果 lbnd 的维数不为 0(即不是标量),则抛出值错误异常
    if np.ndim(scl) != 0:
        raise ValueError("scl must be a scalar.")
        # 如果 scl 的维数不为 0(即不是标量),则抛出值错误异常
    iaxis = normalize_axis_index(iaxis, c.ndim)
    # 根据输入的轴索引 iaxis 和数组 c 的维数,规范化轴索引

    if cnt == 0:
        return c
        # 如果积分的阶数为 0,则直接返回输入的数组 c

    c = np.moveaxis(c, iaxis, 0)
    # 将数组 c 的轴 iaxis 移动到索引 0 的位置

    k = list(k) + [0]*(cnt - len(k))
    # 将积分常数 k 转换为列表形式,并在末尾补充零,使其长度达到积分阶数 cnt

    for i in range(cnt):
        n = len(c)
        # 获取数组 c 的长度
        c *= scl
        # 将数组 c 中的每个元素乘以标量 scl
        if n == 1 and np.all(c[0] == 0):
            c[0] += k[i]
            # 如果数组 c 只有一个元素且该元素全部为 0,则将其加上积分常数 k[i]
        else:
            tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
            # 创建一个形状为 (n+1, ...) 的空数组 tmp,数据类型与 c 相同
            tmp[0] = c[0]*0
            tmp[1] = c[0]
            # 设置 tmp 的前两个元素,用于存储积分后的系数
            for j in range(1, n):
                tmp[j + 1] = c[j]/(j + 1)
                # 计算每个系数的积分值
            tmp[0] += k[i] - hermeval(lbnd, tmp)
            # 计算整体的积分常数并减去边界值的 Hermite 插值
            c = tmp
            # 将 tmp 赋值给 c,继续进行下一阶的积分计算
    c = np.moveaxis(c, 0, iaxis)
    # 将数组 c 的轴 0 移回到 iaxis 的位置
    return c
    # 返回最终的积分结果数组 c
def hermeval(x, c, tensor=True):
    """
    Evaluate an HermiteE series at points x.

    If `c` is of length ``n + 1``, this function returns the value:

    .. math:: p(x) = c_0 * He_0(x) + c_1 * He_1(x) + ... + c_n * He_n(x)

    The parameter `x` is converted to an array only if it is a tuple or a
    list, otherwise it is treated as a scalar. In either case, either `x`
    or its elements must support multiplication and addition both with
    themselves and with the elements of `c`.

    If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`.  If
    `c` is multidimensional, then the shape of the result depends on the
    value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
    x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
    scalars have shape (,).

    Trailing zeros in the coefficients will be used in the evaluation, so
    they should be avoided if efficiency is a concern.

    Parameters
    ----------
    x : array_like, compatible object
        If `x` is a list or tuple, it is converted to an ndarray, otherwise
        it is left unchanged and treated as a scalar. In either case, `x`
        or its elements must support addition and multiplication with
        with themselves and with the elements of `c`.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree n are contained in c[n]. If `c` is multidimensional the
        remaining indices enumerate multiple polynomials. In the two
        dimensional case the coefficients may be thought of as stored in
        the columns of `c`.
    tensor : boolean, optional
        If True, the shape of the coefficient array is extended with ones
        on the right, one for each dimension of `x`. Scalars have dimension 0
        for this action. The result is that every column of coefficients in
        `c` is evaluated for every element of `x`. If False, `x` is broadcast
        over the columns of `c` for the evaluation.  This keyword is useful
        when `c` is multidimensional. The default value is True.

        .. versionadded:: 1.7.0

    Returns
    -------
    values : ndarray, algebra_like
        The shape of the return value is described above.

    See Also
    --------
    hermeval2d, hermegrid2d, hermeval3d, hermegrid3d

    Notes
    -----
    The evaluation uses Clenshaw recursion, aka synthetic division.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermeval
    >>> coef = [1,2,3]
    >>> hermeval(1, coef)
    3.0
    >>> hermeval([[1,2],[3,4]], coef)
    array([[ 3., 14.],
           [31., 54.]])

    """
    # 将 c 转换为至少是一维的 NumPy 数组,并确保其数据类型为双精度浮点数
    c = np.array(c, ndmin=1, copy=None)
    # 如果 c 的数据类型为布尔类型或整数类型,将其转换为双精度浮点数类型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    # 如果 x 是 tuple 或 list 类型,则将其转换为 NumPy 数组
    if isinstance(x, (tuple, list)):
        x = np.asarray(x)
    # 如果 x 是 NumPy 数组并且 tensor 参数为 True,则将 c 的形状重塑为 c.shape + (1,)*x.ndim
    if isinstance(x, np.ndarray) and tensor:
        c = c.reshape(c.shape + (1,)*x.ndim)

    # 如果 c 的长度为 1,设置 c0 为 c[0],c1 为 0
    if len(c) == 1:
        c0 = c[0]
        c1 = 0
    elif len(c) == 2:
        # 如果列表 c 的长度为 2,则执行以下操作
        c0 = c[0]
        c1 = c[1]
    else:
        # 如果列表 c 的长度不为 2,则执行以下操作
        nd = len(c)
        # 取倒数第二个元素作为 c0
        c0 = c[-2]
        # 取最后一个元素作为 c1
        c1 = c[-1]
        # 对于列表 c 中索引从 3 到最后一个元素的范围,依次进行以下操作
        for i in range(3, len(c) + 1):
            # 临时保存 c0 的值
            tmp = c0
            # 更新 nd 的值
            nd = nd - 1
            # 计算新的 c0 值
            c0 = c[-i] - c1*(nd - 1)
            # 更新 c1 的值
            c1 = tmp + c1*x
    # 返回 c0 + c1*x 的计算结果
    return c0 + c1*x
# 定义一个函数,用于在二维 HermiteE 系列上评估点 (x, y)
def hermeval2d(x, y, c):
    # 调用 _valnd 函数,返回 HermiteE 系列在给定点 (x, y) 处的值
    return pu._valnd(hermeval, c, x, y)


# 定义一个函数,用于在 x 和 y 的笛卡尔积上评估二维 HermiteE 系列
def hermegrid2d(x, y, c):
    """
    Evaluate a 2-D HermiteE series on the Cartesian product of x and y.

    This function returns the values:

    .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)

    where the points ``(a, b)`` consist of all pairs formed by taking
    `a` from `x` and `b` from `y`. The resulting points form a grid with
    `x` in the first dimension and `y` in the second.

    The parameters `x` and `y` are converted to arrays only if they are
    tuples or a lists, otherwise they are treated as scalars. In either
    case, either `x` and `y` or their elements must support multiplication
    and addition both with themselves and with the elements of `c`.

    If `c` has fewer than two dimensions, ones are implicitly appended to
    its shape to make it 2-D. The shape of the result will be c.shape[2:] +
    x.shape.

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points in the
        Cartesian product of `x` and `y`.  If `x` or `y` is a list or
        tuple, it is first converted to an ndarray, otherwise it is left
        unchanged and, if it isn't an ndarray, it is treated as a scalar.
    """
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree i,j are contained in ``c[i,j]``. If `c` has dimension
        greater than two the remaining indices enumerate multiple sets of
        coefficients.
        # 参数 c:系数数组,按照度为 i,j 的项的顺序排列。如果 `c` 的维度大于两,
        # 则其余的索引用来枚举多组系数。

    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points in the Cartesian
        product of `x` and `y`.
        # 返回值:ndarray 或兼容对象,二维多项式在 `x` 和 `y` 的笛卡尔积点上的值。

    See Also
    --------
    hermeval, hermeval2d, hermeval3d, hermegrid3d
        # 参见:hermeval, hermeval2d, hermeval3d, hermegrid3d

    Notes
    -----

    .. versionadded:: 1.7.0
        # 注意:添加于版本 1.7.0

    """
    return pu._gridnd(hermeval, c, x, y)
        # 调用 `pu._gridnd` 函数计算 Hermite 插值的结果,使用 `hermeval` 函数,
        # 系数数组 `c`,以及给定的 `x` 和 `y` 值作为参数。
# 返回一个 3-D Hermite_e 系列在给定点 (x, y, z) 处的值。

def hermeval3d(x, y, z, c):
    # 导入 `pu` 模块,并调用其 `_valnd` 函数来计算 HermiteE 系列的值
    return pu._valnd(hermeval, c, x, y, z)


# 在 x、y、z 的笛卡尔乘积上评估 3-D HermiteE 系列。

def hermegrid3d(x, y, z, c):
    # 返回形如 p(a,b,c) = \sum_{i,j,k} c_{i,j,k} * He_i(a) * He_j(b) * He_k(c) 的值,
    # 其中 (a, b, c) 由 x、y、z 中的所有三元组组成。
    # 结果形成一个网格,x 是第一维,y 是第二维,z 是第三维。
    # 导入 `pu` 模块,并调用其 `_valnd` 函数来计算 HermiteE 系列的值
    x, y, z : array_like, compatible objects
        The three dimensional series is evaluated at the points in the
        Cartesian product of `x`, `y`, and `z`.  If `x`, `y`, or `z` is a
        list or tuple, it is first converted to an ndarray, otherwise it is
        left unchanged and, if it isn't an ndarray, it is treated as a
        scalar.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree i,j are contained in ``c[i,j]``. If `c` has dimension
        greater than two the remaining indices enumerate multiple sets of
        coefficients.

这部分代码定义了函数的参数和说明,指定了输入参数的类型和用途。


    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points in the Cartesian
        product of `x` and `y`.

这里指明了函数的返回值类型和说明,描述了返回值是在 `x` 和 `y` 的笛卡尔积中计算的二维多项式的值。


    See Also
    --------
    hermeval, hermeval2d, hermegrid2d, hermeval3d

列出了与本函数相关的其他函数,供用户参考。


    Notes
    -----

    .. versionadded:: 1.7.0

    """

这里是函数的额外说明部分,标明了函数被加入的版本信息。


    return pu._gridnd(hermeval, c, x, y, z)

函数的实际实现部分,调用了 `pu._gridnd` 函数来计算 Hermite 多项式在给定点 `(x, y, z)` 处的值,使用了传入的系数 `c`。
def hermevander(x, deg):
    """Pseudo-Vandermonde matrix of given degree.

    Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
    `x`. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., i] = He_i(x),

    where ``0 <= i <= deg``. The leading indices of `V` index the elements of
    `x` and the last index is the degree of the HermiteE polynomial.

    If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the
    array ``V = hermevander(x, n)``, then ``np.dot(V, c)`` and
    ``hermeval(x, c)`` are the same up to roundoff. This equivalence is
    useful both for least squares fitting and for the evaluation of a large
    number of HermiteE series of the same degree and sample points.

    Parameters
    ----------
    x : array_like
        Array of points. The dtype is converted to float64 or complex128
        depending on whether any of the elements are complex. If `x` is
        scalar it is converted to a 1-D array.
    deg : int
        Degree of the resulting matrix.

    Returns
    -------
    vander : ndarray
        The pseudo-Vandermonde matrix. The shape of the returned matrix is
        ``x.shape + (deg + 1,)``, where The last index is the degree of the
        corresponding HermiteE polynomial.  The dtype will be the same as
        the converted `x`.

    Examples
    --------
    >>> from numpy.polynomial.hermite_e import hermevander
    >>> x = np.array([-1, 0, 1])
    >>> hermevander(x, 3)
    array([[ 1., -1.,  0.,  2.],
           [ 1.,  0., -1., -0.],
           [ 1.,  1.,  0., -2.]])

    """
    # Convert `deg` to an integer, raising a ValueError if it's negative
    ideg = pu._as_int(deg, "deg")
    if ideg < 0:
        raise ValueError("deg must be non-negative")

    # Ensure `x` is converted to a 1-D array of type float64 or complex128
    x = np.array(x, copy=None, ndmin=1) + 0.0

    # Create dimensions for the output array `v`
    dims = (ideg + 1,) + x.shape
    dtyp = x.dtype

    # Create an empty array `v` with the computed dimensions and type
    v = np.empty(dims, dtype=dtyp)

    # Initialize the first row of `v` to represent the constant term of the polynomial
    v[0] = x*0 + 1

    # Fill in the rest of `v` based on Hermite polynomial recursion
    if ideg > 0:
        v[1] = x
        for i in range(2, ideg + 1):
            v[i] = (v[i-1]*x - v[i-2]*(i - 1))

    # Move the leading index of `v` to the last index for final output
    return np.moveaxis(v, 0, -1)


def hermevander2d(x, y, deg):
    """Pseudo-Vandermonde matrix of given degrees.

    Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
    points ``(x, y)``. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., (deg[1] + 1)*i + j] = He_i(x) * He_j(y),

    where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of
    `V` index the points ``(x, y)`` and the last index encodes the degrees of
    the HermiteE polynomials.

    If ``V = hermevander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
    correspond to the elements of a 2-D coefficient array `c` of shape
    (xdeg + 1, ydeg + 1) in the order

    .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...

    and ``np.dot(V, c.flat)`` and ``hermeval2d(x, y, c)`` will be the same
    up to roundoff. This equivalence is useful both for least squares
    fitting and for the evaluation of a large number of 2-D HermiteE
    series of the same degrees and sample points.
    """
    # This function is intentionally left without implementation for now.
    pass
    Parameters
    ----------
    x, y : array_like
        Arrays of point coordinates, all of the same shape. The dtypes
        will be converted to either float64 or complex128 depending on
        whether any of the elements are complex. Scalars are converted to
        1-D arrays.
    deg : list of ints
        List of maximum degrees of the form [x_deg, y_deg].

    Returns
    -------
    vander2d : ndarray
        The shape of the returned matrix is ``x.shape + (order,)``, where
        :math:`order = (deg[0]+1)*(deg[1]+1)`.  The dtype will be the same
        as the converted `x` and `y`.

    See Also
    --------
    hermevander, hermevander3d, hermeval2d, hermeval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    """
    # 调用 `_vander_nd_flat` 函数,计算 Hermite 多项式的 Vandermonde 矩阵
    return pu._vander_nd_flat((hermevander, hermevander), (x, y), deg)
def hermevander3d(x, y, z, deg):
    """Generate a pseudo-Vandermonde matrix for 3D Hermite polynomials.

    Returns a pseudo-Vandermonde matrix `V` for given degrees `deg` and sample
    points `(x, y, z)`. The matrix `V` is structured such that the elements are
    products of Hermite polynomials in `x`, `y`, and `z` coordinates.

    Parameters
    ----------
    x, y, z : array_like
        Arrays of point coordinates for the sample points.
    deg : list of ints
        List of maximum degrees `[x_deg, y_deg, z_deg]` for Hermite polynomials.

    Returns
    -------
    vander3d : ndarray
        Pseudo-Vandermonde matrix `V` of shape `(x.shape + (order,))`, where
        `order = (deg[0]+1) * (deg[1]+1) * (deg[2]+1)`.

    See Also
    --------
    hermevander, hermeval2d, hermeval3d

    Notes
    -----
    This function calculates the pseudo-Vandermonde matrix using the product of
    Hermite polynomials, which is useful for fitting data with 3D Hermite series.

    .. versionadded:: 1.7.0

    """
    return pu._vander_nd_flat((hermevander, hermevander, hermevander), (x, y, z), deg)
    deg : int or 1-D array_like
        # 多项式拟合的阶数或阶数组成的一维数组。如果 `deg` 是一个整数,
        # 则拟合包括从0到第 `deg` 阶的所有项。对于 NumPy 版本 >= 1.11.0,
        # 可以使用指定要包含的项阶数的整数列表。
    rcond : float, optional
        # 拟合的相对条件数。比最大奇异值小的奇异值相对于最大奇异值的倍数将被忽略。
        # 默认值是 len(x)*eps,其中 eps 是浮点类型的相对精度,在大多数情况下约为 2e-16。
    full : bool, optional
        # 控制返回值的性质。当为 False(默认)时,只返回系数;当为 True 时,
        # 还返回奇异值分解的诊断信息。
    w : array_like, shape (`M`,), optional
        # 权重数组。如果不为 None,则权重 `w[i]` 应用于 `x[i]` 处的未平方残差 `y[i] - y_hat[i]`。
        # 理想情况下,权重应选择使得所有乘积 `w[i]*y[i]` 的误差具有相同的方差。
        # 当使用逆方差加权时,使用 `w[i] = 1/sigma(y[i])`。默认值为 None。

    Returns
    -------
    coef : ndarray, shape (M,) or (M, K)
        # 按升序排列的 HermiteE 系数。如果 `y` 是二维的,则数据的第 k 列的系数在列 `k` 中。

    [residuals, rank, singular_values, rcond] : list
        # 仅当 ``full == True`` 时返回这些值

        - residuals -- 最小二乘拟合的平方残差和
        - rank -- 缩放后的 Vandermonde 矩阵的数值秩
        - singular_values -- 缩放后的 Vandermonde 矩阵的奇异值
        - rcond -- `rcond` 的值。

        更多细节请参阅 `numpy.linalg.lstsq`。

    Warns
    -----
    RankWarning
        # 最小二乘拟合中系数矩阵的秩不足。仅当 ``full = False`` 时引发警告。
        # 可以通过以下方式关闭警告:

        >>> import warnings
        >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)

    See Also
    --------
    numpy.polynomial.chebyshev.chebfit
    numpy.polynomial.legendre.legfit
    numpy.polynomial.polynomial.polyfit
    numpy.polynomial.hermite.hermfit
    numpy.polynomial.laguerre.lagfit
    hermeval : 评估 HermiteE 系列。
    hermevander : HermiteE 系列的伪 Vandermonde 矩阵。
    hermeweight : HermiteE 权重函数。
    numpy.linalg.lstsq : 从矩阵计算最小二乘拟合。
    scipy.interpolate.UnivariateSpline : 计算样条拟合。

    Notes
    -----
    # 解决方案是最小化加权平方误差的 HermiteE 系列 `p` 的系数,其中

    .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
    # 返回 HermiteE 系列的拟合结果,通过解决奇异值分解的矩阵方程来实现
    return pu._fit(hermevander, x, y, deg, rcond, full, w)
# c is a trimmed copy
# 使用`pu.as_series`将`c`转换为系列(可能是多项式系列),并返回第一个元素的引用
[c] = pu.as_series([c])

# 如果系列`c`的长度小于2,抛出数值错误异常,要求系列至少包含1阶多项式
if len(c) < 2:
    raise ValueError('Series must have maximum degree of at least 1.')

# 如果系列`c`的长度为2,直接返回一个包含根的数组,根据HermiteE系列的定义
if len(c) == 2:
    return np.array([[-c[0]/c[1]]])
    # 生成厄米特伴随矩阵,反转其行列顺序
    m = hermecompanion(c)[::-1,::-1]
    # 计算反转后矩阵的特征值
    r = la.eigvals(m)
    # 对特征值进行排序
    r.sort()
    # 返回排序后的特征值数组
    return r
# 定义一个函数用于计算标准化 HermiteE 多项式
def _normed_hermite_e_n(x, n):
    """
    Evaluate a normalized HermiteE polynomial.

    Compute the value of the normalized HermiteE polynomial of degree ``n``
    at the points ``x``.

    Parameters
    ----------
    x : ndarray of double.
        Points at which to evaluate the function
    n : int
        Degree of the normalized HermiteE function to be evaluated.

    Returns
    -------
    values : ndarray
        The shape of the return value is described above.

    Notes
    -----
    .. versionadded:: 1.10.0

    This function is needed for finding the Gauss points and integration
    weights for high degrees. The values of the standard HermiteE functions
    overflow when n >= 207.

    """
    # 如果 n 等于 0,则返回一个形状与 x 相同的数组,其值为标准化常数
    if n == 0:
        return np.full(x.shape, 1/np.sqrt(np.sqrt(2*np.pi)))

    # 初始化 HermiteE 多项式的前两项
    c0 = 0.
    c1 = 1./np.sqrt(np.sqrt(2*np.pi))
    nd = float(n)
    # 循环计算 HermiteE 多项式的后续项直到第 n 项
    for i in range(n - 1):
        tmp = c0
        c0 = -c1*np.sqrt((nd - 1.)/nd)
        c1 = tmp + c1*x*np.sqrt(1./nd)
        nd = nd - 1.0
    # 返回计算结果
    return c0 + c1*x


def hermegauss(deg):
    """
    Gauss-HermiteE quadrature.

    Computes the sample points and weights for Gauss-HermiteE quadrature.
    These sample points and weights will correctly integrate polynomials of
    degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`
    with the weight function :math:`f(x) = \\exp(-x^2/2)`.

    Parameters
    ----------
    deg : int
        Number of sample points and weights. It must be >= 1.

    Returns
    -------
    x : ndarray
        1-D ndarray containing the sample points.
    y : ndarray
        1-D ndarray containing the weights.

    Notes
    -----

    .. versionadded:: 1.7.0

    The results have only been tested up to degree 100, higher degrees may
    be problematic. The weights are determined by using the fact that

    .. math:: w_k = c / (He'_n(x_k) * He_{n-1}(x_k))

    where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
    is the k'th root of :math:`He_n`, and then scaling the results to get
    the right value when integrating 1.

    """
    # 将 deg 转换为整数,如果小于等于 0 则抛出 ValueError
    ideg = pu._as_int(deg, "deg")
    if ideg <= 0:
        raise ValueError("deg must be a positive integer")

    # 初始化 HermiteE 多项式的伴随矩阵的第一个近似根
    c = np.array([0]*deg + [1])
    m = hermecompanion(c)
    x = la.eigvalsh(m)

    # 通过一次牛顿法提升根的精度
    dy = _normed_hermite_e_n(x, ideg)
    df = _normed_hermite_e_n(x, ideg - 1) * np.sqrt(ideg)
    x -= dy/df

    # 计算权重,通过缩放因子避免可能的数值溢出
    fm = _normed_hermite_e_n(x, ideg - 1)
    fm /= np.abs(fm).max()
    w = 1/(fm * fm)

    # 对 Hermite_e 进行对称化处理
    w = (w + w[::-1])/2
    x = (x - x[::-1])/2

    # 缩放权重以获得正确的值
    w *= np.sqrt(2*np.pi) / w.sum()

    # 返回样本点和权重数组
    return x, w


def hermeweight(x):
    """
    Hermite_e 多项式的权重函数。

    权重函数为 :math:`\\exp(-x^2/2)`,积分区间为 :math:`[-\\inf, \\inf]`。HermiteE 多项式
    相对于这个权重函数是正交的,但不是归一化的。

    Parameters
    ----------
    x : array_like
       要计算权重函数的数值。

    Returns
    -------
    w : ndarray
       在 `x` 处的权重函数值。

    Notes
    -----
    Hermite_e 多项式权重函数的版本新增于 1.7.0。

    """
    # 计算 Hermite_e 多项式权重函数的值,即 exp(-0.5 * x^2)
    w = np.exp(-.5*x**2)
    # 返回计算得到的权重函数值
    return w
# HermiteE series class
#

class HermiteE(ABCPolyBase):
    """An HermiteE series class.

    The HermiteE class provides the standard Python numerical methods
    '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
    attributes and methods listed below.

    Parameters
    ----------
    coef : array_like
        HermiteE coefficients in order of increasing degree, i.e,
        ``(1, 2, 3)`` gives ``1*He_0(x) + 2*He_1(X) + 3*He_2(x)``.
    domain : (2,) array_like, optional
        Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
        to the interval ``[window[0], window[1]]`` by shifting and scaling.
        The default value is [-1, 1].
    window : (2,) array_like, optional
        Window, see `domain` for its use. The default value is [-1, 1].

        .. versionadded:: 1.6.0
    symbol : str, optional
        Symbol used to represent the independent variable in string
        representations of the polynomial expression, e.g. for printing.
        The symbol must be a valid Python identifier. Default value is 'x'.

        .. versionadded:: 1.24

    """
    # Virtual Functions
    # 静态方法,用于加法操作
    _add = staticmethod(hermeadd)
    # 静态方法,用于减法操作
    _sub = staticmethod(hermesub)
    # 静态方法,用于乘法操作
    _mul = staticmethod(hermemul)
    # 静态方法,用于整数除法操作
    _div = staticmethod(hermediv)
    # 静态方法,用于幂运算操作
    _pow = staticmethod(hermepow)
    # 静态方法,用于计算多项式在给定点的值
    _val = staticmethod(hermeval)
    # 静态方法,用于多项式的积分操作
    _int = staticmethod(hermeint)
    # 静态方法,用于多项式的微分操作
    _der = staticmethod(hermeder)
    # 静态方法,用于拟合数据得到多项式系数
    _fit = staticmethod(hermefit)
    # 静态方法,用于生成通过指定点的直线
    _line = staticmethod(hermeline)
    # 静态方法,用于计算多项式的根
    _roots = staticmethod(hermeroots)
    # 静态方法,用于根据给定的根生成多项式
    _fromroots = staticmethod(hermefromroots)

    # Virtual properties
    # 定义多项式的定义域
    domain = np.array(hermedomain)
    # 定义多项式的窗口
    window = np.array(hermedomain)
    # 基函数名称
    basis_name = 'He'

.\numpy\numpy\polynomial\hermite_e.pyi

# 引入必要的类型提示模块
from typing import Any

# 从 numpy 库中引入特定的类型和函数
from numpy import int_
from numpy.typing import NDArray
from numpy.polynomial._polybase import ABCPolyBase
from numpy.polynomial.polyutils import trimcoef

# 定义公开的模块变量列表
__all__: list[str]

# 将 trimcoef 函数重命名为 hermetrim
hermetrim = trimcoef

# 定义以下函数,用于进行 Hermite 多项式和多项式系数之间的转换
def poly2herme(pol): ...
def herme2poly(c): ...

# 定义一些用于 Hermite 多项式的特定常量数组
hermedomain: NDArray[int_]
hermezero: NDArray[int_]
hermeone: NDArray[int_]
hermex: NDArray[int_]

# 定义以下函数,用于 Hermite 多项式的基本运算和操作
def hermeline(off, scl): ...
def hermefromroots(roots): ...
def hermeadd(c1, c2): ...
def hermesub(c1, c2): ...
def hermemulx(c): ...
def hermemul(c1, c2): ...
def hermediv(c1, c2): ...
def hermepow(c, pow, maxpower=...): ...
def hermeder(c, m=..., scl=..., axis=...): ...
def hermeint(c, m=..., k = ..., lbnd=..., scl=..., axis=...): ...
def hermeval(x, c, tensor=...): ...
def hermeval2d(x, y, c): ...
def hermegrid2d(x, y, c): ...
def hermeval3d(x, y, z, c): ...
def hermegrid3d(x, y, z, c): ...
def hermevander(x, deg): ...
def hermevander2d(x, y, deg): ...
def hermevander3d(x, y, z, deg): ...
def hermefit(x, y, deg, rcond=..., full=..., w=...): ...
def hermecompanion(c): ...
def hermeroots(c): ...
def hermegauss(deg): ...
def hermeweight(x): ...

# 定义 HermiteE 类,继承自 ABCPolyBase 类
class HermiteE(ABCPolyBase):
    # 定义类的属性
    domain: Any
    window: Any
    basis_name: Any

.\numpy\numpy\polynomial\laguerre.py

# 引入必要的库和模块
import numpy as np  # 引入 NumPy 库,用于数值计算
import numpy.linalg as la  # 引入 NumPy 的线性代数模块
from numpy.lib.array_utils import normalize_axis_index  # 从 NumPy 库的数组工具模块中引入数组轴索引归一化函数

# 从当前包中引入其他模块和函数
from . import polyutils as pu  # 从当前包中引入 polyutils 模块并重命名为 pu
from ._polybase import ABCPolyBase  # 从当前包的 _polybase 模块中引入 ABCPolyBase 类

# 声明本模块中公开的符号列表
__all__ = [
    'lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline', 'lagadd',
    'lagsub', 'lagmulx', 'lagmul', 'lagdiv', 'lagpow', 'lagval', 'lagder',
    'lagint', 'lag2poly', 'poly2lag', 'lagfromroots', 'lagvander',
    'lagfit', 'lagtrim', 'lagroots', 'Laguerre', 'lagval2d', 'lagval3d',
    'laggrid2d', 'laggrid3d', 'lagvander2d', 'lagvander3d', 'lagcompanion',
    'laggauss', 'lagweight'
]

# 将 pu.trimcoef 函数重命名为 lagtrim,便于使用
lagtrim = pu.trimcoef


def poly2lag(pol):
    """
    poly2lag(pol)

    Convert a polynomial to a Laguerre series.

    Convert an array representing the coefficients of a polynomial (relative
    to the "standard" basis) ordered from lowest degree to highest, to an
    array of the coefficients of the equivalent Laguerre series, ordered
    from lowest to highest degree.

    Parameters
    ----------
    pol : array_like
        1-D array containing the polynomial coefficients

    Returns
    -------
    c : ndarray
        1-D array containing the coefficients of the equivalent Laguerre
        series.

    See Also
    --------
    lag2poly

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import poly2lag
    >>> poly2lag(np.arange(4))
    array([ 23., -63.,  58., -18.])

    """
    [pol] = pu.as_series([pol])  # 将输入的 pol 转换为系列(数组)
    res = 0  # 初始化结果变量 res
    # 从高次到低次处理多项式的系数
    for p in pol[::-1]:
        # 通过 lagadd 和 lagmulx 函数实现 Laguerre 系列转换过程
        res = lagadd(lagmulx(res), p)
    return res  # 返回转换后的 Laguerre 系列


def lag2poly(c):
    """
    Convert a Laguerre series to a polynomial.

    ```
    
    Convert an array representing the coefficients of a Laguerre series,
    ordered from lowest degree to highest, to an array of the coefficients
    of the equivalent polynomial (relative to the "standard" basis) ordered
    from lowest to highest degree.

    Parameters
    ----------
    c : array_like
        1-D array containing the Laguerre series coefficients, ordered
        from lowest order term to highest.

    Returns
    -------
    pol : ndarray
        1-D array containing the coefficients of the equivalent polynomial
        (relative to the "standard" basis) ordered from lowest order term
        to highest.

    See Also
    --------
    poly2lag

    Notes
    -----
    The easy way to do conversions between polynomial basis sets
    is to use the convert method of a class instance.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lag2poly
    >>> lag2poly([ 23., -63.,  58., -18.])
    array([0., 1., 2., 3.])

    """
    # 导入必要的多项式操作函数:加法、减法、乘法
    from .polynomial import polyadd, polysub, polymulx

    # 将输入的系数数组 c 规范化为多项式系数对象
    [c] = pu.as_series([c])
    # 获取系数数组的长度
    n = len(c)
    # 如果数组长度为1,则直接返回该系数数组作为多项式的系数
    if n == 1:
        return c
    else:
        # 获取系数数组的倒数第二个和最后一个系数
        c0 = c[-2]
        c1 = c[-1]
        # i 表示当前处理的 c1 的次数
        for i in range(n - 1, 1, -1):
            # 临时保存 c0
            tmp = c0
            # 更新 c0 为当前处理的 c[i-2] 减去 c1 * (i-1) / i
            c0 = polysub(c[i - 2], (c1*(i - 1))/i)
            # 更新 c1 为 tmp 加上 (2*i - 1)*c1 减去 c1 * x 的多项式乘法结果除以 i
            c1 = polyadd(tmp, polysub((2*i - 1)*c1, polymulx(c1))/i)
        # 返回最终的多项式系数数组,即 c0 加上 c1 减去 c1 * x 的多项式乘法结果
        return polyadd(c0, polysub(c1, polymulx(c1)))
# 这些是整数类型的常数数组,以便与最广泛的其他类型兼容,如Decimal。

# Laguerre
# Laguerre函数的定义域
lagdomain = np.array([0., 1.])

# Laguerre系数,表示零
lagzero = np.array([0])

# Laguerre系数,表示一
lagone = np.array([1])

# Laguerre系数,表示标识函数x
lagx = np.array([1, -1])


def lagline(off, scl):
    """
    Laguerre级数,其图形是一条直线。

    Parameters
    ----------
    off, scl : scalars
        指定的直线由``off + scl*x``给出。

    Returns
    -------
    y : ndarray
        表示``off + scl*x``的Laguerre系列的数组表示形式。

    See Also
    --------
    numpy.polynomial.polynomial.polyline
    numpy.polynomial.chebyshev.chebline
    numpy.polynomial.legendre.legline
    numpy.polynomial.hermite.hermline
    numpy.polynomial.hermite_e.hermeline

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagline, lagval
    >>> lagval(0,lagline(3, 2))
    3.0
    >>> lagval(1,lagline(3, 2))
    5.0

    """
    if scl != 0:
        return np.array([off + scl, -scl])
    else:
        return np.array([off])


def lagfromroots(roots):
    """
    根据给定的根生成Laguerre级数。

    函数返回多项式的系数

    .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),

    的Laguerre形式,其中 :math:`r_n` 是`roots`中指定的根。如果一个零有多重性为n,
    那么它必须在`roots`中出现n次。例如,如果2是三重根,3是双重根,
    那么`roots`看起来像 [2, 2, 2, 3, 3]。根可以以任何顺序出现。

    如果返回的系数是 `c`,那么

    .. math:: p(x) = c_0 + c_1 * L_1(x) + ... +  c_n * L_n(x)

    最后一项的系数通常不是Laguerre形式中的1。

    Parameters
    ----------
    roots : array_like
        包含根的序列。

    Returns
    -------
    out : ndarray
        系数的1-D数组。如果所有根都是实数,则 `out` 是实数组;如果一些根是复数,
        则 `out` 是复数数组,即使结果中的所有系数都是实数(参见下面的示例)。

    See Also
    --------
    numpy.polynomial.polynomial.polyfromroots
    numpy.polynomial.legendre.legfromroots
    numpy.polynomial.chebyshev.chebfromroots
    numpy.polynomial.hermite.hermfromroots
    numpy.polynomial.hermite_e.hermefromroots

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagfromroots, lagval
    >>> coef = lagfromroots((-1, 0, 1))
    >>> lagval((-1, 0, 1), coef)
    array([0.,  0.,  0.])
    >>> coef = lagfromroots((-1j, 1j))
    >>> lagval((-1j, 1j), coef)
    array([0.+0.j, 0.+0.j])

    """
    return pu._fromroots(lagline, lagmul, roots)


def lagadd(c1, c2):
    """
    ```py
    Add one Laguerre series to another.

    Returns the sum of two Laguerre series `c1` + `c2`.  The arguments
    are sequences of coefficients ordered from lowest order term to
    highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Laguerre series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the Laguerre series of their sum.

    See Also
    --------
    lagsub, lagmulx, lagmul, lagdiv, lagpow

    Notes
    -----
    Unlike multiplication, division, etc., the sum of two Laguerre series
    is a Laguerre series (without having to "reproject" the result onto
    the basis set) so addition, just like that of "standard" polynomials,
    is simply "component-wise."

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagadd
    >>> lagadd([1, 2, 3], [1, 2, 3, 4])
    array([2.,  4.,  6.,  4.])

    """
    # 使用私有函数 `_add` 计算两个 Laguerre 级数的和,并返回结果
    return pu._add(c1, c2)
def lagsub(c1, c2):
    """
    Subtract one Laguerre series from another.

    Returns the difference of two Laguerre series `c1` - `c2`.  The
    sequences of coefficients are from lowest order term to highest, i.e.,
    [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Laguerre series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Of Laguerre series coefficients representing their difference.

    See Also
    --------
    lagadd, lagmulx, lagmul, lagdiv, lagpow

    Notes
    -----
    Unlike multiplication, division, etc., the difference of two Laguerre
    series is a Laguerre series (without having to "reproject" the result
    onto the basis set) so subtraction, just like that of "standard"
    polynomials, is simply "component-wise."

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagsub
    >>> lagsub([1, 2, 3, 4], [1, 2, 3])
    array([0.,  0.,  0.,  4.])

    """
    # 使用 pu._sub 函数计算 Laguerre 系列 c1 和 c2 的差
    return pu._sub(c1, c2)


def lagmulx(c):
    """Multiply a Laguerre series by x.

    Multiply the Laguerre series `c` by x, where x is the independent
    variable.


    Parameters
    ----------
    c : array_like
        1-D array of Laguerre series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the result of the multiplication.

    See Also
    --------
    lagadd, lagsub, lagmul, lagdiv, lagpow

    Notes
    -----
    The multiplication uses the recursion relationship for Laguerre
    polynomials in the form

    .. math::

        xP_i(x) = (-(i + 1)*P_{i + 1}(x) + (2i + 1)P_{i}(x) - iP_{i - 1}(x))

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagmulx
    >>> lagmulx([1, 2, 3])
    array([-1.,  -1.,  11.,  -9.])

    """
    # 将输入的系数数组 c 转换为 Laguerre 系列
    [c] = pu.as_series([c])
    # 处理零系列的特殊情况
    if len(c) == 1 and c[0] == 0:
        return c

    # 初始化乘积数组 prd,长度比输入数组 c 长 1
    prd = np.empty(len(c) + 1, dtype=c.dtype)
    prd[0] = c[0]  # 设置第一个值为 c[0]
    prd[1] = -c[0]  # 设置第二个值为 -c[0]
    # 迭代计算 Laguerre 系列的乘积
    for i in range(1, len(c)):
        prd[i + 1] = -c[i] * (i + 1)
        prd[i] += c[i] * (2 * i + 1)
        prd[i - 1] -= c[i] * i
    return prd


def lagmul(c1, c2):
    """
    Multiply one Laguerre series by another.

    Returns the product of two Laguerre series `c1` * `c2`.  The arguments
    are sequences of coefficients, from lowest order "term" to highest,
    e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Laguerre series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Of Laguerre series coefficients representing their product.

    See Also
    --------
    lagadd, lagsub, lagmulx, lagdiv, lagpow

    Notes
    -----
    In general, the (polynomial) product of two C-series results in terms
    that are summed over the range of the series.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagmul
    >>> lagmul([1, 2, 3], [4, 5])
    array([ 4., 13., 22., 15.])

    """
    # 使用 pu._mulx 函数计算 Laguerre 系列 c1 和 c2 的乘积
    return pu._mulx(c1, c2)
    # s1, s2 are trimmed copies
    [c1, c2] = pu.as_series([c1, c2])

    # Determine the shorter series between c1 and c2
    if len(c1) > len(c2):
        c = c2
        xs = c1
    else:
        c = c1
        xs = c2

    # Compute coefficients based on the length of c
    if len(c) == 1:
        c0 = c[0]*xs
        c1 = 0
    elif len(c) == 2:
        c0 = c[0]*xs
        c1 = c[1]*xs
    else:
        nd = len(c)
        c0 = c[-2]*xs
        c1 = c[-1]*xs
        # Iterate to compute higher order coefficients using Laguerre polynomial operations
        for i in range(3, len(c) + 1):
            tmp = c0
            nd = nd - 1
            c0 = lagsub(c[-i]*xs, (c1*(nd - 1))/nd)
            c1 = lagadd(tmp, lagsub((2*nd - 1)*c1, lagmulx(c1))/nd)

    # Return the sum of c0 and modified c1 coefficients
    return lagadd(c0, lagsub(c1, lagmulx(c1)))
# 定义函数 lagdiv,用于计算两个拉盖尔级数的除法
def lagdiv(c1, c2):
    """
    Divide one Laguerre series by another.

    Returns the quotient-with-remainder of two Laguerre series
    `c1` / `c2`.  The arguments are sequences of coefficients from lowest
    order "term" to highest, e.g., [1,2,3] represents the series
    ``P_0 + 2*P_1 + 3*P_2``.

    Parameters
    ----------
    c1, c2 : array_like
        1-D arrays of Laguerre series coefficients ordered from low to
        high.

    Returns
    -------
    [quo, rem] : ndarrays
        Of Laguerre series coefficients representing the quotient and
        remainder.

    See Also
    --------
    lagadd, lagsub, lagmulx, lagmul, lagpow

    Notes
    -----
    In general, the (polynomial) division of one Laguerre series by another
    results in quotient and remainder terms that are not in the Laguerre
    polynomial basis set.  Thus, to express these results as a Laguerre
    series, it is necessary to "reproject" the results onto the Laguerre
    basis set, which may produce "unintuitive" (but correct) results; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagdiv
    >>> lagdiv([  8., -13.,  38., -51.,  36.], [0, 1, 2])
    (array([1., 2., 3.]), array([0.]))
    >>> lagdiv([  9., -12.,  38., -51.,  36.], [0, 1, 2])
    (array([1., 2., 3.]), array([1., 1.]))

    """
    # 使用私有函数 _div 来实现拉盖尔级数的除法
    return pu._div(lagmul, c1, c2)


# 定义函数 lagpow,用于计算拉盖尔级数的幂
def lagpow(c, pow, maxpower=16):
    """Raise a Laguerre series to a power.

    Returns the Laguerre series `c` raised to the power `pow`. The
    argument `c` is a sequence of coefficients ordered from low to high.
    i.e., [1,2,3] is the series  ``P_0 + 2*P_1 + 3*P_2.``

    Parameters
    ----------
    c : array_like
        1-D array of Laguerre series coefficients ordered from low to
        high.
    pow : integer
        Power to which the series will be raised
    maxpower : integer, optional
        Maximum power allowed. This is mainly to limit growth of the series
        to unmanageable size. Default is 16

    Returns
    -------
    coef : ndarray
        Laguerre series of power.

    See Also
    --------
    lagadd, lagsub, lagmulx, lagmul, lagdiv

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagpow
    >>> lagpow([1, 2, 3], 2)
    array([ 14., -16.,  56., -72.,  54.])

    """
    # 使用私有函数 _pow 来实现拉盖尔级数的幂运算
    return pu._pow(lagmul, c, pow, maxpower)


# 定义函数 lagder,用于计算拉盖尔级数的微分
def lagder(c, m=1, scl=1, axis=0):
    """
    Differentiate a Laguerre series.

    Returns the Laguerre series coefficients `c` differentiated `m` times
    along `axis`.  At each iteration the result is multiplied by `scl` (the
    scaling factor is for use in a linear change of variable). The argument
    `c` is an array of coefficients from low to high degree along each
    axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2``
    while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) +
    2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is
    ``y``.

    """
    # 使用私有函数 _der 来实现拉盖尔级数的微分
    return pu._der(lagmul, c, m, scl, axis)
    # 将输入的系列系数转换为 numpy 数组,确保至少为一维,并复制数据
    c = np.array(c, ndmin=1, copy=True)
    
    # 如果系列系数的数据类型是布尔型、整型或长整型,则转换为双精度浮点型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    
    # 将导数阶数转换为整数,用于计数,并验证其非负性
    cnt = pu._as_int(m, "the order of derivation")
    
    # 将轴的索引转换为整数
    iaxis = pu._as_int(axis, "the axis")
    
    # 如果导数阶数小于 0,则抛出数值错误
    if cnt < 0:
        raise ValueError("The order of derivation must be non-negative")
    
    # 根据轴的索引规范化轴的索引值,确保其在合法范围内
    iaxis = normalize_axis_index(iaxis, c.ndim)
    
    # 如果导数阶数为 0,则直接返回输入的系列系数
    if cnt == 0:
        return c
    
    # 将指定轴移动到数组的第一个位置
    c = np.moveaxis(c, iaxis, 0)
    
    # 获取系列系数的长度
    n = len(c)
    
    # 如果导数阶数大于等于系列长度,则返回长度为 1 的数组乘以 0
    if cnt >= n:
        c = c[:1]*0
    else:
        # 循环进行导数操作,每次操作将系数乘以 scl,并更新系数数组
        for i in range(cnt):
            n = n - 1
            c *= scl
            # 创建一个空的数组来存储导数结果
            der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
            # 计算导数值并更新系数数组
            for j in range(n, 1, -1):
                der[j - 1] = -c[j]
                c[j - 1] += c[j]
            der[0] = -c[1]
            c = der
    
    # 将第一个位置的轴移回原来的位置
    c = np.moveaxis(c, 0, iaxis)
    
    # 返回最终的 Laguerre 系列导数结果数组
    return c
# 定义一个函数 lagint,用于对拉盖尔级数进行积分
def lagint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
    """
    Integrate a Laguerre series.

    Returns the Laguerre series coefficients `c` integrated `m` times from
    `lbnd` along `axis`. At each iteration the resulting series is
    **multiplied** by `scl` and an integration constant, `k`, is added.
    The scaling factor is for use in a linear change of variable.  ("Buyer
    beware": note that, depending on what one is doing, one may want `scl`
    to be the reciprocal of what one might expect; for more information,
    see the Notes section below.)  The argument `c` is an array of
    coefficients from low to high degree along each axis, e.g., [1,2,3]
    represents the series ``L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]]
    represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) +
    2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.


    Parameters
    ----------
    c : array_like
        Array of Laguerre series coefficients. If `c` is multidimensional
        the different axis correspond to different variables with the
        degree in each axis given by the corresponding index.
    m : int, optional
        Order of integration, must be positive. (Default: 1)
    k : {[], list, scalar}, optional
        Integration constant(s).  The value of the first integral at
        ``lbnd`` is the first value in the list, the value of the second
        integral at ``lbnd`` is the second value, etc.  If ``k == []`` (the
        default), all constants are set to zero.  If ``m == 1``, a single
        scalar can be given instead of a list.
    lbnd : scalar, optional
        The lower bound of the integral. (Default: 0)
    scl : scalar, optional
        Following each integration the result is *multiplied* by `scl`
        before the integration constant is added. (Default: 1)
    axis : int, optional
        Axis over which the integral is taken. (Default: 0).

        .. versionadded:: 1.7.0

    Returns
    -------
    S : ndarray
        Laguerre series coefficients of the integral.

    Raises
    ------
    ValueError
        If ``m < 0``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
        ``np.ndim(scl) != 0``.

    See Also
    --------
    lagder

    Notes
    -----
    Note that the result of each integration is *multiplied* by `scl`.
    Why is this important to note?  Say one is making a linear change of
    variable :math:`u = ax + b` in an integral relative to `x`.  Then
    :math:`dx = du/a`, so one will need to set `scl` equal to
    :math:`1/a` - perhaps not what one would have first thought.

    Also note that, in general, the result of integrating a C-series needs
    to be "reprojected" onto the C-series basis set.  Thus, typically,
    the result of this function is "unintuitive," albeit correct; see
    Examples section below.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagint
    >>> lagint([1,2,3])
    array([ 1.,  1.,  1., -3.])
    >>> lagint([1,2,3], m=2)
    """
    """
    Calculate Laguerre integration coefficients for a given set of parameters.

    Parameters:
    c : array_like
        Coefficients to integrate.
    k : int or list of int, optional
        Integration constants. Default is 0.
    m : int, optional
        Order of integration. Default is 1.
    lbnd : scalar, optional
        Lower bound of integration. Default is 0.
    scl : scalar, optional
        Scaling factor. Default is 1.
    axis : int, optional
        Integration axis. Default is 0.

    Returns:
    array
        Integrated coefficients.

    Raises:
    ValueError
        If input parameters are invalid or out of bounds.

    """

    # Ensure `c` is at least 1-dimensional and cast to double if necessary
    c = np.array(c, ndmin=1, copy=True)
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)

    # Ensure `k` is iterable
    if not np.iterable(k):
        k = [k]

    # Ensure `m` is a non-negative integer
    cnt = pu._as_int(m, "the order of integration")

    # Ensure `axis` is a valid axis index
    iaxis = pu._as_int(axis, "the axis")
    iaxis = normalize_axis_index(iaxis, c.ndim)

    # Validate order of integration `cnt`
    if cnt < 0:
        raise ValueError("The order of integration must be non-negative")

    # Validate number of integration constants `k`
    if len(k) > cnt:
        raise ValueError("Too many integration constants")

    # Ensure `lbnd` and `scl` are scalars
    if np.ndim(lbnd) != 0:
        raise ValueError("lbnd must be a scalar.")
    if np.ndim(scl) != 0:
        raise ValueError("scl must be a scalar.")

    # Perform Laguerre integration
    if cnt == 0:
        return c

    # Move integration axis to the front
    c = np.moveaxis(c, iaxis, 0)

    # Pad `k` with zeros if necessary
    k = list(k) + [0] * (cnt - len(k))

    # Iteratively compute Laguerre integration
    for i in range(cnt):
        n = len(c)
        c *= scl
        if n == 1 and np.all(c[0] == 0):
            c[0] += k[i]
        else:
            tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
            tmp[0] = c[0]
            tmp[1] = -c[0]
            for j in range(1, n):
                tmp[j] += c[j]
                tmp[j + 1] = -c[j]
            tmp[0] += k[i] - lagval(lbnd, tmp)
            c = tmp

    # Move integration axis back to its original position
    c = np.moveaxis(c, 0, iaxis)

    return c
def lagval(x, c, tensor=True):
    """
    Evaluate a Laguerre series at points x.

    If `c` is of length ``n + 1``, this function returns the value:

    .. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)

    The parameter `x` is converted to an array only if it is a tuple or a
    list, otherwise it is treated as a scalar. In either case, either `x`
    or its elements must support multiplication and addition both with
    themselves and with the elements of `c`.

    If `c` is a 1-D array, then ``p(x)`` will have the same shape as `x`.  If
    `c` is multidimensional, then the shape of the result depends on the
    value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
    x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
    scalars have shape (,).

    Trailing zeros in the coefficients will be used in the evaluation, so
    they should be avoided if efficiency is a concern.

    Parameters
    ----------
    x : array_like, compatible object
        If `x` is a list or tuple, it is converted to an ndarray, otherwise
        it is left unchanged and treated as a scalar. In either case, `x`
        or its elements must support addition and multiplication with
        themselves and with the elements of `c`.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree n are contained in c[n]. If `c` is multidimensional the
        remaining indices enumerate multiple polynomials. In the two
        dimensional case the coefficients may be thought of as stored in
        the columns of `c`.
    tensor : boolean, optional
        If True, the shape of the coefficient array is extended with ones
        on the right, one for each dimension of `x`. Scalars have dimension 0
        for this action. The result is that every column of coefficients in
        `c` is evaluated for every element of `x`. If False, `x` is broadcast
        over the columns of `c` for the evaluation.  This keyword is useful
        when `c` is multidimensional. The default value is True.

        .. versionadded:: 1.7.0

    Returns
    -------
    values : ndarray, algebra_like
        The shape of the return value is described above.

    See Also
    --------
    lagval2d, laggrid2d, lagval3d, laggrid3d

    Notes
    -----
    The evaluation uses Clenshaw recursion, aka synthetic division.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagval
    >>> coef = [1, 2, 3]
    >>> lagval(1, coef)
    -0.5
    >>> lagval([[1, 2],[3, 4]], coef)
    array([[-0.5, -4. ],
           [-4.5, -2. ]])

    """
    # 将输入的系数转换为至少为一维的 numpy 数组
    c = np.array(c, ndmin=1, copy=None)
    # 如果系数数组的数据类型为布尔类型,将其转换为双精度浮点型
    if c.dtype.char in '?bBhHiIlLqQpP':
        c = c.astype(np.double)
    # 如果 x 是元组或列表,则转换为 numpy 数组
    if isinstance(x, (tuple, list)):
        x = np.asarray(x)
    # 如果 x 是 numpy 数组且 tensor 为 True,则将系数数组 c 扩展为 x 的维度
    if isinstance(x, np.ndarray) and tensor:
        c = c.reshape(c.shape + (1,)*x.ndim)

    # 如果系数数组 c 的长度为 1,设置 c0 为 c[0],c1 为 0
    if len(c) == 1:
        c0 = c[0]
        c1 = 0
    # 如果列表 c 的长度为 2,执行以下操作
    elif len(c) == 2:
        # 将 c[0] 赋值给 c0
        c0 = c[0]
        # 将 c[1] 赋值给 c1
        c1 = c[1]
    # 如果列表 c 的长度不为 2,执行以下操作
    else:
        # 获取列表 c 的长度,并将其赋值给 nd
        nd = len(c)
        # 将倒数第二个元素 c[-2] 赋值给 c0
        c0 = c[-2]
        # 将最后一个元素 c[-1] 赋值给 c1
        c1 = c[-1]
        # 对于 i 从 3 到 len(c) + 1 的范围进行循环
        for i in range(3, len(c) + 1):
            # 将 c0 的值暂存到 tmp 中
            tmp = c0
            # 更新 nd 的值,减去 1
            nd = nd - 1
            # 根据公式计算新的 c0 值
            c0 = c[-i] - (c1*(nd - 1))/nd
            # 根据公式计算新的 c1 值
            c1 = tmp + (c1*((2*nd - 1) - x))/nd
    # 返回计算结果 c0 + c1*(1 - x)
    return c0 + c1*(1 - x)
# 定义一个函数,用于在二维空间中评估拉盖尔级数在点 (x, y) 处的值
def lagval2d(x, y, c):
    # 调用 pu 模块中的 _valnd 函数来计算二维拉盖尔级数的值,并返回结果
    return pu._valnd(lagval, c, x, y)


# 定义一个函数,用于在笛卡尔积 x 和 y 上评估二维拉盖尔级数的值
def laggrid2d(x, y, c):
    # 返回值是二维拉盖尔级数在所有点 (a, b) 上的求和结果,其中 a 取自 x,b 取自 y
    """
    Evaluate a 2-D Laguerre series on the Cartesian product of x and y.

    This function returns the values:

    .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * L_i(a) * L_j(b)

    where the points ``(a, b)`` consist of all pairs formed by taking
    `a` from `x` and `b` from `y`. The resulting points form a grid with
    `x` in the first dimension and `y` in the second.

    The parameters `x` and `y` are converted to arrays only if they are
    tuples or a lists, otherwise they are treated as scalars. In either
    case, either `x` and `y` or their elements must support multiplication
    and addition both with themselves and with the elements of `c`.

    If `c` has fewer than two dimensions, ones are implicitly appended to
    its shape to make it 2-D. The shape of the result will be c.shape[2:] +
    x.shape + y.shape.

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points ``(x, y)``,
        where `x` and `y` must have the same shape. If `x` or `y` is a list
        or tuple, it is first converted to an ndarray, otherwise it is left
        unchanged and if it isn't an ndarray it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficient of the term
        of multi-degree i,j is contained in ``c[i,j]``. If `c` has
        dimension greater than two the remaining indices enumerate multiple
        sets of coefficients.

    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points formed with
        pairs of corresponding values from `x` and `y`.

    See Also
    --------
    lagval, laggrid2d, lagval3d, laggrid3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagval2d
    >>> c = [[1, 2],[3, 4]]
    >>> lagval2d(1, 1, c)
    1.0
    """
    x, y : array_like, compatible objects
        两个一维序列或兼容对象,表示在其笛卡尔乘积中求解二维系列的值。如果 `x` 或 `y` 是列表或元组,则首先转换为 ndarray 数组;否则,保持不变,若不是 ndarray,则视为标量。

    c : array_like
        系数数组,按照多重度 i,j 的顺序排列,其中多重度 i,j 的系数包含在 `c[i,j]` 中。如果 `c` 的维度大于两,剩余的索引用于枚举多组系数。

    Returns
    -------
    values : ndarray, compatible object
        在 `x` 和 `y` 的笛卡尔乘积中,二维切比雪夫级数在各点的值。

    See Also
    --------
    lagval, lagval2d, lagval3d, laggrid3d
        相关函数以及更高维度的 Laguerre 多项式计算函数。

    Notes
    -----

    .. versionadded:: 1.7.0
        引入版本说明:此函数在 NumPy 1.7.0 版本中首次引入。

    Examples
    --------
    >>> from numpy.polynomial.laguerre import laggrid2d
    >>> c = [[1, 2], [3, 4]]
    >>> laggrid2d([0, 1], [0, 1], c)
    array([[10.,  4.],
           [ 3.,  1.]])
        示例说明:使用 laggrid2d 函数计算给定系数数组 `c` 的二维 Laguerre 多项式在指定点网格上的值。
    
    """
    return pu._gridnd(lagval, c, x, y)
# 定义一个函数,用于在给定点(x, y, z)处评估三维拉盖尔级数
def lagval3d(x, y, z, c):
    # 返回由私有函数 _valnd 处理的结果,传入拉盖尔函数 lagval 和参数 x, y, z, c
    return pu._valnd(lagval, c, x, y, z)


# 定义一个函数,用于在 x, y, z 的笛卡尔乘积上评估三维拉盖尔级数
def laggrid3d(x, y, z, c):
    """
    Evaluate a 3-D Laguerre series on the Cartesian product of x, y, and z.

    This function returns the values:

    .. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * L_i(a) * L_j(b) * L_k(c)

    where the points ``(a, b, c)`` consist of all triples formed by taking
    `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
    a grid with `x` in the first dimension, `y` in the second, and `z` in
    the third.

    The parameters `x`, `y`, and `z` are converted to arrays only if they
    are tuples or a lists, otherwise they are treated as scalars. In
    either case, either `x`, `y`, and `z` or their elements must support
    multiplication and addition both with themselves and with the elements
    of `c`.

    If `c` has fewer than three dimensions, ones are implicitly appended to
    its shape to make it 3-D. The shape of the result will be c.shape[3:] +
    x.shape + y.shape + z.shape.

    Parameters
    ----------
    x, y, z : array_like, compatible object
        Points at which the three-dimensional series is evaluated, forming a grid
        with `x` in the first dimension, `y` in the second, and `z` in the third.
        If `x`, `y`, or `z` is a list or tuple, it is first converted to an ndarray,
        otherwise it is treated as a scalar.
    c : array_like
        Array of coefficients where `c[i,j,k]` contains the coefficient of the term
        of multi-degree `i,j,k`. If `c` has more than 3 dimensions, the additional
        dimensions enumerate multiple sets of coefficients.

    Returns
    -------
    values : ndarray, compatible object
        The values of the multidimensional polynomial evaluated at the Cartesian
        product of `x`, `y`, and `z`.

    See Also
    --------
    lagval, lagval2d, laggrid2d, lagval3d

    Notes
    -----
    This function was added in version 1.7.0 of the library.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import laggrid3d
    >>> c = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
    >>> laggrid3d(1, 1, 2, c)
    array([[[[ -1.,  -2.],
             [ -3.,  -4.]],
            [[ -5.,  -6.],
             [ -7.,  -8.]]]])
    """
    x, y, z : array_like, compatible objects
        The three dimensional series is evaluated at the points in the
        Cartesian product of `x`, `y`, and `z`.  If `x`, `y`, or `z` is a
        list or tuple, it is first converted to an ndarray, otherwise it is
        left unchanged and, if it isn't an ndarray, it is treated as a
        scalar.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree i,j are contained in ``c[i,j]``. If `c` has dimension
        greater than two the remaining indices enumerate multiple sets of
        coefficients.

    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points in the Cartesian
        product of `x` and `y`.

    See Also
    --------
    lagval, lagval2d, laggrid2d, lagval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.laguerre import laggrid3d
    >>> c = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
    >>> laggrid3d([0, 1], [0, 1], [2, 4], c)
    array([[[ -4., -44.],
            [ -2., -18.]],
           [[ -2., -14.],
            [ -1.,  -5.]]])
    
    """
    # 调用 _gridnd 函数,计算三维拉盖尔多项式的值
    return pu._gridnd(lagval, c, x, y, z)
def lagvander(x, deg):
    """Pseudo-Vandermonde matrix of given degree.

    Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
    `x`. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., i] = L_i(x)

    where ``0 <= i <= deg``. The leading indices of `V` index the elements of
    `x` and the last index is the degree of the Laguerre polynomial.

    If `c` is a 1-D array of coefficients of length ``n + 1`` and `V` is the
    array ``V = lagvander(x, n)``, then ``np.dot(V, c)`` and
    ``lagval(x, c)`` are the same up to roundoff. This equivalence is
    useful both for least squares fitting and for the evaluation of a large
    number of Laguerre series of the same degree and sample points.

    Parameters
    ----------
    x : array_like
        Array of points. The dtype is converted to float64 or complex128
        depending on whether any of the elements are complex. If `x` is
        scalar it is converted to a 1-D array.
    deg : int
        Degree of the resulting matrix.

    Returns
    -------
    vander : ndarray
        The pseudo-Vandermonde matrix. The shape of the returned matrix is
        ``x.shape + (deg + 1,)``, where The last index is the degree of the
        corresponding Laguerre polynomial.  The dtype will be the same as
        the converted `x`.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagvander
    >>> x = np.array([0, 1, 2])
    >>> lagvander(x, 3)
    array([[ 1.        ,  1.        ,  1.        ,  1.        ],
           [ 1.        ,  0.        , -0.5       , -0.66666667],
           [ 1.        , -1.        , -1.        , -0.33333333]])

    """
    # Ensure deg is converted to an integer
    ideg = pu._as_int(deg, "deg")
    # Check if the degree is non-negative
    if ideg < 0:
        raise ValueError("deg must be non-negative")

    # Convert `x` to a numpy array, ensuring it's at least 1-D
    x = np.array(x, copy=None, ndmin=1) + 0.0
    # Define dimensions of the result matrix `v`
    dims = (ideg + 1,) + x.shape
    # Determine the dtype for `v` based on `x`
    dtyp = x.dtype
    # Create an uninitialized array `v` with specified dimensions and dtype
    v = np.empty(dims, dtype=dtyp)
    # Initialize the first row of `v` as 1's
    v[0] = x * 0 + 1
    # If degree is greater than 0, compute subsequent rows of `v`
    if ideg > 0:
        v[1] = 1 - x
        for i in range(2, ideg + 1):
            v[i] = (v[i-1] * (2*i - 1 - x) - v[i-2] * (i - 1)) / i
    # Move the first axis of `v` to the last axis
    return np.moveaxis(v, 0, -1)


def lagvander2d(x, y, deg):
    """Pseudo-Vandermonde matrix of given degrees.

    Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
    points ``(x, y)``. The pseudo-Vandermonde matrix is defined by

    .. math:: V[..., (deg[1] + 1)*i + j] = L_i(x) * L_j(y),

    where ``0 <= i <= deg[0]`` and ``0 <= j <= deg[1]``. The leading indices of
    `V` index the points ``(x, y)`` and the last index encodes the degrees of
    the Laguerre polynomials.

    If ``V = lagvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
    correspond to the elements of a 2-D coefficient array `c` of shape
    (xdeg + 1, ydeg + 1) in the order

    .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...

    and ``np.dot(V, c.flat)`` and ``lagval2d(x, y, c)`` will be the same
    up to roundoff. This equivalence is useful both for least squares

    """
    # Function definition and docstring are complete as they are.
    fitting and for the evaluation of a large number of 2-D Laguerre
    series of the same degrees and sample points.

    Parameters
    ----------
    x, y : array_like
        Arrays of point coordinates, all of the same shape. The dtypes
        will be converted to either float64 or complex128 depending on
        whether any of the elements are complex. Scalars are converted to
        1-D arrays.
    deg : list of ints
        List of maximum degrees of the form [x_deg, y_deg].

    Returns
    -------
    vander2d : ndarray
        The shape of the returned matrix is ``x.shape + (order,)``, where
        :math:`order = (deg[0]+1)*(deg[1]+1)`.  The dtype will be the same
        as the converted `x` and `y`.

    See Also
    --------
    lagvander, lagvander3d, lagval2d, lagval3d

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagvander2d
    >>> x = np.array([0])
    >>> y = np.array([2])
    >>> lagvander2d(x, y, [2, 1])
    array([[ 1., -1.,  1., -1.,  1., -1.]])
    
"""
return pu._vander_nd_flat((lagvander, lagvander), (x, y), deg)
def lagfit(x, y, deg, rcond=None, full=False, w=None):
    """
    Least squares fit of Laguerre series to data.

    Return the coefficients of a Laguerre series of degree `deg` that is the
    least squares fit to the data values `y` given at points `x`. If `y` is
    1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
    fits are done, one for each column of `y`, and the resulting
    coefficients are stored in the corresponding columns of a 2-D return.
    The fitted polynomial(s) are in the form

    .. math::  p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x),

    where ``n`` is `deg`.

    Parameters
    ----------
    x : array_like
        Array of independent variable values.
    y : array_like
        Array of dependent variable values. If `y` is 2-D, each column represents
        a separate set of data.
    deg : int
        Degree(s) of the Laguerre series to fit.
    rcond : float, optional
        Cut-off ratio for small singular values of the coefficient matrix.
    full : bool, optional
        If True, return additional information.
    w : array_like, optional
        Weights to apply to the residuals.

    Returns
    -------
    coef : ndarray
        Coefficients of the Laguerre series, or array of coefficients if `y` is 2-D.
    residues, rank, singular_values, rcond : ndarray, int, ndarray, float
        Returned only if `full` is True; details of the fit.

    See Also
    --------
    lagvander, lagvander3d, lagfit, lagval2d, lagval3d

    Notes
    -----
    The least squares fit minimizes the sum of the squares of the residuals,
    weighted by the optional parameter `w`.

    Examples
    --------
    >>> import numpy as np
    >>> from numpy.polynomial.laguerre import lagfit
    >>> x = np.array([1, 2, 3])
    >>> y = np.array([2, 3, 4])
    >>> lagfit(x, y, 2)
    array([ 2.,  1.,  0.])
    """
    return pu._fit(legvander, x, y, deg, rcond, full, w)
    x : array_like, shape (M,)
        # M个样本点的x坐标 ``(x[i], y[i])`` 的x坐标
    y : array_like, shape (M,) or (M, K)
        # 样本点的y坐标。可以同时拟合多个共享相同x坐标的数据集,通过传入包含每列数据集的二维数组。
    deg : int or 1-D array_like
        # 拟合多项式的阶数。如果`deg`是一个整数,则包括直到第`deg`项的所有项。对于NumPy版本 >= 1.11.0,可以使用指定要包括的项的阶数的整数列表。
    rcond : float, optional
        # 拟合条件数的相对值。相对于最大奇异值,小于此值的奇异值将被忽略。默认值是len(x)*eps,其中eps是浮点类型的相对精度,在大多数情况下约为2e-16。
    full : bool, optional
        # 返回值的性质开关。当为False时(默认值),仅返回系数;当为True时,还返回奇异值分解的诊断信息。
    w : array_like, shape (`M`,), optional
        # 权重。如果不为None,则权重``w[i]``应用于``x[i]``处未平方的残差``y[i] - y_hat[i]``。理想情况下,选择权重使得所有产品``w[i]*y[i]``的误差具有相同的方差。使用逆方差加权时,使用``w[i] = 1/sigma(y[i])``。默认值为None。

    Returns
    -------
    coef : ndarray, shape (M,) or (M, K)
        # 从低到高排序的Laguerre系数。如果`y`是2-D,则数据列*k*的系数在列*k*中。

    [residuals, rank, singular_values, rcond] : list
        # 仅在``full == True``时返回这些值

        - residuals -- 最小二乘拟合的残差平方和
        - rank -- 缩放Vandermonde矩阵的数值秩
        - singular_values -- 缩放Vandermonde矩阵的奇异值
        - rcond -- `rcond`的值。

        更多细节,请参见`numpy.linalg.lstsq`。

    Warns
    -----
    RankWarning
        # 最小二乘拟合中系数矩阵的秩不足。仅当``full == False``时才会引发警告。可以通过以下方式关闭警告

        >>> import warnings
        >>> warnings.simplefilter('ignore', np.exceptions.RankWarning)

    See Also
    --------
    numpy.polynomial.polynomial.polyfit
    numpy.polynomial.legendre.legfit
    numpy.polynomial.chebyshev.chebfit
    numpy.polynomial.hermite.hermfit
    numpy.polynomial.hermite_e.hermefit
    lagval : 评估Laguerre级数。
    lagvander : Laguerre级数的伪Vandermonde矩阵。
    lagweight : Laguerre权重函数。
    # 使用 Laguerre 系列进行曲线拟合,计算最小二乘拟合系数
    numpy.linalg.lstsq : Computes a least-squares fit from the matrix.
    scipy.interpolate.UnivariateSpline : Computes spline fits.

    Notes
    -----
    The solution is the coefficients of the Laguerre series ``p`` that
    minimizes the sum of the weighted squared errors

    .. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,

    where the :math:`w_j` are the weights. This problem is solved by
    setting up as the (typically) overdetermined matrix equation

    .. math:: V(x) * c = w * y,

    where ``V`` is the weighted pseudo Vandermonde matrix of `x`, ``c`` are the
    coefficients to be solved for, `w` are the weights, and `y` are the
    observed values.  This equation is then solved using the singular value
    decomposition of ``V``.

    If some of the singular values of `V` are so small that they are
    neglected, then a `~exceptions.RankWarning` will be issued. This means that
    the coefficient values may be poorly determined. Using a lower order fit
    will usually get rid of the warning.  The `rcond` parameter can also be
    set to a value smaller than its default, but the resulting fit may be
    spurious and have large contributions from roundoff error.

    Fits using Laguerre series are probably most useful when the data can
    be approximated by ``sqrt(w(x)) * p(x)``, where ``w(x)`` is the Laguerre
    weight. In that case the weight ``sqrt(w(x[i]))`` should be used
    together with data values ``y[i]/sqrt(w(x[i]))``. The weight function is
    available as `lagweight`.

    References
    ----------
    .. [1] Wikipedia, "Curve fitting",
           https://en.wikipedia.org/wiki/Curve_fitting

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagfit, lagval
    >>> x = np.linspace(0, 10)
    >>> rng = np.random.default_rng()
    >>> err = rng.normal(scale=1./10, size=len(x))
    >>> y = lagval(x, [1, 2, 3]) + err
    >>> lagfit(x, y, 2)
    array([1.00578369, 1.99417356, 2.99827656]) # may vary

    """
    # 使用 lagvander 函数调用 _fit 函数,进行 Laguerre 系列拟合
    return pu._fit(lagvander, x, y, deg, rcond, full, w)
# 返回 Laguerre 多项式 c 的伴随矩阵。

# 当 c 是 Laguerre 多项式的基础时,通常的伴随矩阵已经是对称的,因此不需要进行缩放。

# Parameters 参数
# ----------
# c : array_like
#     按从低到高次序排列的 Laguerre 系数的一维数组。

# Returns 返回
# -------
# mat : ndarray
#     维度为 (deg, deg) 的伴随矩阵。

# Notes 注意
# -----
# 这个函数在版本 1.7.0 中被添加。

def lagcompanion(c):
    # c 是 c 的一个修剪副本
    [c] = pu.as_series([c])
    # 如果 c 的长度小于 2,则抛出值错误
    if len(c) < 2:
        raise ValueError('Series must have maximum degree of at least 1.')
    # 如果 c 的长度为 2,则返回一个数组
    if len(c) == 2:
        return np.array([[1 + c[0]/c[1]]])

    # n 是 c 长度减去 1
    n = len(c) - 1
    # 创建一个 dtype 为 c.dtype 的 n x n 的零矩阵
    mat = np.zeros((n, n), dtype=c.dtype)
    # 将矩阵展开后按列设置元素的引用
    top = mat.reshape(-1)[1::n+1]
    mid = mat.reshape(-1)[0::n+1]
    bot = mat.reshape(-1)[n::n+1]
    # 设置 top 为 -1 到 -n 的数组
    top[...] = -np.arange(1, n)
    # 设置 mid 为 2 到 2n+1 的数组
    mid[...] = 2.*np.arange(n) + 1.
    # 设置 bot 为 top 的引用
    bot[...] = top
    # 最后一列加上 (c[:-1]/c[-1])*n
    mat[:, -1] += (c[:-1]/c[-1])*n
    # 返回矩阵
    return mat


# 计算 Laguerre 级数的根。

# 返回多项式 p(x) = sum_i c[i] * L_i(x) 的根(也称为“零点”)。

# Parameters 参数
# ----------
# c : 1-D array_like
#     系数的一维数组。

# Returns 返回
# -------
# out : ndarray
#     级数的根数组。如果所有的根都是实数,则 out 也是实数,否则是复数。

# See Also 参见
# --------
# numpy.polynomial.polynomial.polyroots
# numpy.polynomial.legendre.legroots
# numpy.polynomial.chebyshev.chebroots
# numpy.polynomial.hermite.hermroots
# numpy.polynomial.hermite_e.hermeroots

# Notes 注意
# -----
# 根的估计是通过伴随矩阵的特征值获得的。远离复平面原点的根可能由于这些值的数值不稳定性而具有较大误差。
# 具有大于 1 的重复度的根也会显示较大的误差,因为在这些点附近,系列的值对根的误差相对不敏感。
# 靠近原点的孤立根可以通过牛顿法的几次迭代来改进。

# Laguerre 级数基础多项式不是 x 的幂,因此这个函数的结果可能看起来不直观。

def lagroots(c):
    # c 是 c 的一个修剪副本
    [c] = pu.as_series([c])
    # 如果 c 的长度小于等于 1,则返回一个空数组
    if len(c) <= 1:
        return np.array([], dtype=c.dtype)
    # 如果 c 的长度为 2,则返回一个数组
    if len(c) == 2:
        return np.array([1 + c[0]/c[1]])
    # 创建一个旋转后的伴随矩阵以减小误差
    m = lagcompanion(c)[::-1,::-1]  # 使用lagcompanion函数生成伴随矩阵,并进行行列逆序操作
    r = la.eigvals(m)  # 计算矩阵m的特征值
    r.sort()  # 对特征值进行排序
    return r  # 返回排序后的特征值数组
# 定义 Gauss-Laguerre 积分函数
def laggauss(deg):
    """
    Gauss-Laguerre quadrature.

    Computes the sample points and weights for Gauss-Laguerre quadrature.
    These sample points and weights will correctly integrate polynomials of
    degree :math:`2*deg - 1` or less over the interval :math:`[0, \\inf]`
    with the weight function :math:`f(x) = \\exp(-x)`.

    Parameters
    ----------
    deg : int
        Number of sample points and weights. It must be >= 1.

    Returns
    -------
    x : ndarray
        1-D ndarray containing the sample points.
    y : ndarray
        1-D ndarray containing the weights.

    Notes
    -----

    .. versionadded:: 1.7.0

    The results have only been tested up to degree 100; higher degrees may
    be problematic. The weights are determined by using the fact that

    .. math:: w_k = c / (L'_n(x_k) * L_{n-1}(x_k))

    where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
    is the k'th root of :math:`L_n`, and then scaling the results to get
    the right value when integrating 1.

    Examples
    --------
    >>> from numpy.polynomial.laguerre import laggauss
    >>> laggauss(2)
    (array([0.58578644, 3.41421356]), array([0.85355339, 0.14644661]))

    """
    # 将 deg 转换为整数,如果无法转换,将引发异常
    ideg = pu._as_int(deg, "deg")
    if ideg <= 0:
        raise ValueError("deg must be a positive integer")

    # 创建伴随矩阵,并通过其特征值计算样本点
    c = np.array([0]*deg + [1])
    m = lagcompanion(c)
    x = la.eigvalsh(m)

    # 通过牛顿法进一步优化样本点的精度
    dy = lagval(x, c)
    df = lagval(x, lagder(c))
    x -= dy / df

    # 计算权重,并进行缩放以避免可能的数值溢出
    fm = lagval(x, c[1:])
    fm /= np.abs(fm).max()
    df /= np.abs(df).max()
    w = 1 / (fm * df)

    # 缩放权重以确保积分 1 的准确性
    w /= w.sum()

    return x, w


# 定义 Laguerre 多项式的权重函数
def lagweight(x):
    """Weight function of the Laguerre polynomials.

    The weight function is :math:`exp(-x)` and the interval of integration
    is :math:`[0, \\inf]`. The Laguerre polynomials are orthogonal, but not
    normalized, with respect to this weight function.

    Parameters
    ----------
    x : array_like
       Values at which the weight function will be computed.

    Returns
    -------
    w : ndarray
       The weight function at `x`.

    Notes
    -----

    .. versionadded:: 1.7.0

    Examples
    --------
    >>> from numpy.polynomial.laguerre import lagweight
    >>> x = np.array([0, 1, 2])
    >>> lagweight(x)
    array([1.        , 0.36787944, 0.13533528])

    """
    # 计算 Laguerre 多项式的权重,权重函数为 exp(-x)
    w = np.exp(-x)
    return w

#
# Laguerre series class
#

class Laguerre(ABCPolyBase):
    """A Laguerre series class.

    The Laguerre class provides the standard Python numerical methods
    '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
    attributes and methods listed below.

    Parameters
    ----------
    # Laguerre多项式的系数,按照递增次数排序,例如 (1, 2, 3) 给出的是 1*L_0(x) + 2*L_1(X) + 3*L_2(x)
    coef : array_like
    # (可选参数)要使用的区间。将区间 [domain[0], domain[1]] 通过移位和缩放映射到区间 [window[0], window[1]]。
    # 默认值为 [0, 1]。
    domain : (2,) array_like, optional
    # (可选参数)窗口,参见“domain”来使用它。默认值为 [0, 1]。
    # .. versionadded:: 1.6.0
    window : (2,) array_like, optional
    # (可选参数)用于表示多项式表达式中自变量的符号,例如用于打印。
    # 符号必须是有效的Python标识符。默认值为 'x'。
    # .. versionadded:: 1.24
    symbol : str, optional

    # 虚拟函数
    _add = staticmethod(lagadd)
    _sub = staticmethod(lagsub)
    _mul = staticmethod(lagmul)
    _div = staticmethod(lagdiv)
    _pow = staticmethod(lagpow)
    _val = staticmethod(lagval)
    _int = staticmethod(lagint)
    _der = staticmethod(lagder)
    _fit = staticmethod(lagfit)
    _line = staticmethod(lagline)
    _roots = staticmethod(lagroots)
    _fromroots = staticmethod(lagfromroots)

    # 虚拟属性
    domain = np.array(lagdomain)
    window = np.array(lagdomain)
    basis_name = 'L'

.\numpy\numpy\polynomial\laguerre.pyi

# 引入类型提示模块中的Any类型
from typing import Any

# 引入numpy库中的int_类型和NDArray类型
from numpy import int_
from numpy.typing import NDArray

# 引入numpy.polynomial._polybase模块中的ABCPolyBase类
from numpy.polynomial._polybase import ABCPolyBase

# 引入numpy.polynomial.polyutils模块中的trimcoef函数,赋值给lagtrim变量
from numpy.polynomial.polyutils import trimcoef

# __all__列表,用于定义模块中公开的所有符号
__all__: list[str]

# 将trimcoef函数赋值给lagtrim变量
lagtrim = trimcoef

# 定义函数poly2lag,未完整定义,暂时省略

# 定义函数lag2poly,未完整定义,暂时省略

# lagdomain、lagzero、lagone、lagx,均为定义为NDArray[int_]类型的变量

# 定义函数lagline,未完整定义,暂时省略

# 定义函数lagfromroots,未完整定义,暂时省略

# 定义函数lagadd,未完整定义,暂时省略

# 定义函数lagsub,未完整定义,暂时省略

# 定义函数lagmulx,未完整定义,暂时省略

# 定义函数lagmul,未完整定义,暂时省略

# 定义函数lagdiv,未完整定义,暂时省略

# 定义函数lagpow,未完整定义,暂时省略

# 定义函数lagder,未完整定义,暂时省略

# 定义函数lagint,未完整定义,暂时省略

# 定义函数lagval,未完整定义,暂时省略

# 定义函数lagval2d,未完整定义,暂时省略

# 定义函数laggrid2d,未完整定义,暂时省略

# 定义函数lagval3d,未完整定义,暂时省略

# 定义函数laggrid3d,未完整定义,暂时省略

# 定义函数lagvander,未完整定义,暂时省略

# 定义函数lagvander2d,未完整定义,暂时省略

# 定义函数lagvander3d,未完整定义,暂时省略

# 定义函数lagfit,未完整定义,暂时省略

# 定义函数lagcompanion,未完整定义,暂时省略

# 定义函数lagroots,未完整定义,暂时省略

# 定义函数laggauss,未完整定义,暂时省略

# 定义函数lagweight,未完整定义,暂时省略

# Laguerre类,继承自ABCPolyBase类,定义了domain、window、basis_name属性
class Laguerre(ABCPolyBase):
    domain: Any
    window: Any
    basis_name: Any