Checking if a floating point value is within a certain range

Jun 2, 2014 at 5:45pm
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.?
Jun 2, 2014 at 6:00pm
Use the standard > and < or (<= and >=) operators?
Jun 2, 2014 at 6:22pm
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 Jun 2, 2014 at 6:24pm
Jun 2, 2014 at 8:59pm
Thanks; however, aren't such comparisons typically deprecated when it comes to floating point values?
Jun 3, 2014 at 1:15am
@Stewbond how does your second example work? Wont it will always be true if range is positive.
Jun 3, 2014 at 1:37am
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.
Jun 3, 2014 at 4:46am
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 Jun 3, 2014 at 4:46am
Jun 3, 2014 at 4:49am
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 Jun 3, 2014 at 4:52am
Topic archived. No new replies allowed.