scipy 试着求一个复函数的积分

kuuvgm7e  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(168)

我有一个函数,我试图在其中计算定积分。然而,这个函数的一部分使用了Map函数,我得到了TypeError: only size-1 arrays can be converted to Python scalars
下面是我的函数:

from scipy import integrate
import numpy as np
def func(a, b, c, d): #a is an array of 4000 elements, b is an array of ten elements, c&d are integers
    n = len(a)
    aver = a.mean()
    stdevn = a.std()
    final = []
    def fn(a=a, b=b, c=c, d=d):
        return ((1/n)*sum(map(lambda y: ((1/c) * np.exp(-0.5*((x - y - 0.2*((b-aver)/stdevn)*y)/bandwidth)**2)), a)))

    for i in b:
        total = integrate.quad(fn, a=0, b=100)
        final.append(total)
    return final

结果应该是一个长度为b(10)的数组。我不确定代码中哪里有错误。x在函数中,因为它是积分的一部分
追溯:

---> 10         total = integrate.quad(fn, a=0, b=100)                             
     11 
     12         final.append(total)

/opt/conda/lib/python3.7/site-packages/scipy/integrate/quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
    350     if weight is None:
    351         retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
--> 352                        points)
    353     else:
    354         if points is not None:

/opt/conda/lib/python3.7/site-packages/scipy/integrate/quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
    461     if points is None:
    462         if infbounds == 0:
--> 463             return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
    464         else:
    465             return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)

TypeError: only size-1 arrays can be converted to Python scalars
sdnqo3pr

sdnqo3pr1#

这是一个可行的解决方案:

from scipy import integrate
import numpy as np
def func(a, b, c, d): #a is an array of 4000 elements, b is an array of ten elements, c&d are integers
    n = len(a)
    aver = a.mean()
    stdevn = a.std()
    final = []

    for i in b:
        total = integrate.quad(lambda x: x*(inv*sum(map(lambda y: ((1/b) * np.exp(-0.5*((x-y-0.2*((b-aver)/stdevn*x/bandwidth))), clm))), a, b, epsabs = np.inf
        final.append(total)
    return final
vdgimpew

vdgimpew2#

我想你是错误地使用了scipy.integrate.quad。从手册页上可以看到quad函数需要间隔的开始和结束作为参数。你试图传递两个变量(我猜是作为fn函数的参数?)。尝试类似于total = integrate.quad(fn, min_interval, max_interval, args=(a, b, c, d))。下次请添加一个最小的可重复示例。像这样,它更像是一个猜谜游戏。

相关问题