Skip to content

Instantly share code, notes, and snippets.

@bushyn
Created December 4, 2012 22:51
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 bushyn/4209830 to your computer and use it in GitHub Desktop.
Save bushyn/4209830 to your computer and use it in GitHub Desktop.
import math
F = lambda x: 1/((1+math.sin(2*x))**2)
def rectangle_method(a, b, E, c):
n = 2
JN1 = 0
while 1:
h = (b - a)/n
x = a + c*h
S = 0
for i in range(n):
S = S+F(x)
x = x+h
JN = S*h
if abs(JN-JN1)<=E:
return n, JN
else:
n=2*n
JN1 = JN
def trapezoidal_rule(a, b, E, c):
n = 2
JN1 = 0
while 1:
h = (b - a)/n
x = a
S = F(a) + F(b)
for i in range(1,n):
x = x+h
S = S+2*F(x)
JN = S*h/2
if abs(JN-JN1)<=E:
return n, JN
else:
n=2*n
JN1 = JN
def simpsons_rule(a, b, n):
h = (b - a) / n
S = F(a)
for i in range(1, n, 2):
x = a + h * i
S += 4 * F(x)
for i in range(2, n-1, 2):
x = a + h * i
S += 2 * F(x)
S += F(b)
z = h * S / 3
return z
print(rectangle_method(0, 2, 0.0001, 0))
print(trapezoidal_rule(0, 2, 0.0001, 0))
print(simpsons_rule(0, 2, 1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment