Skip to content

Instantly share code, notes, and snippets.

@aburousan
Last active June 29, 2020 12:32
Show Gist options
  • Save aburousan/8cd3ebfdb0fec3c2b51b6fa4cb8fc953 to your computer and use it in GitHub Desktop.
Save aburousan/8cd3ebfdb0fec3c2b51b6fa4cb8fc953 to your computer and use it in GitHub Desktop.
This is a program to Integrate using Trapezoidal Rule. Here you can also see the plot of the Trapezoids
import numpy as np
import matplotlib.pyplot as plt
original = np.pi/4
def f(x):
return 1/(1+(x*x))
x_real = np.linspace(0,1,1000)#This and the next line are used to create a plot of the curve represented by our f(x) function.
y_real = f(x_real)
def traezoid(f,n,a=0,b=1):
x = np.linspace(a,b,n+1)#This creates n+1 points(i.e., n lengths) on x axis which are seperated by h
y = f(x); h = (b - a)/n #This gives y values corresponding to the x values (a,a+h,...etc)
y_last = y[1:];y_first = y[:-1] #Using this line we get 2 arrays which contains all y values corresponding to all x values
s = (h/2) * np.sum(y_first + y_last) #But y_last contains all values except f(a) and y_fast contains all values except f(b)
return s, x, y
n = 2
print("______________________________________________")
print("N \t Approx Integration. \t Error")
print("______________________________________________")
for i in range(4):
s,X,Y = traezoid(f,n)
error = original-s
print("{0:6.0f}".format(n),"\t","{0:1.12f}".format(s),"\t ","{0:1.12e}".format(error))
plt.subplot(2,2,i+1)#This creates 4 subplots
plt.plot(x_real,y_real,color='Black',label='n = %s'%n)#This plots the real function
plt.legend(loc='best')
for k in range(n):
xs = [X[k],X[k],X[k+1],X[k+1]]#This and It's next line gives the points to draw Trapezoids
ys = [0,f(X[k]),f(X[k+1]),0]
plt.fill_between(xs,ys)#This one draw the Trapezoids
n = n*2
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment