I've written a small program to calculate Pi in Java.
My summations are currently typed double
.
I have two outputs, one which is Pi to 16 decimal places (the raw output).
The second output is rounded using NumberFormat
/DecimalFormat
to 3-5 decimal places.
I've spent a little while googling and browsing Stackoverflow but being a beginner I'm unsure of any keywords
that may be needed to find the correct method I'm looking for, so please excuse my naivety...
Is it possible to calculate an answer (i.e. Pi) to more than 16 decimal places? Say, 32? If so, how can I approach this?
I've looked at BigDecimal
, however I don't think this is what I'm after as all examples I've seen pre-define the number with a large amount of decimal places first, not via a calculation, but I may be wrong.
I understand double
's are a 64-bit type so won't achieve more than 16 decimal places.
I also understand using long
as a type will lose precision...
Any advice or guidance will be appreciated.
Thank you.
Update
Unfortunately, I'm still not getting any more than 16 decimal places using BigDecimals... Am I heading in the right direction?
Update Again
I've just realised I think my problem is with scale
during my division. I changed it to 100 and now I get Pi to 100 decimal places... I think the scale
parameter allows more precision etc. It requires the divide(BigDecimal divisor, int scale, int roundingMode)
method. See Java Doc >> here <<
With 500,000 terms from the Madhava–Leibniz series, I can now calculate Pi to 10,000 decimal places with 6 'correct' significant figures. The rest are still converging (and obviously need 1000's more terms to get a more accurate representation of Pi). But for the purposes of what most of us need Pi for, this is fine.
Thank you all for your help.