Saturday, March 14, 2015

Want to calculate pi on your own pc for Pi Day?

(this involves a certain basic computer proficiency on your part, but not a bit of programming)

I've thrown together a crude little VBScript you should be able to run from any Windows pc that will generate an approximation of pi.  

It uses the Leibnitz series, which is fairly inefficient, meaning it takes a lot of loops to approach accuracy.  It is, however, about the easiest to throw into a little script.

This is the calculation that the script is performing to generate pi:








And this is what it arrives at after 200,000,000 cycles - and how long it took on my laptop, about 2 and a half minutes. Pi accurate to 7 decimal places.  That many cycles means that the smallest fraction it applied in that series was 1/199,999,999, by the way.  















Just copy everything between, but not including, the "********" below and paste it into a file named calc_pi.vbs (or whateveryouwannacallit.vbs).

Save that file to your computer and run it.  You'll get a pop up asking you how big you want the denominator in that first graphic to get.  The default is 200,000, but in the example above, I used 200,000,000.

Then, depending on how big you make that number, you'll get a pop up with the second graphic in a few seconds or minutes.

Show it to your friends!  Watch as they ... well, probably roll their eyes at you!



********

'Quick approximation of pi using the Leibnitz series

intSeriesLim = InputBox ("What limit do you want to use?", _
"Leibnitz Series", "200000")  

num1QPi = 1
numPi = 0
numPlusMinus = -1
intCount = 1
startTime = Now()

for i = 3 to intSeriesLim step 2
numVal = numPlusMinus^intCount
numIncrement = numVal/i
num1QPi = num1QPi + numIncrement
intCount = intCount + 1
next

numPi = 4*num1QPi

endTime = Now()
MsgBox "Started: " & startTime & " and Ended: " _
& endTime & vbCrlf & vbCrlf _
& "With a series limit of " & intSeriesLim _
& ", pi is approx " & numPi

********

No comments:

Post a Comment