Simbody  3.8

Limit a numerical value so that it does not go outside a given range.

Limit a numerical value so that it does not go outside a given range.

There are two functions (plus overloads) defined here: clamp() and clampInPlace(). The first one is the most commonly used and simply calculates an in-range value from an input value and a given range [low,high]. clampInPlace() is given a reference to a variable and if necessary modifies that variable so that its value is in the given range [low,high]. Both functions are overloaded for all the integral and real types but are not defined for complex or conjugate types.

The following examples shows how clamp() and clampInPlace() can be defined in terms of std::min() and std::max().

clamp():

const double low, high; // from somewhere
const double v;
double clampedValue;
clampedValue = clamp(low,v,high); // clampedValue is in [low,high]
clampedValue = std::min(std::max(low,v), high); // equivalent
ELEM max(const VectorBase< ELEM > &v)
Definition: VectorMath.h:251
ELEM min(const VectorBase< ELEM > &v)
Definition: VectorMath.h:178
double clamp(double low, double v, double high)
If v is in range low <= v <= high then return v, otherwise return the nearest bound; this function do...
Definition: Scalar.h:634

clampInPlace():

const double low, high; // from somewhere
double v;
clampInPlace(low,v,high); // now v is in [low,high]
v = std::min(std::max(low,v), high); // equivalent
double & clampInPlace(double low, double &v, double high)
Check that low <= v <= high and modify v in place if necessary to bring it into that range.
Definition: Scalar.h:533