[SciPy-User] calculate definite integral of sampled data

Gustavo Goretkin gustavo.goretkin@gmail....
Wed Aug 10 01:46:19 CDT 2011

You could try using the numpy.cumsum (standing for cumulative sum) function
to accomplish this. This would give you the equivalent of a Riemann sum (the
sum is approximated with rectangles, specifically I think this would be
considered the midpoint Riemann sum).

You should be able the accomplish the trapezoidal rule by first averaging
consecutive samples and then applying the Riemann sum. Here's an example

In [2]: sample_points = np.linspace(0,10,1000)

In [3]: y = np.cos(sample_points)

In [4]: y_midpoint = np.cumsum(y)

In [5]: y_smooth = ( y[0:-1] + y[1:] ) * (.5)

In [6]: y_trapezoidal = np.cumsum(y_smooth)

Note that after trapezoidal integration, the array length is one fewer.

In my opinion, the more elegant way to do the smoothing step is with the
numpy.convolution operator. In this same way, you should be able to
implement other equally-spaced quadrature rules like Simpson's rule, but I
may be incorrect.


On Wed, Aug 10, 2011 at 1:59 AM, Manuel Graune <contact@graune.org> wrote:

> Hi everyone,
> to calculate the definite integral of a function or an array of sampled
> data scipy provides (among others) the quad and trapz functions.
> So it is possible to compute e. g. the definite integral of cos(t) over
> some interval by doing
> definite_integral= scipy.integrate.quad(cos,lower_limit,upper_limit)
> or
> definite_integral= scipy.integrate.trapz(some_array).
> Now, if I want to plot cos(t) and  the integral of cos(t) from 0 to t in
> a graph, the necessary array can be calculated by:
> @numpy.vectorize
> def intfunc(fnc,upper_limit):
>    return scipy.integrate.quad(fnc,0.0,upper_limit)
>    definite_inegral= intfunc(cos,t)
> which seems (whithout knowing the actual code) a bit wasteful and slow
> but is relatively concise.
> Now for my question: scipy provides e. g. the trapz-function to
> calculate definite integral of a complete array of sampled data.
> However, I have no idea how to get achieve the same as above for
> sampled data (apart from manually iterating in a for-loop). Is there
> a function somewhere which delivers an array of the definite integrals
> for each of the data-points in an array?
> Regards,
> Manuel
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20110810/7abc075a/attachment.html 

More information about the SciPy-User mailing list