Function for clamping an angle

ghz 8months ago ⋅ 81 views

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?

Answers

You can achieve constant time complexity for all input values by using modular arithmetic directly. Here's a revised version of your clamp function that ensures constant time complexity:

const TAU = Math.PI * 2;

function clamp(theta) {
    // Apply modular arithmetic to ensure theta is in the range [0, tau)
    return ((theta % TAU) + TAU) % TAU;
}

Explanation:

  • The expression (theta % TAU) ensures that theta is brought into the range [-tau, tau).
  • Adding TAU to the result ensures that the value is non-negative.
  • Finally, applying another modulo operation with TAU ensures that the value is in the range [0, tau).

This approach ensures constant time complexity for all input values of theta, regardless of whether they are positive or negative.