Advertisement
Ridwanul_Haque

Numerical Integration

Aug 13th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. from matplotlib import pyplot as plt
  2.  
  3. plt.figure(figsize=(10,10))
  4. file = open("input.txt","r")
  5.  
  6. n = file.readline().rstrip()
  7. n = int(n)
  8. X=[]
  9. Y=[]
  10. X_1=[]
  11.  
  12. for line in file:
  13.     line  = line.rstrip().split()
  14.     X.append(float(line[0]))
  15.     Y.append(float(line[1]))
  16.  
  17. a=0
  18. b=0
  19. c=0
  20. def Trapezoid(a,b):
  21.     return 0.5*(X[b]-X[a])*(Y[a]+Y[b])  
  22.  
  23. def Simpson13(a,b,c):
  24.     return (X[c]-X[a])*(Y[a]+4*Y[b]+Y[c])/6.0
  25.  
  26. def Simpson38(a,b,c,d):
  27.     return (X[d]-X[a])*(Y[a]+3*Y[b]+3*Y[c]+Y[d])/8.0
  28.  
  29. summ = 0
  30. idx = 0
  31. while idx<n-1:
  32.     if((idx+3<=n-1) and abs((X[idx+3]-X[idx+2])-(X[idx+2]-X[idx+1]))<0.00001 and abs((X[idx+2]-X[idx+1])-(X[idx+1]-X[idx]))<0.00001):
  33.         summ +=Simpson38(idx,idx+1,idx+2,idx+3)
  34.         X_1=[]
  35.         Y_1=[]
  36.         X_1.extend([X[idx],X[idx+1],X[idx+2],X[idx+3]])
  37.         Y_1.extend([Y[idx],Y[idx+1],Y[idx+2],Y[idx+3]])
  38.         a = a+1
  39.         idx = idx+3
  40.         plt.plot(X_1,Y_1,color="black")
  41.         plt.fill_between(X_1,Y_1,color="cyan",label="Simpson's 3/8 rule")
  42.  
  43.        
  44.     elif((idx+2<=n-1) and abs((X[idx+2]-X[idx+1])-(X[idx+1]-X[idx]))<0.00001):
  45.         summ +=Simpson13(idx,idx+1,idx+2)
  46.         X_2=[]
  47.         Y_2=[]
  48.         X_2.extend([X[idx],X[idx+1],X[idx+2]])
  49.         Y_2.extend([Y[idx],Y[idx+1],Y[idx+2]])
  50.         b = b+1
  51.         idx = idx+2
  52.         plt.plot(X_2,Y_2,color="black")
  53.         plt.fill_between(X_2,Y_2,color="pink",label="Simpson's 1/3 rule")
  54.     elif(idx+1<=n-1):
  55.         summ +=Trapezoid(idx,idx+1)
  56.         X_3=[]
  57.         Y_3=[]
  58.         X_3.extend([X[idx],X[idx+1]])
  59.         Y_3.extend([Y[idx],Y[idx+1]])
  60.         c = c+1
  61.         idx = idx+1
  62.         plt.plot(X_3,Y_3,color="black")
  63.         plt.fill_between(X_3,Y_3,color="yellow",label="Trapezoid rule")
  64.      
  65. print(X)
  66. print(Y)
  67. print("Trapezoid: ",c," intervals")
  68. print("1/3 rule: ",b*2," intervals")
  69. print("3/8 rule: ",a*3," intervals")
  70. print("Integral Value: ",summ)
  71. plt.xlabel(" x co-ordinates")
  72. plt.ylabel(" f(x)")
  73. plt.legend()
  74. plt.grid("true")
  75. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement