Simpsons 3 by 8
#Numerical integration by Simpson's 3/8 rule
from math import *
def f(x):
return 1/(1+x)
a,b,n =eval(input('Input lower limit (a), upper limit (b) & no. of steps(multiple of 3)(n): '))
h = (b - a)/float(n)
x = [a+h*i for i in range(n+1)]
y=[f(x[i]) for i in range(n+1)]
intgrl=y[0] + y[-1]
for i in range(1,n):
if i%3==0:
intgrl+=2*y[i]
else:
intgrl+=3*y[i]
intgrl=(3*h/8)*intgrl
print('Integral using Simpson\'s 3/8 rule = ',intgrl)
Output Screen:
Input lower limit (a), upper limit (b) & no. of steps(multiple of 3)(n): 0,1,3
Integral using Simpson's 3/8 rule = 0.6937500000000001
Another Code
#Numerical integration by Simpsons 3/8 rule
from math import *
def f(x):
return sin(x)
a=0
b=pi/2
n=int(input ("enter number of intervals,n "))
h=(b-a)/n
integral=f(a)+f(b)
for i in range(1,n):
x=a+i*h
if (i%3==0):
integral=integral+2*f(x)
else:
integral=integral+3*f(x)
integral=(3*h/8)*integral
print (integral)
Comments
Post a Comment