0

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()
  • 2
    In Python <3, we have 1/2 = 0, but 1/2.0 = 0.5. You have to convert `hits` or `n` to float first in the division – Jasper Feb 17 '15 at 22:58
  • possible duplicate of [how can I force division to be floating point in Python?](http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python) – Jasper Feb 17 '15 at 22:58
  • Or use `from __future__ import division` - https://www.python.org/dev/peps/pep-0238/ – Peter DeGlopper Feb 17 '15 at 22:58
  • @Jasper Yeah! Thanks for your fast answer. Casting to `float` like this `frac = float(hits) / n` did the trick. – Carlos Brito Feb 17 '15 at 23:02

0 Answers0