[英]compare Java Double.Max_VALUE with large double numbers returns true
[英]Java method (type, double) returns negative value for large number (not large enough to exceed max value)
我是Java的新手,我寫了一個方法double farey_S(int N)
,該方法的double farey_S(int N)
為N = 10,000,但在N = 100,000時,它返回負數,就好像它溢出了一樣。 但是從輸出模式來看:
farey_S(10) = 6.914682539682538
farey_S(100) = 58.296238062166246
farey_S(1000) = 517.9547174126604
farey_S(10000) = 5030.839940050789
farey_S(100000) = -8366.231603179493
輸出不應該是遠遠不夠大,超出了允許的最大值。
這是代碼:
public class InverseCoprimeSum {
public static void main(String[] args) {
System.out.println("farey_S(10) = " + farey_S(10));
System.out.println("farey_S(100) = " + farey_S(100));
System.out.println("farey_S(1000) = " + farey_S(1000));
System.out.println("farey_S(10000) = " + farey_S(10000));
System.out.println("farey_S(100000) = " + farey_S(100000));
}
public static double farey_S(int N) {
double tot = 0.0;
int a, b, a1, b1, c, d, k;
a = 0;
b = 1;
c = 1;
d = N;
while(c < N) {
k = (N + b) / d;
a1 = a;
b1 = b;
a = c;
b = d;
c = k * c - a1;
d = k * d - b1;
if(a < N - b)
tot += (a + 1.0) / (a * b);
else
tot += (N - b + 1.0) / (a * b);
}
tot -= 2;
return tot;
}
}
乘法(a * b)
作為整數乘法完成,從而導致整數溢出。
要進行兩次乘法運算,應該類似於
...
if(a < N - b)
tot += (a + 1.0) / ((double)a * b);
else
tot += (N - b + 1.0) / ((double)a * b);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.