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.
BigDecimal is what you want. It has methods like add(), multiply() pow() etc that return new BigDecimal objects.
First of all, the width of a double isn't directly related to the number of decimal places it can hold. A double value is a mantissa and an exponent (among other things), and, of course, is base 2 internally, so it's more complex than "a double can hold X decimal places".
In any case you should be able to use a
BigDecimal
for all of your calculations, just perform all of your math using the methods ofBigDecimal
instead of built-in arithmetic operators.Usage of BigDecimal is good way to solve this issue. No other standard type couldn't handle this precision for you. Other way is to implement your own data structure. But i bet, that BigDecimal will be much much better.
Take a look on Javadoc for BigDecimal (http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html) The main difference between using standard types and this BigDecimal type, that you couldn't use operators like +, -, etc., but you need to use methods like add(),divide(), etc.