Area of the Shadow? – The Monte Carlo Solution in VBScript


If you want to solve the following puzzle then it may be not so easy/intuitive at a glance. It is a square and 20 is the area with e.g. unit = square meters (which really does not matter)

shadow-area Area of the Shadow? - The Monte Carlo Solution in VBScript algorithms math monte carlo Monte Carlo Simulation Monte Carlo Simulation Algorithm vbscript

shadow-area

The computer is very good at this if you want to get a very close approximation, you can use the Monte-Carlo algorithm. The principle of Monte-Carlo is to generate as many random samples (in this case points) as possible (however definitely) then count the number of points that fall inside the shadow region. The ratio multiples the area of the rectangle equals the area of the shadow region. The following VBScript demonstrates this algorithm.

monte-carlo-vbscript Area of the Shadow? - The Monte Carlo Solution in VBScript algorithms math monte carlo Monte Carlo Simulation Monte Carlo Simulation Algorithm vbscript

monte-carlo-vbscript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
' HelloACM.com
Const N = 1000000
C = 0
 
Randomize
For i = 1 To N
    x = Rnd
    y = Rnd
    r = Sqr(x * x + y * y)
    If (r >= 1) Then ' Outside the 1/4 Circle 
        r = Sqr((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5))
        If (r <= 0.5) Then ' Distance to Center smaller than Radius = 0.5
             C = C + 1
        End If
    End If
Next
 
Msgbox C / N * 20
' HelloACM.com
Const N = 1000000
C = 0

Randomize
For i = 1 To N
    x = Rnd
    y = Rnd
    r = Sqr(x * x + y * y)
    If (r >= 1) Then ' Outside the 1/4 Circle 
        r = Sqr((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5))
        If (r <= 0.5) Then ' Distance to Center smaller than Radius = 0.5
             C = C + 1
        End If
    End If
Next

Msgbox C / N * 20

We assume the each side of rectangle is 1 so the radius of the circle is 0.5. We first exclude the points that fall inside the 1/4 circle and then we count the points that only fall inside the full circle by using distance to center (less than 0.5). The ratio can be obtained by dividing the number to total samples.

Obviously, the more samples we have, more accurate this result is. I leave this to you guys as a C++ coding exercise.

Pure Math Solution (by Josué Molina)

math-solution Area of the Shadow? - The Monte Carlo Solution in VBScript algorithms math monte carlo Monte Carlo Simulation Monte Carlo Simulation Algorithm vbscript

math-solution

Monte Carlo Simulation Algorithms to compute the Pi based on Randomness:

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
777 words
Last Post: Manage WordPress Connections, Settings in One Place for Multiple WordPress Sites on Same Domain
Next Post: Google Talk supports (y)

The Permanent URL is: Area of the Shadow? – The Monte Carlo Solution in VBScript

Leave a Reply