Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCalculate PI statistically
KeywordsPI, random, statistics
CategoriesAlgorithms
 
This program selects random points in the rectangle (0,0) - (1,1). A circle with radius 0.5 centered in that rectangle has area Pi * (0.5)^2 so the number of points that lie within that circle should be approximately:

    [points in circle] = [total points] * [area circle] / [area rectangle]
                       = [total points] * [Pi * (0.5)^2] / [1]
                       = [total points] * [Pi / 4]

Solving for Pi:

    Pi = 4 * [points in circle] / [total points]

The program makes the calculation a little easier by noting that a point (X, Y) is in the circle if:

    Sqr(X^2 + Y^2) < R^2

where R is the radius of the circle. Replacing R with 1 and squaring both sides gives:

    X^2 + Y^2 < 1

 
Private Sub Command1_Click()
Const TOTAL_POINTS = 1000000
Dim x As Single
Dim y As Single
Dim points_in_circle As Single
Dim i As Long

    Randomize
    For i = 1 To TOTAL_POINTS
        x = Rnd
        y = Rnd
        If x * x + y * y < 1 Then
            points_in_circle = points_in_circle + 1
        End If
    Next i

    MsgBox "Pi = " & 4 * points_in_circle / TOTAL_POINTS
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated