Last active
February 10, 2020 19:31
-
-
Save pmelanson/8857131 to your computer and use it in GitHub Desktop.
Simpson's rule applied to sin(x), and also hardcoded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
# Approximates the definite integral of sin(x) using Simpson's rule. | |
from math import pi,sin,cos | |
def simpson_approximation(a, b, n): | |
"Approximates the definite integral of sin(x) from a to b with respect to x with 'n' iterations" | |
dx = (b-a)/n | |
summation = 0 | |
for i in range(1, n): # iterate from 1 to n-1 | |
if i % 2 == 1: # if i is odd | |
summation += 4 * sin(dx * i + a) | |
elif i % 2 == 0: # if i is even | |
summation += 2 * sin(dx * i + a) | |
summation += sin(a) | |
summation += sin(b) | |
approximate_integral = dx * summation / 3 | |
print("With n =",n,"the approximate integral of sin(x) from","%3f"%a,"to","%3f"%b,"with respect to x is", approximate_integral) | |
return approximate_integral | |
a = 0 | |
b = pi | |
n_list = [10, 100, 1000] | |
for n in n_list: | |
approximation = simpson_approximation(a, b, n) | |
print("This is a", "%3.2e" % (approximation/(cos(a) - cos(b)) - 1), "difference from the exact value of", -cos(a) + cos(b)) | |
print("") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment