Created
December 4, 2012 22:51
-
-
Save bushyn/4209830 to your computer and use it in GitHub Desktop.
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
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