Calculating Pi

Started by TomToad, August 12, 2018, 12:41:27

Previous topic - Next topic

TomToad

If you ever have the need to calculate Pi, here are a few ways to do it.  The code below is for BlitzMax, but should translate to any other language easily.
'Print Pi according to BlitzMax constant.
Print "Pi:~t~t~t"+Pi

'Gregory-Leibniz method
'infinite sum in the form of Pi = (4/1)-(4/3)+(4/5)-(4/7)+(4/9)-(4/11)+(4/13)-(4/15) ...
'increment the denominator to the next odd integer and alternate adding and subtracting.
'The longer you continue the sequence, the closer you get to Pi
Local PiGrLe:Double
Local d:Int = 1
For Local i:Long = 1 To 500000000 Step 2
PiGrLe :+ (4:Double/i)*d
d = -d
Next
Print "Gregory-Leibniz:~t"+PiGrLe+" difference = "+(Pi-PiGrLe)

Local PiNil:Double = 3:Double
'Nilikantha Method
'Similar to the Gregory-Leibnix method, except the denominator is in the form of n*(n+1)*(n+2)
'start with n at 2 and increase to the next even integer, alternate adding and subtracting, and add 3
'to the result.
'This formula allows Pi to become more accurate much sooner in the sequence, but you need to look out
'for floating point errors as the multilication can result in very large numbers, which reduces
'computer fp precision.
'Pi = 3+(4/(2*3*4))-(4/(4*5*6))+(4/(6*7*8))-(4/(8*9*10))+(4/(10*11*12))-(4/(12*13*14)) ...
d = 1
For Local i:Long = 2 To 5000000 Step 2
PiNil :+ (4:Double/(i*(i+1)*(i+2)))*d
d = -d
Next
Print "Nilakantha:~t~t"+PiNil+" difference = "+(Pi-PiNil)

'Arcsine function.
'Pick a number from -1 to 1.  Use the formula
'Pi = 2*(Arcsin(Sqrt(1-x^2))+Abs(Arcsin(x)))
'Arcsin must return result in radians, which is why I use asin_!() here
'If you use the number 1, the formula is reduced to 2*Arcsin(1)
Local PiArc:Double = 2:Double*asin_!(1)
Print "ArcSin:~t~t"+PiArc+" difference = "+(Pi-PiArc)

'Limit function
'Pick a high number.  The higher the number, the more accurate the result.
'Use this formulat, x*Sin(180/x) 'Sin() must accept values in degrees
'Be aware, too high of a number will result in inaccuracies due to computer
'floating point precision.
Local PiLimit:Double = 500000000:Double*Sin(180.0:Double/500000000:Double)
Print "Limit:~t~t~t"+PiLimit+" difference = "+(Pi-PiLimit)
------------------------------------------------
8 rabbits equals 1 rabbyte.

Xerra

Seriously, you went to that much trouble? If you'd asked I'd have just done it for you...

M2 Pro Mac mini - 16GB 512 SSD
ACER Nitro 5 15.6" Gaming Laptop - Intel® Core™ i7, RTX 3050, 1 TB SSD
Vic 20 - 3.5k 1mhz 6502

Latest game - https://xerra.itch.io/Gridrunner
Blog: http://xerra.co.uk
Itch.IO: https://xerra.itch.io/