【问题标题】:Create The Legendre Formula Using Numpy使用 Numpy 创建勒让德公式
【发布时间】:2014-05-02 01:27:54
【问题描述】:

所以,我尝试使用 numpy.polynomial.legendre 命令生成 P2 到 Pn 多项式公式。 我想输入 2,它会给我p2 = 1/2 *(-1 +3x**2),或者如果输入是 3,它会给我 P3 公式。

这样我可以给出 x 值来计算每个 Pn 并使用我的一些类方法来计算误差以进一步找到根。

我设法使用以下方法制作情节:

 numpy.polynomial.legendre.legval (x, np.identity(10))

【问题讨论】:

    标签: python numpy matplotlib formula


    【解决方案1】:

    我认为您正在寻找函数scipy.special.legendre

    #Build the polynomial
    >>> import scipy.special as sp
    >>> sp.legendre(2)
    poly1d([ 1.5,  0. , -0.5])
    
    #Compute on an interval from -1 to 1
    >>> sp.legendre(2)(np.linspace(-1,1,10))
    array([ 1.        ,  0.40740741, -0.03703704, -0.33333333, -0.48148148,
           -0.48148148, -0.33333333, -0.03703704,  0.40740741,  1.        ])
    

    【讨论】:

    • 哇,谢谢,我试图进入 scipy.org 以进入文档,但我一直在从那里的任何链接中收到错误。非常感谢,这正是我所需要的。
    【解决方案2】:

    您也可以使用 numpy polynomial 包来执行此操作。

    In [1]: from numpy.polynomial import Polynomial, Legendre
    
    In [2]: for i in range(5):
       ...:     p = Legendre.basis(i).convert(kind=Polynomial)
       ...:     print p.coef
       ...: 
    [ 1.]
    [ 0.  1.]
    [-0.5  0.   1.5]
    [ 0.  -1.5  0.   2.5]
    [ 0.375  0.    -3.75   0.     4.375]
    

    请注意,系数从低到高顺序排列。但是,不需要转换为幂级数来计算这些值,而且不这样做更准确。

    In [3]: Legendre.basis(2)(np.linspace(-1,1,10))
    Out[3]: 
    array([ 1.        ,  0.40740741, -0.03703704, -0.33333333, -0.48148148,
           -0.48148148, -0.33333333, -0.03703704,  0.40740741,  1.        ])
    

    您还可以使用 linspace 方法从 [-1, 1] 绘制结果。

    In [4]: plot(*Legendre.basis(2).linspace())
    Out[4]: [<matplotlib.lines.Line2D at 0x30da4d0>]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多