Reputation: 291
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.
Upvotes: 2
Views: 2119
Reputation: 43391
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
).
Upvotes: 3
Reputation: 81694
Yes, BigDecimal
is the way to go. It works quite reliably -- any odd problems were probably pilot error.
Upvotes: 1