user1126849
user1126849

Reputation: 291

Precise Square Roots in Java

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

Answers (3)

yshavit
yshavit

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

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

Yes, BigDecimal is the way to go. It works quite reliably -- any odd problems were probably pilot error.

Upvotes: 1

MahdeTo
MahdeTo

Reputation: 11184

Check something like JScience it has a decimal class where you can set the number of digits and subsequently the required precision.

something like this is what you need.

Upvotes: 1

Related Questions