Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this return Infinity? (Java)

Im trying to find the result of 1/1 + 1/4 + 1/9 + 1/16 + 1/25 ...

These is the lines I wrote that give the result 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. 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?

like image 688
Vu TrongNghia Avatar asked Jan 05 '23 07:01

Vu TrongNghia


1 Answers

Because your testLimit as well as your i are defined as 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.

Specifically, when i reaches 2¹⁶, i*i will be 2³². This means 1 followed by 32 zeros in binary, of which, only the 32 zeros are kept, which means zero. (Thanks @templatetypedef).

Therefore, you'll have a number divided by zero, which is infinity.

Change your loop declaration so that i is double. Or multiply by a double (1.0) on the left hand of i*i. This will cause the expression to be changed into double before multiplying by the second i.

like image 128
RealSkeptic Avatar answered Jan 08 '23 10:01

RealSkeptic