简体   繁体   English

为什么这会归还无限? (JAVA)

[英]Why does this return Infinity? (Java)

Im trying to find the result of 1/1 + 1/4 + 1/9 + 1/16 + 1/25 ... 我试图找到1/1 + 1/4 + 1/9 + 1/16 + 1/25的结果......

These is the lines I wrote that give the result Infinity : 这些是我写的给出结果Infinity

public class BaselProblem {
    public static void main(String[] args) {
        int testLimit = 100000;
        double sum = 0;
        for (int i = 1; i<testLimit; i++) 
        {
            sum = sum + 1.0/(i*i);
        }
        System.out.println(sum);
    }
}

Changing 1.0/(i*i) to 1/(1.0*i*i) gives the correct result 1.6449240667982423 . 1.0/(i*i)更改为1/(1.0*i*i) 1.6449240667982423 1/(1.0*i*i)可得到正确的结果1.6449240667982423 Why is it that only the 2nd form work but not the 1st? 为什么只有第二种形式起作用但不起作用?

Also, because (i*i) > 1 , then 1.0/(i*i) should be < 1 , so how can it leads to in Infinity ? 另外,因为(i*i) > 1 ,那么1.0/(i*i)应该< 1 ,那么它如何导致Infinity

Because your testLimit as well as your i are defined as int . 因为你的testLimit以及你的i被定义为int Since you put the expression i*i in parentheses, it will be calculated first, and will try to find the multiple of two integers - which will reach overflow pretty quickly and reset to zero. 由于你将表达式i*i放在括号中,它将首先计算,并将尝试找到两个整数的倍数 - 这将很快达到溢出并重置为零。

Specifically, when i reaches 2¹⁶, i*i will be 2³². 具体来说,当i达到2¹⁶时, i*i将是2³²。 This means 1 followed by 32 zeros in binary, of which, only the 32 zeros are kept, which means zero. 这意味着1后跟32个二进制零,其中只保留32个零,这意味着零。 (Thanks @templatetypedef). (谢谢@templatetypedef)。

Therefore, you'll have a number divided by zero, which is infinity. 因此,您将有一个除以零的数字,即无穷大。

Change your loop declaration so that i is double . 更改你的循环声明,以便idouble Or multiply by a double (1.0) on the left hand of i*i . 或者乘以i*i 左边的double(1.0)。 This will cause the expression to be changed into double before multiplying by the second i . 这将导致表达式乘以第二个i 之前变为double

Java integer have a maximum value of 2,147,483,647. Java整数的最大值为2,147,483,647。 You're eventually surpassing that maximum with the integer that results from i*i. 你最终会用i * i产生的整数超过那个最大值。

If you do 1.0*i*i, you're converting the result to a double which can hold a maximum value of 1.79769313486231570E+308. 如果你做1.0 * i * i,你将结果转换为一个双倍,它可以保持最大值1.79769313486231570E + 308。

Your maximum value for i*i will be 10,000,000 which a double can hold, but an integer can't. i * i的最大值将是10,000,000,双倍可以容纳,但整数不能。

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

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