java BigDecimal 上是否有用于平方根的库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1384919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are there libraries for Square Root over BigDecimal?
提问by Daniel C. Sobral
Are there any libraries for Square Root over BigDecimal in Java?
Java 中是否有用于平方根 over BigDecimal 的库?
采纳答案by Redder
JScience v4.3.1has a Realclass which seems to be the equivalent of BigDecimaland that might help you. An example of usage:
JScience v4.3.1有一个Real类,它似乎等效于BigDecimal并且可能对您有所帮助。用法示例:
// The Square Root of Two, to 30 digits
// According to "The Square Root of Two, to 5 million digits."
// Source: http://www.gutenberg.org/files/129/129.txt
System.out.println("1.41421356237309504880168872420");
// Using JScience with 50 digits precision
Real.setExactPrecision(50);
System.out.println(Real.valueOf(2).sqrt());
// Using default java implementation
System.out.println(Math.sqrt(2));
> 1.41421356237309504880168872420
> 1.414213562373095048801689
> 1.4142135623730951
Edit: Updated the code and the links to reflect the current version at the time (v4.3.1). Based on @ile an @Tomasz comments, thanks.
编辑:更新了代码和链接以反映当时的当前版本(v4.3.1)。基于@ile 和@Tomasz 评论,谢谢。
回答by cletus
Try Big Square Roots. It uses the Newton's methodfor approximating solutions such as square roots.
回答by quant_dev
(This is may not be a solution for you)
(这可能不是您的解决方案)
As long as your BigDecimal is in the range of double, you can convert the BigDecimal to double, use Math.sqrt() and promote the double back to BigDecimal. It will probably be faster than carrying out the calculation on BigDecimals. In many cases the loss of precision due to conversion between types will be negligible compared to the inevitable error in computing the square root.
只要您的 BigDecimal 在 double 的范围内,您就可以将 BigDecimal 转换为 double,使用 Math.sqrt() 并将 double 提升回 BigDecimal。它可能比在 BigDecimals 上执行计算更快。在许多情况下,与计算平方根时不可避免的错误相比,由于类型之间的转换而导致的精度损失可以忽略不计。

