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]
chebtrim = trimcoef
def poly2cheb(pol): ...
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): ...
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): ...
class Chebyshev(ABCPolyBase):
@classmethod
def interpolate(cls, func, deg, domain=..., args = ...): ...
domain: Any
window: Any
basis_name: Any
.\numpy\numpy\polynomial\hermite.py
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__ = [
'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']
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])
"""
[pol] = pu.as_series([pol])
deg = len(pol) - 1
res = 0
for i in range(deg, -1, -1):
res = hermadd(hermmulx(res), pol[i])
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
if n == 2:
c[1] *= 2
return c
else:
c0 = c[-2]
c1 = c[-1]
for i in range(n - 1, 1, -1):
tmp = c0
c0 = polysub(c[i - 2], c1*(2*(i - 1)))
c1 = polyadd(tmp, polymulx(c1)*2)
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.
"""
hermdomain = np.array([-1., 1.])
hermzero = np.array([0])
hermone = np.array([1])
hermx = np.array([0, 1/2])
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])
else:
return np.array([off])
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.]))
"""
return pu._div(hermmul, c1, c2)
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.])
"""
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")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
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, 0, -1):
der[j - 1] = (2*j)*c[j]
c = der
c = np.moveaxis(c, 0, iaxis)
return c
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)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt = pu._as_int(m, "the order of integration")
iaxis = pu._as_int(axis, "the axis")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
k = list(k) + [0]*(cnt - len(k))
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]*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)
return 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 = np.array(c, ndmin=1, copy=None)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if isinstance(x, (tuple, list)):
x = np.asarray(x)
if isinstance(x, np.ndarray) and tensor:
c = c.reshape(c.shape + (1,)*x.ndim)
x2 = x * 2
if len(c) == 1:
c0 = c[0]
c1 = 0
elif len(c) == 2:
c0 = c[0]
c1 = c[1]
else:
nd = len(c)
c0 = c[-2]
c1 = c[-1]
for i in range(3, len(c) + 1):
tmp = c0
nd = nd - 1
c0 = c[-i] - c1*(2*(nd - 1))
c1 = tmp + c1*x2
return c0 + c1*x2
def hermval2d(x, y, c):
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.])
"""
"""
调用 _gridnd 函数来计算二维埃尔米特多项式在给定点 (x, y) 上的值,使用了 hermval 函数和系数 c
"""
return pu._gridnd(hermval, c, x, y)
def hermval3d(x, y, z, c):
return pu._valnd(hermval, c, x, y, z)
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,)
y : array_like, shape (M,) or (M, K)
deg : int or 1-D array_like
rcond : float, optional
full : bool, optional
w : array_like, shape (`M`,), optional
Returns
-------
coef : ndarray, shape (M,) or (M, K)
[residuals, rank, singular_values, rcond] : list
- residuals -- 最小二乘拟合的残差平方和
- rank -- 缩放的Vandermonde矩阵的数值秩
- singular_values -- 缩放的Vandermonde矩阵的奇异值
- rcond -- `rcond`的值
有关更多详细信息,请参阅`numpy.linalg.lstsq`。
Warns
-----
RankWarning
>>> 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])
"""
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] = pu.as_series([c])
if len(c) <= 1:
return np.array([], dtype=c.dtype)
if len(c) == 2:
return np.array([-.5*c[0]/c[1]])
m = hermcompanion(c)[::-1,::-1]
r = la.eigvals(m)
r.sort()
return r
```py
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 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):
tmp = c0
c0 = -c1*np.sqrt((nd - 1.)/nd)
c1 = tmp + c1*x*np.sqrt(2./nd)
nd = nd - 1.0
return c0 + c1*x*np.sqrt(2)
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")
if ideg <= 0:
raise ValueError("deg must be a positive integer")
c = np.array([0]*deg + [1], dtype=np.float64)
m = hermcompanion(c)
x = la.eigvalsh(m)
dy = _normed_hermite_n(x, ideg)
df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2*ideg)
x -= dy/df
fm = _normed_hermite_n(x, ideg - 1)
fm /= np.abs(fm).max()
w = 1/(fm * fm)
w = (w + w[::-1]) / 2
x = (x - x[::-1]) / 2
w *= np.sqrt(np.pi) / w.sum()
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
"""
_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
from numpy import int_, float64
from numpy.typing import NDArray
from numpy.polynomial._polybase import ABCPolyBase
from numpy.polynomial.polyutils import trimcoef
__all__: list[str]
hermtrim = trimcoef
def poly2herm(pol): ...
def herm2poly(c): ...
hermdomain: NDArray[int_]
hermzero: NDArray[int_]
hermone: NDArray[int_]
hermx: NDArray[float64]
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): ...
class Hermite(ABCPolyBase):
domain: Any
window: Any
basis_name: Any
.\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']
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])
deg = len(pol) - 1
res = 0
for i in range(deg, -1, -1):
res = hermeadd(hermemulx(res), pol[i])
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)
if n == 1:
return c
if n == 2:
return c
else:
c0 = c[-2]
c1 = c[-1]
for i in range(n - 1, 1, -1):
tmp = c0
c0 = polysub(c[i - 2], c1*(i - 1))
c1 = polyadd(tmp, polymulx(c1))
return polyadd(c0, polymulx(c1))
hermedomain = np.array([-1., 1.])
hermezero = np.array([0])
hermeone = np.array([1])
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
"""
if scl != 0:
return np.array([off, scl])
else:
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.
"""
return np.poly(roots)
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.])
"""
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.])
"""
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] = pu.as_series([c])
if len(c) == 1 and c[0] == 0:
return c
prd = np.empty(len(c) + 1, dtype=c.dtype)
prd[0] = c[0]*0
prd[1] = c[0]
for i in range(1, len(c)):
prd[i + 1] = c[i]
prd[i - 1] += c[i]*i
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.])
"""
[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:
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
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 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([ 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])
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
"""
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
rcond : float, optional
full : bool, optional
w : array_like, shape (`M`,), optional
Returns
-------
coef : ndarray, shape (M,) or (M, K)
[residuals, rank, singular_values, rcond] : list
- residuals -- 最小二乘拟合的平方残差和
- rank -- 缩放后的 Vandermonde 矩阵的数值秩
- singular_values -- 缩放后的 Vandermonde 矩阵的奇异值
- rcond -- `rcond` 的值。
更多细节请参阅 `numpy.linalg.lstsq`。
Warns
-----
RankWarning
>>> 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
-----
.. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
return pu._fit(hermevander, x, y, deg, rcond, full, w)
[c] = pu.as_series([c])
if len(c) < 2:
raise ValueError('Series must have maximum degree of at least 1.')
if len(c) == 2:
return np.array([[-c[0]/c[1]]])
m = hermecompanion(c)[::-1,::-1]
r = la.eigvals(m)
r.sort()
return r
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.
"""
if n == 0:
return np.full(x.shape, 1/np.sqrt(np.sqrt(2*np.pi)))
c0 = 0.
c1 = 1./np.sqrt(np.sqrt(2*np.pi))
nd = float(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.
"""
ideg = pu._as_int(deg, "deg")
if ideg <= 0:
raise ValueError("deg must be a positive integer")
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)
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。
"""
w = np.exp(-.5*x**2)
return w
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
"""
_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)
domain = np.array(hermedomain)
window = np.array(hermedomain)
basis_name = 'He'
.\numpy\numpy\polynomial\hermite_e.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]
hermetrim = trimcoef
def poly2herme(pol): ...
def herme2poly(c): ...
hermedomain: NDArray[int_]
hermezero: NDArray[int_]
hermeone: NDArray[int_]
hermex: NDArray[int_]
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): ...
class HermiteE(ABCPolyBase):
domain: Any
window: Any
basis_name: Any
.\numpy\numpy\polynomial\laguerre.py
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__ = [
'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'
]
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])
res = 0
for p in pol[::-1]:
res = lagadd(lagmulx(res), p)
return res
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] = pu.as_series([c])
n = len(c)
if n == 1:
return c
else:
c0 = c[-2]
c1 = c[-1]
for i in range(n - 1, 1, -1):
tmp = c0
c0 = polysub(c[i - 2], (c1*(i - 1))/i)
c1 = polyadd(tmp, polysub((2*i - 1)*c1, polymulx(c1))/i)
return polyadd(c0, polysub(c1, polymulx(c1)))
lagdomain = np.array([0., 1.])
lagzero = np.array([0])
lagone = np.array([1])
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.])
"""
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.])
"""
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] = pu.as_series([c])
if len(c) == 1 and c[0] == 0:
return c
prd = np.empty(len(c) + 1, dtype=c.dtype)
prd[0] = c[0]
prd[1] = -c[0]
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.])
"""
return pu._mulx(c1, c2)
[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:
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
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 lagadd(c0, lagsub(c1, lagmulx(c1)))
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.]))
"""
return pu._div(lagmul, c1, c2)
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.])
"""
return pu._pow(lagmul, c, pow, maxpower)
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``.
"""
return pu._der(lagmul, c, m, scl, axis)
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")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
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)
return c
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.
"""
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt = pu._as_int(m, "the order of integration")
iaxis = pu._as_int(axis, "the axis")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
k = list(k) + [0] * (cnt - len(k))
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
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. ]])
"""
c = np.array(c, ndmin=1, copy=None)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if isinstance(x, (tuple, list)):
x = np.asarray(x)
if isinstance(x, np.ndarray) and tensor:
c = c.reshape(c.shape + (1,)*x.ndim)
if len(c) == 1:
c0 = c[0]
c1 = 0
elif len(c) == 2:
c0 = c[0]
c1 = c[1]
else:
nd = len(c)
c0 = c[-2]
c1 = c[-1]
for i in range(3, len(c) + 1):
tmp = c0
nd = nd - 1
c0 = c[-i] - (c1*(nd - 1))/nd
c1 = tmp + (c1*((2*nd - 1) - x))/nd
return c0 + c1*(1 - x)
def lagval2d(x, y, c):
return pu._valnd(lagval, c, x, y)
def laggrid2d(x, y, c):
"""
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.]]])
"""
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]])
"""
ideg = pu._as_int(deg, "deg")
if ideg < 0:
raise ValueError("deg must be non-negative")
x = np.array(x, copy=None, ndmin=1) + 0.0
dims = (ideg + 1,) + x.shape
dtyp = x.dtype
v = np.empty(dims, dtype=dtyp)
v[0] = x * 0 + 1
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
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
"""
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
"""
return pu._fit(lagvander, x, y, deg, rcond, full, w)
def lagcompanion(c):
[c] = pu.as_series([c])
if len(c) < 2:
raise ValueError('Series must have maximum degree of at least 1.')
if len(c) == 2:
return np.array([[1 + c[0]/c[1]]])
n = len(c) - 1
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[...] = -np.arange(1, n)
mid[...] = 2.*np.arange(n) + 1.
bot[...] = top
mat[:, -1] += (c[:-1]/c[-1])*n
return mat
def lagroots(c):
[c] = pu.as_series([c])
if len(c) <= 1:
return np.array([], dtype=c.dtype)
if len(c) == 2:
return np.array([1 + c[0]/c[1]])
m = lagcompanion(c)[::-1,::-1]
r = la.eigvals(m)
r.sort()
return r
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]))
"""
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)
w /= w.sum()
return x, w
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])
"""
w = np.exp(-x)
return w
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
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]
lagtrim = trimcoef
class Laguerre(ABCPolyBase):
domain: Any
window: Any
basis_name: Any