#Program to evaluate integration using monte carlo method:
from math import*
def f(x):
y=(1-x*x)*exp(-x*x)
return y
import random as rn
a=input("Enter the lower limit:")
b=input("Enter the upper limit:")
nt=input("Enter the total no. darts:")
n=input("Enter the no. of divisions:")
a=float(a)
b=float(b)
n=int(n)
nt=int(nt)
dell=(b-a)/(n*1.0)
k=[]
for i in range (n):
j=a+i*dell
u=f(j)
k.append(u)
h1=max(k)*1.2
s=min(k)*1.2
h2=abs(s)
ns=0.0
for i in range(nt):
x=rn.random()
y=rn.random()
x1=a+(b-a)*x
y1=-h2+(h1+h2)*y
y2=f(x1)
if y1<=y2:
ns=ns+1
A=ns/nt*(h1+h2)*(b-a)-h2*(b-a)
print("The value of the integration is:",A)
from math import*
def f(x):
y=(1-x*x)*exp(-x*x)
return y
import random as rn
a=input("Enter the lower limit:")
b=input("Enter the upper limit:")
nt=input("Enter the total no. darts:")
n=input("Enter the no. of divisions:")
a=float(a)
b=float(b)
n=int(n)
nt=int(nt)
dell=(b-a)/(n*1.0)
k=[]
for i in range (n):
j=a+i*dell
u=f(j)
k.append(u)
h1=max(k)*1.2
s=min(k)*1.2
h2=abs(s)
ns=0.0
for i in range(nt):
x=rn.random()
y=rn.random()
x1=a+(b-a)*x
y1=-h2+(h1+h2)*y
y2=f(x1)
if y1<=y2:
ns=ns+1
A=ns/nt*(h1+h2)*(b-a)-h2*(b-a)
print("The value of the integration is:",A)
Comments
Post a Comment