import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Find the following integral as simply as you can.
$$I = \int_0^{\pi/2}\cos(x)dx$$again:
$$I \approx \sum_{i=0}^{N_{rec}-1}f(x_i)\Delta x$$Nrec = 100
x = np.linspace(0,np.pi/2, Nrec+1)
Δx = x[1]-x[0]
fx = np.cos(x)
#--------- way 1
I = np.sum(fx[:-1])*Δx
print(I)
#--------- way 2
I = 0.0
for i in range(Nrec): # 0 <= i <= Nrec-1
I = I + Δx*fx[i]
print(I)
1.007833419873582 1.007833419873582
integrate
that takes the following arguments:f
to integrate,a
, b
def integrate(f, a, b, Nrec):
x = np.linspace(0,np.pi/2, Nrec+1)
Δx = x[1]-x[0]
I = np.sum(f(x[:-1]))*Δx
return I
#---------------------
def f(x):
return np.cos(x)
#---------------------
I = integrate(f, 0, np.pi/2, 100)
print(f"I = {I:.6f}")
I = 1.007833
integrate_trap
that takes the following arguments:f
to integrate,a
, b
def integrate_trap(f, a, b, Ntrap):
x = np.linspace(0,np.pi/2, Ntrap+1)
Δx = x[1]-x[0]
I = Δx*np.sum(f(x[:])) - Δx/2*(f(x[0])+f(x[-1]))
return I
#---------------------
def f(x):
return np.cos(x)
#---------------------
I = integrate_trap(f, 0, np.pi/2, 100)
print(f"I = {I:.6f}")
I = 0.999979