I was doing some benchmarks the other day, and one of the tests was a calculation of pi using a particular algorithm. I found that quite interesting and naturally this made me curious if I could do the same calculation in PowerShell. Of course, if all you need is the value of pi, that is easily obtained with the [Math] .NET class.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
PS C:\> [math]::pi 3.14159265358979
But this Friday Fun is as much about the journey as anything. I started with finding an algorithm I could use to calculate pi. I decided to use the Gauss-Legendre algorithm. The general process is to iterate through a series of equations, each pass getting you closer to pi.
Pi is then calculated like this:
From my research, I knew what the starting values should be. For reasons that will become clear in a moment, I explicitly defined my variables as arrays.
$a = @(1) $b = @(1/[math]::Sqrt(2)) $t = @(1/4) $p = @(1)
As you can see, I still need to rely on the [Math] class for things like the square root of 2. Now the fun part. The algorithm loops and each subsequent value of a variable is based on a calculation of the current variable. My solution was to use a For loop and run the equations for each variable I also decided to evaluate for pi each time through the loop so I could see how close I was getting.
for ($n=0;$n -lt 3;$n++) { #each time through the array add a new value to each array using the += operator $a+= ($a[$n]+$b[$n])/2 $b+= [math]::Sqrt(($a[$n]*$b[$n])) $t+= $t[$n] - ($p[$n] * ([math]::Pow(($a[$n] - $a[$n+1]),2))) $p+= 2*$p[$n] ([math]::Pow($a[$n+1] +$b[$n+1],2))/(4 *($t[$n+1])) }
This worked out nicely because $n can serve as the index number for each calculated variable so that I can get the correct ones for the final calculation. The for loop starts with $n=0 and loops while $n is less than or equal to 3. Each time through the loop, $n is incremented by 1 ($n++). You may be wondering why I'm only looping until 3. Well, here's what happens when I run my little script.
PS C:\> Get-Pi.ps1 3.14057925052217 3.14159264621354 3.14159265358979
No matter how many more times I run the loop, I won't get a value any more precise than 3.14159265358979 which just happens to be the same value as [math]::pi. I thought there might be a way to force PowerShell or .NET to run the calculation to more decimal places but that's a bit beyond my .NET pay grade apparently. But I hoped you picked up something about the For construct or arrays. And don't ask me about the math.I can punch in the numbers but I have no idea what it all means. But I had fun and hope you do to.