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)
The modulo operator, like the other arithmetic operators, can be used with the numeric types int and float . As you'll see later on, it can also be used with other types like math. fmod() , decimal. Decimal , and your own classes.
The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y.
modulo doesn't work with decimals because it only accepts integers. As discussed above, you can define another procedure to see if two numbers are divisible by each other. Otherwise, the computer doesn't know how to accept non-integer numbers for modulo .
Integer division returns the quotient portion of a value, and modulus division returns the remainder.
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod
function, as well as remainder
function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
You're looking for fmod().
I guess to more specifically answer your question, in older languages the %
operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.
EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With