質問

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.

役に立ちましたか?

解決

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.

他のヒント

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).

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top