我正在从 Programming in Java book-site 中解决这个问题(为了练习,不是 HW .. Q15 在http://introcs.cs.princeton.edu/java/13flow/):
求谐波级数 1/1 + 1/4 + 1/9 + 1/16 + ... + 1/N2 的总和。for 循环有 4 种变体,其中一些应该给出正确的答案。我的预期答案在评论中,实际结果如下。
public class OneThreeExFifteen {
public static void main(String[] args) {
int N = 1000000;
double s1=0 , s2 = 0, s3 = 0, s4=0;
for (int i = 1; i <= N ; i++ )
s1 = s1 + 1 / ( i * i ); // Expected s1 = 1
for (int i = 1 ; i <= N ; i++ )
s2 = s2 + 1.0 / i * i; // Expected s2 = 1000000
for (int i = 1 ; i <= N ; i++)
s3 = s3 + 1.0 / (i * i) ; // Correctly computes the series sum
for (int i = 1; i <= N ; i++ )
s4 = s4 + 1 / (1.0 * i * i) ; // Correctly computes the serires sum
System.out.println("for loop 1" + s1);
System.out.println("for loop 2" +s2);
System.out.println("for loop 3" +s3);
System.out.println("for loop 4" +s4);
}
}
结果:
for loop 1 ( I get a Divide by 0 error - had to comment out this loop)
for loop 2 1000000.0
for loop 3 Infinity
for loop 4 1.64493306684877
问题 - 为什么我会得到
a) 除以零误差?
b) for 循环 3 的无穷大结果?