2
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?

Alon Shmiel
  • 6,753
  • 23
  • 90
  • 138

4 Answers4

6

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.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

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

Stochastically
  • 7,616
  • 5
  • 30
  • 58
3

You could do:

f += (f < 0) ? -0.2 : +0.2;
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
1

How about you use the conditional operator?

f += (f < 0) ? -0.2f : 0.2f;
antonijn
  • 5,702
  • 2
  • 26
  • 33