Nugroho's blog.: Numeric Integration using Python and Pylab

Friday, April 14, 2017

Numeric Integration using Python and Pylab

Pylab is Python module that contain NumPy and MatPlotlib.

Let f(x) = x^2 and we want to integrate it from 0 to 1.

Numerically we could use square method or trapezoidal (which is almost better).




Let use square method first.

and count "inner square" using this code

from pylab import *

def f(x):
    return x*x

def integrate(x):
    sum = 0
    for i in arange(len(x)-1):
        sum += f(x[i])*dx
    return sum

x   = linspace(0,1,100)
dx  = x[1]-x[0]
y   = f(x)
print integrate(x)
plot(x,y)
grid(True)
show()


The result is 0.32829983335.

The  "outer square "  code below give the result 0.338400843451

from pylab import *

def f(x):
    return x*x

def integrate(x):
    sum = 0
    for i in arange(len(x)-1):
        sum += f(x[i+1])*dx
    return sum

x   = linspace(0,1,100)
dx  = x[1]-x[0]
y   = f(x)
print integrate(x)
plot(x,y)
grid(True)
show()

How about Trapezoidal method? Easy, just modify little bit, and give the result 0.333350338401,  which is much better,  :)

from pylab import *

def f(x):
    return x*x

def integrate(x):
    sum = 0
    for i in arange(len(x)-1):
        sum += (f(x[i])+f(x[i+1]))*dx/2.
    return sum

x   = linspace(0,1,100)
dx  = x[1]-x[0]
y   = f(x)
print integrate(x)
plot(x,y)
grid(True)
show()
.

No comments:

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)