Code archives/Algorithms/Pi Calculator Rev 2
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
Calculates Pi based on the approximate area of a circle with a given radius multiplied by 1 over that radius squared. This is simply a modification of the equation A=Pi*R^2. So Pi=A*1/R^2. Not as limited by floats as the last one, but it would be less accurate in the long run, plus it is MUCH more time consuming, since the time to run increases exponentially with the radius used. | |||||
r=Input$("Enter a value for the radius (higher is more accurate, 2000 is best): ") total=0 For x=-r To r For y=-r To r If Sqr(x^2+y^2)<r total=total+1 End If Next Next other#=1/Float(r)^2 pivalue#=other#*total Print pivalue# Delay(10000) End |
Comments
| ||
You can square the radius and test with that, instead of using a squareroot. Makes it much faster. Here shows times for both methods: Graphics3D 800,600,32,2 r=Input$("Enter a value for the radius (higher is more accurate, 2000 is best): ") total=0 time=MilliSecs() For x=-r To r For y=-r To r If Sqr(x*x+y*y)<r total=total+1 End If Next Next time2=MilliSecs()-time other#=1/Float(r)^2 pivalue#=other#*total Print pivalue# Print "Slow method : "+time2 total=0 time=MilliSecs() rr=r*r For x=-r To r For y=-r To r If x*x+y*y<rr total=total+1 End If Next Next time2=MilliSecs()-time other#=1/Float(r)^2 pivalue#=other#*total Print pivalue# Print "Fast method : "+time2 MouseWait End |
| ||
uh, You know you can just put: Print "Pi = "+Pi+" |
| ||
blitz monkey, some times you want to know how the value Pi gets to be calculated for your own purpose (learnin, understanding), I think this example code serves this purpose. Please don't insult the man. |
| ||
Here's my incomprehensible contribution, in BlitzMax so we can use double precision.' One of those whiz-bang modern algorithms for Pi. Framework BRL.StandardIO Import BRL.Retro Print ; Print Print "Eleven iterations give full double precision accuracy." Print "Twelfth time through the mill adds nothing." Print ; Print s! = 0 ; m! = 1 ; d1! = 1 ; d2! = 4 ; d3! = 5 ; d4! = 6 For n = 1 To 12 s :+ m * ( 4 / d1 - 2 / d2 - 1 / d3 - 1 / d4 ) m :/ 16 ; d1 :+ 8 ; d2 :+ 8 ; d3 :+ 8 ; d4 :+ 8 Print RSet(n,4) + " " + s Next ' Check that we got it right. Print Print " Pi = " + Pi |
Code Archives Forum