Java Math.pow的错误结果 [英] Wrong result by Java Math.pow

查看:167
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆