Search code examples
algorithmmath

Function for clamping an angle


I want a function to return a value in the range [0, tau) for any given finite number.

Naively I would write

const TAU = Math.PI * 2;
function clamp(theta) {
    while(theta < 0) theta += TAU;
    return theta % TAU;
}

However, I note that this is constant time for positive theta and linear time for negative theta. Is there a solution that is O(1) for all input values?


Solution

  • How does % works in your language for negative argument?

    In Python it gives modulo, and

    def clamp(theta):
       return theta % TAU
    

    returns needed result (for example, same results for pi/2, 5*pi/2, -3*pi/2)

    If % is remainder, you can use the next expression (as recommended for JS) to make corrections for negative results:

    ((theta % TAU) + TAU) % TAU