Java 中的精确平方根
在 Java 中存储平方根等无理数的最佳方法是什么?我需要很大的精度(超过 100 位),所以 float 和 double 不太好。是大十进制吗?我以前使用过它,但遇到了奇怪的问题,但这可能只是我的代码。我的代码非常复杂,因此我想在返工其他内容之前确保 BigDecimal 是正确的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果所有数字都来自同一运算(例如,所有平方根),您可以存储它们的源(例如平方)而不是计算结果。如果数字来自几次计算,您可以创建封装这些的类:SquareRoot、CubedRoot 等。
例如,√2 将是 new SquareRoot( 2),其字段将是一个
long
或double
(2) 并且可能也是一个transient
缓存结果(作为BigDecimal)。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 anlong
ordouble
(2) and probably also atransient
cached result (as aBigDecimal
).检查类似 JScience 的东西,它有一个小数类,您可以在其中设置位数以及随后所需的精度。
像 this 这样的东西就是你所需要的。
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.
是的,
BigDecimal
是正确的选择。它的工作相当可靠——任何奇怪的问题都可能是飞行员的失误。Yes,
BigDecimal
is the way to go. It works quite reliably -- any odd problems were probably pilot error.