Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure a number is within a range?

Tags:

c++

stl

boost

Suppose I have some value:

double x;

and I want to confine it to some range [a, b] such that the resulting value is within that range:

double confine(double x, double a, double b)
{
  if (x < a) return a;
  else if (x > b) return b;
  return x;
}

Is there a single boost or STL function that can do this for me?

like image 735
quant Avatar asked Dec 14 '22 15:12

quant


1 Answers

Yes, Boost Algorithm has clamp:

double clamped = clamp(x, a, b);

It requires only operator< or a custom comparator, and guarantees that it is called only once or twice. The documentation points out that with double and other floating-point types, NaN could cause unexpected results.

like image 146
chris Avatar answered Dec 31 '22 18:12

chris