Search code examples
javamathdivide-by-zero

Why is it that when I have X(long) / (Y*Y*Y)(long) I get Error: Divide by Zero?


In my example X is already long and Y is a long also. I am not casting at then.

I really just want to divide by a number that is cubed. (using native libraries)

These numbers are extremely large. If I convert them to floats and do it, its value is Infinite...

System.out.println(formatter.format("%20d", (X/(Y*Y*Y))));

Y is an extremely large number, it is not 0. X is a measurement of time in milliseconds.

I will post the exact code in a short while if this question doesn't get closed... I don't have access to it right this minute.

Context: I am dealing with a big notation calculation for O(n^3).

Error: "Exception in thread "main" java.lang.ArithmeticException: / by zero"

Answers:

Assuming you didn't really mean the quotes, the likely reason is that Y * Y * Y is greater than 2 ^ 31. It's overflowing, with a lower part of 0. I believe this would only happen if Y is a multiple of 2^11 (2048) - but I'm not certain*

-This is the case for me, Y is a multiple of 2048, hopefully this helps with trying to find a solution.

    // Algorithm 3
    for( int n = 524288; n <= 5000000; n *= 2 ){
        int alg = 3;
        long timing;
        maxSum = maxSubSum3( a );
        timing = getTimingInfo( n, alg );
        System.out.println(fmt.format("%20s %20d %20d %20d %20d %20s%n", "Alg. 3", n, timing, timing, timing/(n*n), "time/(n*log(n))"));
    }

Solution

  • Assuming you didn't really mean the quotes, the likely reason is that Y * Y * Y is greater than 2 ^ 31. It's overflowing, with a lower part of 0.

    I believe this would only happen if Y is a multiple of 2^11 (2048) - but I'm not certain.

    It can be avoided by making sure that the computation of Y^3 is done using some datatype that can hold it. If it's less than 2 million, you can use a long instead. If not, you'll have to either use a double or a BigInteger. Given that your other value is in milliseconds, I'd guess that floating point would be fine. So you'd end up with:

    System.out.println(formatter.format("%20d", (int)(X/((double)Y*Y*Y))));
    

    You may want to use floating point for the output as well - I assumed not.