I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
Given a periodic function (e.g.
sin
) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
The "obvious" solution is something like:
#include <cmath>
float sin(float x){
return limited_sin((x + M_PI) % (2 *M_PI) - M_PI);
}
Why doesn't this work? I get this error:
error: invalid operands of types double and double to binary operator %
Interestingly, it does work in Python:
def sin(x):
return limited_sin((x + math.pi) % (2 * math.pi) - math.pi)
try
fmod
I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.
The % operator gives you a REMAINDER(another name for modulus) of a number. For C/C++, this is only defined for integer operations. Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:
The
%
operator does not work in C++, when you are trying to find the remainder of two numbers which are both of the typeFloat
orDouble
.Hence you could try using the
fmod
function frommath.h
/cmath.h
or you could use these lines of code to avoid using that header file:}
The modulo operator
%
in C and C++ is defined for two integers, however, there is anfmod()
function available for usage with doubles.The constraints are in the standards:
C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators
C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators
The solution is to use
fmod
, which is exactly why the operands of%
are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators: