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)
sin(x)
for large values ofx
actually requires a very difficult transcendental argument reduction process that cannot get by with any finite approximation of pi. – R.. GitHub STOP HELPING ICE May 23 '11 at 21:03fmod
is likely what the instructor is looking for. – Dennis Zickefoose May 23 '11 at 21:16