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()

.

from Blogger http://ift.tt/2phj4LY

via IFTTT

### Like this:

Like Loading...

*Related*