繁体   English   中英

Java Math问题输出不正确

[英]Java Math issue incorrect output

(51 ^ 43)科学计算器中的Mod77给出2作为输出,

(int)(Math.pow(51,43)%(double)77)给出的12应该是2。

你能帮忙吗?

    final BigInteger base = BigInteger.valueOf(51);
    final BigInteger exponent = BigInteger.valueOf(43);
    final BigInteger modulus = BigInteger.valueOf(77);
    System.out.println(base.modPow(exponent, modulus));

打印2

double精度没有足够的精度来容纳Math.pow(51,43)所有数字。 因此,当您使用mod 77 ,答案很容易出现明显的舍入错误。

我建议使用BigInteger进行任意精度的整数运算。

代替:

(int)(Math.pow(51,43)%(double)77)

做:

(int)(Math.pow(51,43))%((double)77)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM