我对Python非常陌生,当我使用quad时,我试图在没有问题的情况下进行连续积分,但是当我切换到fixed_quad时却陷入了困境,如下面的测试示例所示:
def test(z,r):
return r*z**2 + 5
def inttest(r):
return fixed_quad(test, 10*r, 100, args=(r,))[0]
def test2(r, t):
return inttest(r)*(2*t+3)
def inttest2(t):
return fixed_quad(test2, 3, 5, args = (t,), n=5)[0]
print inttest2(3) 我得到以下错误:
Traceback (most recent call last):
File "C:\Python27\tt11.py", line 132, in <module>
print inttest2(3)
File "C:\Python27\tt11.py", line 129, in inttest2
return fixed_quad(test2, 3, 5, args = (t,), n=5)[0]
File "C:\Python27\lib\site-packages\scipy\integrate\quadrature.py", line 58, in fixed_quad
return (b-a)/2.0*sum(w*func(y,*args),0), None
File "C:\Python27\tt11.py", line 124, in test2
return inttest(r)*(2*t+3)
File "C:\Python27\tt11.py", line 119, in inttest
return fixed_quad(test, 10*r, 100, args=(r,))[0]
File "C:\Python27\lib\site-packages\scipy\integrate\quadrature.py", line 54, in fixed_quad
if ainf or binf:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()我做错了什么?任何帮助都是非常感谢的。
发布于 2014-08-16 21:02:49
总之,您的代码无法工作,因为test2不能接受np.array作为输入。
fixed_quad中的相关代码非常简短:
def fixed_quad(func,a,b,args=(),n=5):
[x,w] = p_roots(n)
x = real(x)
ainf, binf = map(isinf,(a,b))
if ainf or binf:
raise ValueError("Gaussian quadrature is only available for "
"finite limits.")
y = (b-a)*(x+1)/2.0 + a
return (b-a)/2.0*sum(w*func(y,*args),0), None而docstring表示:
Parameters
----------
func : callable
A Python function or method to integrate (must accept vector inputs).y将成为尺寸为(n, )的np.array。因此,如果您的test2不能接受np.array作为输入,func(y,*args)将产生错误。
出于这些原因,如果我们提供n=1,它将工作(但当然是无用的):
def inttest2(t):
return si.fixed_quad(test2, 3, 5, args = (t,), n=1)[0]
print inttest2(3)
#22469400.0解决方案是允许test2将np.array作为r的导入。
def test2(r, t):
return np.array(map(inttest, np.array(r)))*(2*t+3)
def inttest2(t):
return fixed_quad(test2, 3, 5, args = (t,), n=5)[0]
print inttest2(3)
#22276200.0https://stackoverflow.com/questions/25341369
复制相似问题