NumPy vectorization with integration

后端 未结 3 608
后悔当初
后悔当初 2020-12-06 12:40

I have a vector \"enter and wish to make another vector of the same length whose k-th componen

3条回答
  •  Happy的楠姐
    2020-12-06 13:40

    The function quad executes an adaptive algorithm, which means the computations it performs depend on the specific thing being integrated. This cannot be vectorized in principle.

    In your case, a for loop of length 10 is a non-issue. If the program takes long, it's because integration takes long, not because you have a for loop.

    When you absolutely need to vectorize integration (not in the example above), use a non-adaptive method, with the understanding that precision may suffer. These can be directly applied to a 2D NumPy array obtained by evaluating all of your functions on some regularly spaced 1D array (a linspace). You'll have to choose the linspace yourself since the methods aren't adaptive.

    • numpy.trapz is the simplest and least precise
    • scipy.integrate.simps is equally easy to use and more precise (Simpson's rule requires an odd number of samples, but the method works around having an even number, too).
    • scipy.integrate.romb is in principle of higher accuracy than Simpson (for smooth data) but it requires the number of samples to be 2**n+1 for some integer n.

提交回复
热议问题