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,333
  • 19
  • 88
  • 134

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
  • 697,062
  • 78
  • 1,055
  • 1,465
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,476
  • 5
  • 29
  • 58
3

You could do:

f += (f < 0) ? -0.2 : +0.2;
Andy Prowl
  • 119,862
  • 22
  • 374
  • 446
1

How about you use the conditional operator?

f += (f < 0) ? -0.2f : 0.2f;
antonijn
  • 5,562
  • 2
  • 24
  • 32