user3540466 user3540466 - 2 months ago 7
Java Question

Floating point arithmetic not working as expected

The following simple floating point arithmetic operation is not working as expected.

double den = (1+j);
den = 1/den;

double newden = 1/(1+j);

The above code gives the following output.




As shown above, the first two operations work as expected but the last doesn't. I suppose that it has something to do with the variable type but still haven't figured out the problem.

Can you please explain the behaviour of arithmetic operations in Java?


An arithmetic operation in java is done in int if there is no float/double/long involved. Hence, change one of the arg to float/double and it works as expected.

The following code would work:

double newden = 1d/(i+j);

From the java spec:

Widening primitive conversion (ยง5.1.2) is applied to convert either or both operands as specified by the following rules, in order:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.