![](/img/trans.png)
[英]Output is incorrect from a math equation with-in java, For the first person and second
[英]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.