float f = -0.050000;
I want to do the next rules:
if (f < 0) f -= 0.2;
else f += 0.2;
there is an option to do it by one line?
float f = -0.050000;
I want to do the next rules:
if (f < 0) f -= 0.2;
else f += 0.2;
there is an option to do it by one line?
You can use a modified version of C++ branchless signum function for this:
f += 0.2 * ((0<=f)-(f<0));
The expression
(0<=f)-(f<0)
evaluates to -1
when f
is less than zero, to 1
when f
is greater than or equal to zero.
If copysign or an equivalent is available, then
f += copysign(0.2,f);
is likely to be the fastest with modern computers because it avoids branching. Given the length of processing pipelines on modern CPUs, a branch misprediction can easily cost several cycles