用numpy向量化相关的Legendre多项式

2024-03-29 09:16:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想输入一个向量到相关的legendre多项式。

import scipy.special as sp
def f(m,n,x):
    return sp.lpmn(m,n,x)[0][-1,-1]
x=[1,2,3]
print f(1,1,x)

输出是

^{pr2}$

如何将向量输入到相关的legendre多项式中,例如用于拟合和绘图?使用numpy向量化函数不起作用:

np.vectorize(f(1,1,x))

>>>> File "C:\Anaconda\lib\site-packages\scipy\special\basic.py", line 681, in lpmn
raise ValueError("z must be scalar.")

>>>> ValueError: z must be scalar.

Tags: importreturndefasscipybe向量sp
1条回答
网友
1楼 · 发布于 2024-03-29 09:16:03

^{}接受一个函数作为第一个参数,并返回一个新函数来包装原始参数。当这样称呼时:

np.vectorize(f(1,1,x))

它实际上意味着“用参数1、1和x调用函数f,将结果作为第一个参数传递给”np矢量化". 你应该做的是装饰你的功能:

^{pr2}$

测试:

In [4]: f(1, 1, [1, 2, 3])
/usr/lib/python3/dist-packages/numpy/lib/function_base.py:1639: RuntimeWarning: overflow encountered in ? (vectorized)
  outputs = ufunc(*inputs)
Out[4]: array([ 0.        ,  1.73205081,  2.82842712])

像这样使用时,必须小心不要将数组值作为顺序和度数传递给fmn),因为它们也将被矢量化,这可能会失败,或执行意外的事情:

In [6]: f([1, 2], 1, [1, 2, 3])
 ...
ValueError: operands could not be broadcast together with shapes (2,) () (3,) 

通过传递一组位置参数的索引和关键字参数的名称,可以告诉numpy.vectorize不要考虑这些参数:

def f(m, n, x):
    return sp.lpmn(m, n, x)[0][-1, -1]
f = np.vectorize(f, excluded={0, 1}, otypes=[np.float64])

相关问题 更多 >