Welcome, guest | Sign In | My Account | Store | Cart

Calculating area under the curve using Monte Carlo method for any given function.

Python, 38 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Calculating area under the curve using Monte Carlo method
# FB - 201006137

import math
import random

# define any function here!
def f(x):
    return math.sqrt(1.0 - x * x)

# define any xmin-xmax interval here! (xmin < xmax)
xmin = -1.0
xmax = 1.0

# find ymin-ymax
numSteps = 1000000 # bigger the better but slower!
ymin = f(xmin)
ymax = ymin
for i in range(numSteps):
    x = xmin + (xmax - xmin) * float(i) / numSteps
    y = f(x)
    if y < ymin: ymin = y
    if y > ymax: ymax = y

# Monte Carlo
rectArea = (xmax - xmin) * (ymax - ymin)
numPoints = 1000000 # bigger the better but slower!
ctr = 0
for j in range(numPoints):
    x = xmin + (xmax - xmin) * random.random()
    y = ymin + (ymax - ymin) * random.random()
    if f(x) > 0 and y > 0 and y <= f(x):
        ctr += 1
    if f(x) < 0 and y < 0 and y >= f(x):
        ctr += 1

fnArea = rectArea * float(ctr) / numPoints
print "Area under the curve = " + str(fnArea)

3 comments

FB36 (author) 13 years, 10 months ago  # | flag

In the given example, it would calculate pi/2 because the given function defines a half-circle.

Pietro Berkes 13 years, 10 months ago  # | flag

Given that the code is already evaluating the function at a huge number of points (lines 19--23), conventional numerical integration would be far better. Also, the kind of rejection sampling proposed here is very inefficient, and requires knowing the minimum and maximum of the function.

FB36 (author) 13 years, 10 months ago  # | flag

I certainly did not write this code for any practical purpose. Monte Carlo is probably the most inefficient solution method for almost any problem. I only put it here thinking some people may find it interesting, that's all.