17/2 = 8.5 (have 1 remainder so its equals 1 , ok )
now, i dont get it , 8.5 / 2 = 4.25 so why 8.5 % 2 = 0.5 ? it should be 2 ? because its have two digits after thr decimal point. - > 4.25 .
and the same for all the others
Dan D'amico wrote:now, i dont get it , 8.5 / 2 = 4.25 so why 8.5 % 2 = 0.5 ? it should be 2 ?
Should it? First-off, the idea of a modulus op (java actually calls it the "remainder operator") on a floating-point value seems somewhat odd to me.
For an explanation like this, you need to go to the horse's mouth; but unfortunately, even it doesn't provide examples of the style that you're doing. What it does do though is explain how the calculation is done - specifically:
"the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r = n - (d ⋅ q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d."
So, in your case above (8.5%2), the calculation is 8.5 - (2 * 4), which == 0.5.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
a) Basically all the time at the very beginning discard floating part as it's not significant and use only whole part.
b) Divide whole number by given number, in your case 2, take the remainder, and add him to floating part from the very beginning.
No, I am afraid that is not how it works. The details are in the JLS link which Winston posted earlier.
Remember that the operands of binary arithmetic operators undergo promotion before the operation. So the first things which happens is that the division is converted from
9.25 % 2
9.25 % 2.0
9.25 / 2.0 → 4.625
This is truncated to 4.0
4.0 * 2.0 → 8.0
9.25 - 8.0 → 1.25 QED
campbell@XXXXX:~/java$ java RemainderDemo 9.25 2
9.250000 % 2.000000 = 1.250000
9.250000 BigDecimal.remainder(2.000000) = 1.250000
9.250000 IEEE% 2.000000 = -0.750000
java RemainderDemo 9.25 0
9.250000 % 0.000000 = NaN
Exception in thread "main" java.lang.ArithmeticException: Division by zero