Montecarlo: Integrate x from 0 to 1
#this example integrates x from 0 to 1
#approximation of an integral by average
sum=0
def f(x):
return x
from random import *
n=int(input('How many random numbers ?'))
for i in range(1,n+1):
x=random()
sum=sum+f(x)
print('Value of integral =',1/n*sum)
Output Screen:
How many random numbers ?10000
Value of integral = 0.4997902939934223
Comments
Post a Comment