Skip to content

Instantly share code, notes, and snippets.

@cablehead
Created August 20, 2021 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cablehead/a5b5d5649dbce7815a9b7cb5a5dc613f to your computer and use it in GitHub Desktop.
Save cablehead/a5b5d5649dbce7815a9b7cb5a5dc613f to your computer and use it in GitHub Desktop.
Enter function to be integrated for f(x): x**2
Enter lower limit / bound of integration: 1
<class 'str'>
<class 'int'>
You entered: 1
Enter upper limit / bound of integration: 3
You entered: 3
Enter number of segments of integration: 20
You entered: 20
Result: 8.66666666666667
def simpsonsRule(f, a, b, n):
"""
simpsonsRule: (int) -> float
Parameters:
n: integer representing the number of segments being used to
approximate the integral
Pre conditions:
Function bounds() declared that returns lower and upper bounds of integral.
Function f(x) declared that returns the evaluated equation at point x.
Parameters passed.
Post conditions:
Returns float equal to the approximate integral of f(x) from a to b
using Simpson's rule.
Description:
Returns the approximation of an integral. Works as of python 3.3.2
REQUIRES NO MODULES to be imported, especially not non standard ones.
-Code by TechnicalFox
"""
sum = float()
sum += f(a) #evaluating first point
sum += f(b) #evaluating last point
width=(b-a)/(2*n) #width of segments
oddSum = float()
evenSum = float()
for i in range(1,n): #evaluating all odd values of n (not first and last)
oddSum += f(2*width*i+a)
sum += oddSum * 2
for i in range(1,n+1): #evaluating all even values of n (not first and last)
evenSum += f(width*(-1+2*i)+a)
sum += evenSum * 4
return sum * width/3
def main():
# read in f
value = input("Enter function to be integrated for f(x): ")
value = "def f(x):\n\treturn " + value
capture = {}
exec (value, globals(), capture)
f = capture['f']
a = input("Enter lower limit / bound of integration: ")
print (type(a))
a = int(a)
print (type(a))
print ("You entered:", a)
while True:
b = input("Enter upper limit / bound of integration: ")
b = int(b)
print ("You entered:", b)
if b > a:
break
print ("Upper bound must be greater than lower bound...")
n = input("Enter number of segments of integration: ")
n = int(n)
print ("You entered:", n)
print ("Result:", simpsonsRule(f, a, b, n))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment