Jump to content

Calculate Pi


ddxfish
 Share

Recommended Posts

I had to make an efficiency comparison of ways to calculate Pi for a class (based on # of iterations). One is statistical and the other is algebraic. I figured I would post them here.

 

Monte Carlo Method of calculating Pi (statistical)

;Monte Carlo method to calculate Pi

$incircle = 0
$count = InputBox("Monte Carlo", "Please enter how many samples to calculate")

For $i = 0 To $count
    $hypo = pythagoran(((Random(0, 1) * 2) - 1), ((Random(0, 1) * 2) - 1))
    If $hypo <= 1 Then $incircle += 1
Next
MsgBox(0, "Pi Equals", "Pi: " & ((4 * $incircle) / $count) & @CRLF & "Samples: " & $count)

Func pythagoran($a, $b)
    Return Sqrt(($a ^ 2) + ($b ^ 2))
EndFunc   ;==>pythagoran

Nilakantha Method of calculating Pi (algebraic)

;Nilakantha method to calc pi

$pi = 3
$count = InputBox("Nilakantha", "Enter number of iterations")

For $i = 1 to $count
    $denom = (2 * $i) + 2
    if mod($i, 2) = 1 Then
        $pi += (4 / (($denom)*($denom - 1)*($denom -2)))
    elseif mod($i, 2) = 0 Then
        $pi -= (4 / (($denom)*($denom - 1)*($denom -2)))
    EndIf
Next
MsgBox(0, 0, $pi)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...