开发者

How to integrate a numpy array in scipy?

I have a relatively expensive-to-calculate function which, given a single scalar, returns a numpy.array() object. When I try to integrate this function with respect to the scalar argument, using scipy.integrate.romberg, I get an error internal to scipy from the condition it uses to determine convergence:

Traceback (most recent call last):
  File "wqc.py", line 148, in <module>
    H_cycle = (m.pi / wt) * scipy.integrate.romberg(H_if, 0, m.pi / wt)
  File "/usr/lib/python2.6/site-packages/scipy/integrate/quadrature.py", line 471, in romberg
    while (abs(result - lastresult) > tol) and (i <= divmax):
ValueErro开发者_JAVA技巧r: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Is there any way to integrate the entire array at once, or do I need to integrate element-by-element? I would like to avoid the second solution, as there is no easy way to calculate just one element of the array.


The problem appears to be here:

abs(result - lastresult) > tol

result and lastresult are likely numpy.arrays (instead of single values). The above entire expression is therefore evaluating to an array of truth values, rather than a single True/False. Therefore when you and the result of the above expression with (i <= divmax), you get the error The truth value of an array with more than one element is ambiguous.. The suggestion by the ValueError is appropriate. You should turn the array of truth values into a single truth value.

example = numpy.array([True, True, True, False])
example.any()
>>> True
example.all()
>>> False

This will resolve the problem.


What you're trying to do is ambiguous in purely mathematical sense. The integration routine has no way of knowing whether you want to integrate several scalar functions at the same time (which as far as I understand you're after), or if you're doing something like one of these beasts: http://en.wikipedia.org/wiki/Vector_calculus#Theorems

What I would do to here I would tabulate the expensive function, interpolate it (using scipy.interp1d or UnivariateSpline), and integrate these.


http://www.sagemath.org may provide alternative ways of numerical integration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜