Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating an Answer in Java with more than 16 decimal places

Tags:

java

decimal

pi

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.

like image 613
Reanimation Avatar asked Dec 04 '25 03:12

Reanimation


1 Answers

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.

like image 63
Mysterion Avatar answered Dec 06 '25 15:12

Mysterion