What is the best way to store irrational numbers like square roots in Java? I need a great deal of precision (over 100 digits), so float and double won't be good. Is it BigDecimal? I was using that before but I ran into strange problems, it could just be my code though. My code is very complex so I want to make sure BigDecimal is the right way to go before I rework the other stuff.
Asked
Active
Viewed 2,025 times
2
-
_Is it BigDecimal?_ Yes, it is. – Kohányi Róbert Jan 03 '12 at 05:28
-
1Have you ran any tests with BigDecimal and can you document your issues? I've found BigDecimals to not necessarily be the most efficient but I've never seen it get an incorrect computation. – nmjohn Jan 03 '12 at 05:31
-
http://stackoverflow.com/questions/7676521/storing-large-decimal-numbers-in-java – NinethSense Jan 03 '12 at 05:32
-
java.math.BigDecimal is definetly good. – Abhishek bhutra Jan 03 '12 at 05:33
-
No, it's not "it could be just my code though", it in fact ***is*** just your code. Trust me, the odds of your code having a bug vs BigDecimal code having a bug are 10000 to 1. – Hovercraft Full Of Eels Jan 03 '12 at 05:40
-
Thanks everyone. @HovercraftFullOfEels, well I didn't know that or I wouldn't have asked the question. – user1126849 Jan 03 '12 at 07:11
3 Answers
3
If all of your numbers are coming from the same operation (e.g., all square roots), you could store their source (e.g. the square) instead of the computed result. If the numbers come from a few computations, you could create classes that encapsulate this: SquareRoot
, CubedRoot
, etc.
For instance, √2 would be new SquareRoot(2)
, and its fields would be an long
or double
(2) and probably also a transient
cached result (as a BigDecimal
).

yshavit
- 42,327
- 7
- 87
- 124
-
I needed their actual digits, but I might not have specified this clearly earlier. – user1126849 Jan 03 '12 at 07:34
1
-
The other answers were good as well, but this helped me the most. By the way it's now called FloatingPoint. – user1126849 Jan 03 '12 at 07:34
1
Yes, BigDecimal
is the way to go. It works quite reliably -- any odd problems were probably pilot error.

Ernest Friedman-Hill
- 80,601
- 10
- 150
- 186