Java Math.pow的错误结果 [英] Wrong result by Java Math.pow
问题描述
如果您尝试运行以下代码
If you try to run the following code
public class Main {
public static void main(String[] args) {
long a = (long)Math.pow(13, 15);
System.out.println(a + " " + a%13);
}
}
您将获得51185893014090752 8
You will get "51185893014090752 8"
13 ^ 15 的正确值为 51185893014090757 ,即大于 Math返回的结果。 pow
5 。可能导致它的任何想法?
The correct value of 13^15 is 51185893014090757, i.e. greater than the result returned by Math.pow
by 5. Any ideas of what may cause it?
推荐答案
你已经超过了有效位数(~15到16)双精度浮点值。一旦你这样做,你就不能指望你的结果中最不重要的数字真正有意义/精确。
You've exceeded the number of significant digits available (~15 to 16) in double-precision floating-point values. Once you do that, you can't expect the least significant digit(s) of your result to actually be meaningful/precise.
如果你需要在Java中任意精确的算术,考虑使用 BigInteger
和 BigDecimal
。
If you need arbitrarily precise arithmetic in Java, consider using BigInteger
and BigDecimal
.
这篇关于Java Math.pow的错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!