I frequently work with float or double types which are in a range of [0, 1]. I am aware that floating point operations are imprecise, so I typically clamp my values so that they are guaranteed to be in this range before/after operations.
In some cases I rely on floats being not even slightly negative and being exactly <= 1, making this necessary.
For example is it necessary in any of these functions:
// x and y are guaranteed to be in [0, 1]
float avg(float x, float y) {
// the average of [0, 1] values should always be in [0, 1]
return std::clamp<float>((x + y) / 2, 0, 1);
}
float mul(float x, float y) {
// the product of [0, 1] values should always be in [0, 1]
return std::clamp<float>(x * y, 0, 1);
}
float pow(float x, unsigned y) {
// raising an [0, 1] value to any unsigned power should also result in an [0, 1] value
return std::clamp<float>(std::pow(x, y), 0, 1);
}
Are there any consistent rules for when arithmetic operations can make floats leave the [0, 1] range?