To adjust a floating-point number so that it falls within a specified range and wraps around when it exceeds that range, we can use a modulo-like operation tailored for floating-point arithmetic.
✅ Function Overview
The function wrap takes three parameters:
x: The floating-point number to be adjusted.
min: The lower bound of the desired range.
max: The upper bound of the desired range.
It ensures that the output value lies within [min, max) — i.e., it is inclusive of min and exclusive of max. If x is outside this interval, it wraps around to the beginning of the range.
This is a common requirement in applications like angle wrapping (e.g., 360 degrees → 0 degrees), circular buffers, or any situation involving periodic behavior.
🧠 Implementation Strategy
-
Calculate the range length:
length = max - min
-
Shift the value to align with zero:
dx = x - min
This makes the range start from 0.
-
Compute the modulo of the shifted value:
rem = fmod(dx, length)
This gives a remainder in the range [-length, length).
-
Adjust negative remainders to be within [0, length):
If rem < 0, add length to it.
-
Shift back to the original range:
return rem + min
This ensures the result is always in [min, max).
🧪 Example Usage
#include <iostream>
#include <cmath> // for fmod
double wrap(double x, double min, double max) {
double length = max - min;
double dx = x - min;
double rem = std::fmod(dx, length);
if (rem < 0) {
rem += length;
}
return rem + min;
}
int main() {
std::cout << wrap(1.5, 0.0, 1.0) << std::endl; // 0.5
std::cout << wrap(-0.5, 0.0, 1.0) << std::endl; // 0.5
std::cout << wrap(3.0, 1.0, 3.0) << std::endl; // 1.0 (since max == min, no wrapping)
std::cout << wrap(3.5, 1.0, 3.0) << std::endl; // 1.5 (wraps around)
return 0;
}
⚠️ Important Notes
- Assumption:
max > min is required. If max == min, the function will crash due to division by zero.
- Edge Cases:
- If
x == max, it will wrap to min.
- If
x == min, it stays at min.
This implementation is efficient, robust, and suitable for use in a wide range of applications involving circular or periodic data.