How do I use modulus for float/double?
I'm creating an RPN calculator for a school project and having trouble with the modulus operator. Since we're using the double data type, modulus won't work on floating-point numbers. For example, 0.5 % 0.3 should return 0.2, but I'm getting a division by zero exception.
The instruction says to use fmod()
. I've looked everywhere for fmod()
, including javadoc, but I can't find it. I'm starting to think it's a method I'm going to have to create?
Edit: Hmmm, strange. I just plugged in those numbers again and it seems to be working fine… but just in case. Do I need to watch out for using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).
Solution 1:
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
Solution 2:
Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):
From JLS §15.17.3:
The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:
- If either operand is NaN, the result is NaN.
- If the result is not NaN, the sign of the result equals the sign of the dividend.
- If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
- If the dividend is finite and the divisor is an infinity, the result equals the dividend.
- If the dividend is a zero and the divisor is finite, the result equals the dividend.
- In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, 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 for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2