Checking if a floating point value is within a certain range

Suppose I wanted to check if a given floating point value is within a certain range. What would be Your recommended approach when considering simplicity, speed, portability, etc.?
Use the standard > and < or (<= and >=) operators?
1
2
3
4
5
template <typename T>
bool inline IsBetween(T value, T min, T max)
{
  return (value < max) && (value > min);
}

or
1
2
3
4
5
template <typename T>
bool inline IsBetween(T value, T range)
{
  return (value < (value + range)) && (value > (value - range));
}
Last edited on
Thanks; however, aren't such comparisons typically deprecated when it comes to floating point values?
@Stewbond how does your second example work? Wont it will always be true if range is positive.
aren't such comparisons typically deprecated when it comes to floating point values?
No. What gave you that impression?

RE Stewbond's second example: naraku is right, you would need to provide a midpoint for the range as well.
What gave you that impression?

I thought floating point comparisons was one of those things which should not be done due to the inexactness of representing certain numbers, such as 1/3.
Last edited on
That's only if you test for equality, i.e. == and !=. That is why checking a range (of acceptable error) is recommended over checking equality (Look at firedraco's suggestion and Stewbond's first example to see how to check a range).
Last edited on
Topic archived. No new replies allowed.