First time posting, please excuse me if I'm not as concise as I need to be. So I'm trying to do the algorithm for Monte Carlo integration and I've got the code below. However when I run it with the parameters specified in main
I get 0
as output. I'm pretty sure it has something to do with the way Python handles floats but I don't know where else to look. Any help is always appreciated. I know I will kick myself when I see my mistake.
One more thing, I'm using Python 2.7.
montecarloint.py
from random import uniform
from math import exp
def estimate_area(f, a, b, m, n=1000):
hits = 0
total = m * (b-a)
for i in range(n):
x = uniform(a, b)
y = uniform(0, m)
if y <= f(x):
hits += 1
frac = hits / n
return (frac * total)
def f(x):
return exp(-x ** 2)
def main():
print (estimate_area(f, 0, 2, 1))
main()