Anupznk

integration

Jun 19th, 2021
569
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import math
  2. from tabulate import tabulate as tb
  3.  
  4.  
  5. def func(x):
  6.     return 2000 * math.log((140000 / (140000 - 2100 * x)), math.e) - 9.8 * x
  7.  
  8.  
  9. def trapezoidIntegration(lowerLim, upperLim, n):
  10.     h = (upperLim - lowerLim) / n
  11.     middleTerm = 0
  12.     for i in range(1, n):
  13.         middleTerm += 2 * func(lowerLim + i * h)
  14.     result = h * (func(lowerLim) + middleTerm + func(upperLim)) / 2
  15.     return result
  16.  
  17.  
  18. def showTable_Trapezoidal(lowerLim, upperLim, n1, n2):
  19.     table = [[]]
  20.     prevValue = trapezoidIntegration(lowerLim, upperLim, n1)
  21.     table.append([n1, prevValue, '---------------'])
  22.  
  23.     for i in range(n1 + 1, n2 + 1):
  24.         currValue = trapezoidIntegration(lowerLim, upperLim, i)
  25.         error = abs((currValue - prevValue) / currValue * 100.0)
  26.         prevValue = currValue
  27.         table.append([i, currValue, error])
  28.  
  29.     print(tb(table, headers=['n', 'Approximate Value', '|error| %'], tablefmt='orgtbl'))
  30.  
  31.  
  32. def simpsonSingle(lowerLim, upperLim):
  33.     h = (upperLim - lowerLim) / 2
  34.     return h / 3 * (func(lowerLim) + 4 * func((lowerLim + upperLim) / 2) + func(upperLim))
  35.  
  36.  
  37. def simpsonMultiple(lowerLim, upperLim, n):
  38.     h = (upperLim - lowerLim) / (n)
  39.     result = 0
  40.     low = lowerLim
  41.     for i in range(n):
  42.         result += simpsonSingle(low, low + h)
  43.         low = low + h
  44.     return result
  45.  
  46.  
  47. def showTable_Simpson(lowerLim, upperLim, n1, n2):
  48.     table = [[]]
  49.     prevValue = simpsonMultiple(lowerLim, upperLim, n1)
  50.     table.append([n1, prevValue, '---------------'])
  51.  
  52.     for i in range(n1 + 1, n2 + 1):
  53.         currValue = simpsonMultiple(lowerLim, upperLim, i)
  54.         error = abs((currValue - prevValue) / currValue * 100.0)
  55.         prevValue = currValue
  56.         table.append([i, currValue, error])
  57.  
  58.     print(tb(table, headers=['n', 'Approximate Value', '|error| %'], tablefmt='orgtbl'))
  59.  
  60.  
  61. n = int(input('Enter the number of sub-intervals (For Trapezoidal Rule):'))
  62. result = trapezoidIntegration(8, 30, n)
  63. print('Result from Trapezoidal Rule:', result)
  64. showTable_Trapezoidal(8, 30, 1, 5)
  65.  
  66. n = int(input('Enter the number of sub-intervals (Simpson\'s Rule):'))
  67. result = simpsonMultiple(8, 30, n)
  68. print('Result from Simpson\'s Rule:', result)
  69. showTable_Simpson(8, 30, 1, 5)
  70.  
  71. # result of the integration = 11061.335568081007
  72.  
RAW Paste Data