Friday, 6 March 2015

Numerical integration with Python

figure_19999

In this short article I am going to post a simple Python script for numerical integration.

Numerical integration is a part of a family of algorithms for calculating the numerical value of a definite integral. The two simplest method for performing numerical integration are rectangle and trapezoidal rule. If you’d like to know more about these two methods you can check the wikipedia page which has been pretty helpful to me.

Now, the code below works fine if the functions you are using is not decreasing and positive, however:
-If your function is decreasing, the plot need to be adjusted to show the correct graph
-If the function is negative at some point, the code might not work, since it has not been designed to handle it. Perhaps in the future I’ll fix that.

Therefore, bottom line, square root of x is fine, logarithms (after 1),x^2,x^3(from 0) etc…

Here is an approximation with 50 points and the rectangle rule:

figure_1_50 (2)

and the code output on the console:

Finally, below is the code I used to generate the output above:

Hope this is useful.

2 comments:

  1. You might want to check out quadpy https://github.com/nschloe/quadpy (a project of mine). It does the heavy lifting for all sorts of integration problems.

    ReplyDelete
    Replies
    1. Thanks for the suggestion! I'll check it out!

      Delete