C++ Function to Wrap a Floating-Point Number Within a Range
Here's a C++ function that adjusts a floating-point number to stay within a specified range, wrapping around when it goes outside the bounds:
#include <cmath>
#include <algorithm>
/**
* Wraps a floating-point value within a specified range.
*
* @param value The input value to be wrapped
* @param min The minimum value of the range (inclusive)
* @param max The maximum value of the range (inclusive)
* @return The wrapped value within the range [min, max]
*/
double wrapInRange(double value, double min, double max) {
// Handle the case where the range is invalid
if (min >= max) {
return min; // or could return value, or throw an exception
}
const double range = max - min;
// Calculate how many times the range fits into the difference
double diff = value - min;
double wrapped = fmod(diff, range);
// Handle negative values
if (wrapped < 0) {
wrapped += range;
}
return min + wrapped;
}
Alternative Version (Using std::fmod)
Here's a slightly more concise version using std::fmod:
#include <cmath>
double wrapInRange(double value, double min, double max) {
if (min >= max) return min;
const double range = max - min;
return min + std::fmod(std::fmod(value - min, range) + range, range);
}
Example Usage
#include <iostream>
int main() {
// Example: Wrap angles between 0 and 360 degrees
double angle = 400.0;
double wrapped = wrapInRange(angle, 0.0, 360.0);
std::cout << "Original: " << angle << ", Wrapped: " << wrapped << std::endl;
// Example: Wrap time between 0 and 24 hours
double time = -3.5;
wrapped = wrapInRange(time, 0.0, 24.0);
std::cout << "Original: " << time << ", Wrapped: " << wrapped << std::endl;
return 0;
}
Key Features
- Handles both positive and negative values correctly
- Works with any floating-point range (not just 0-360 or similar)
- Uses
fmod for efficient modulo operation
- Includes basic error handling for invalid ranges
- Returns the minimum value if the range is invalid (could be modified to throw an exception if needed)
The function essentially calculates how many times the range fits into the difference between the value and the minimum, then returns the remainder adjusted to stay within the range.