Fastest way to clamp a real (fixed/floating point) value?
Posted
by Niklas
on Stack Overflow
See other posts from Stack Overflow
or by Niklas
Published on 2009-01-09T09:13:11Z
Indexed on
2010/03/21
15:31 UTC
Read the original article
Hit count: 228
Hi, Is there a more efficient way to clamp real numbers than using if statements or ternary operators? I want to do this both for doubles and for a 32-bit fixpoint implementation (16.16). I'm not asking for code that can handle both cases; they will be handled in separate functions.
Obviously, I can do something like:
double clampedA;
double a = calculate();
clampedA = a > MY_MAX ? MY_MAX : a;
clampedA = a < MY_MIN ? MY_MIN : a;
or
double a = calculate();
double clampedA = a;
if(clampedA > MY_MAX)
clampedA = MY_MAX;
else if(clampedA < MY_MIN)
clampedA = MY_MIN;
The fixpoint version would use functions/macros for comparisons.
This is done in a performance-critical part of the code, so I'm looking for an as efficient way to do it as possible (which I suspect would involve bit-manipulation)
EDIT: It has to be standard/portable C, platform-specific functionality is not of any interest here. Also, MY_MIN
and MY_MAX
are the same type as the value I want clamped (doubles in the examples above).
© Stack Overflow or respective owner