0

I was trying experimenting with Java a little, and this problem came up:

public class TestRandom {
    public static void main(String[] args){
        System.out.println(Math.pow((1/(1+1)),1));
    }
}

evaluated to 0.0, which was most likely originally NaN.

Is there something wrong with me or is there a real explanation?

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97

1 Answers1

11

You've got an integer division in there. 1/2 is 0, not 0.5.

You could try changing the expression to Math.pow((1.0/(1+1)),1) to force this to be a floating-point division.

Edit

Division in Java has been designed in the same way as it was in C and C++, which came before Java. When you do division with two expressions of type int, you get a result of type int. This was a choice that the language designers made, for better or worse, and we're stuck with it now. But basically it means that any fractional result from a division gets rounded downwards (strictly speaking, towards zero). In this case, 1/2 gets rounded to 0.

The same kind of thing happens with long.

The Java Language Specification says

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

Community
  • 1
  • 1
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110