3

I would like to do numerical integration for a given set of samples.

Let say I have x unevenly spaced regions and y = f(x) is the function I want to integrate.

    x       y=f(x)
   0.1      10.5
   1.2      2.0
   3.7      11.0
   7.0      4.0

Now can I use the Simpon's rule from scipy.integrate this way?

from scipy.integrate import simps

I = simps(y,x)

even though my x values are unevenly spaced?

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
  • I think you just have the `y` and `x` arguments reversed, it should be `simps(y, x)`, otherwise, it should work. Does it not? – tom10 Jul 08 '15 at 14:39
  • @tom10: Sorry, that was a typo! Does it work this way? – Srivatsan Jul 08 '15 at 14:46
  • What Tom said above, the y should come before the x. But with Simpson's Rule, you have to have even amount of intervals for it to work and they have to be evenly spaced. Since it's calculating a integral using parabolas. – Sean Stinehour Jul 08 '15 at 14:46
  • @SeanStinehour: Which method should I use for unevenly spaced intervals? – Srivatsan Jul 08 '15 at 14:46
  • 1
    What you can do is use a variation of the Trapezoidal Rule(I don't know off hand if Python has it), `AT = ½ (y0 + y1)Δx1 + ½ (y1 + y2)Δx2 + ...... + ½ (yn -1 + yn)Δxn`. For example, `½ (10.5 + 2.0)1.1 +...` – Sean Stinehour Jul 08 '15 at 15:00
  • @SeanStinehour: Is there a name for this rule that you have mentioned? – Srivatsan Jul 08 '15 at 15:54
  • If you only have discrete points, you will have to decide how to integrate them. One hopes that you have additional information or insight into what the points represent and how you got them. This could point to the 'best' way to integrate in your particular case. – Jon Custer Jul 08 '15 at 16:36
  • @ThePredator No, there isn't aside from the Trapezoidal Rule. It's just the same formula, moved a bit around so you can account for the uneven intervals. This might [help](http://www.solitaryroad.com/c376.html). It follows #2 of the Trapezoidal rule. – Sean Stinehour Jul 08 '15 at 17:07
  • @SeanStinehour: Thanks! – Srivatsan Jul 08 '15 at 17:58

1 Answers1

2

For numerical integration, the above procedure can be followed once we have the values of both x and the function y=f(x).

One can also use the Trapezoidal rule from numpy like:

result = np.trapz(y,x)
Srivatsan
  • 9,225
  • 13
  • 58
  • 83