0

At first, I set a view's alpha to 0.4, I want to some actions later when aView.alpha == 0.4, but the compare failed.

Code:

aView.alpha = 0.4;
...//never changes aView.alpha.
if (aView.alpha == 0.4) {
    //this compare failed.
}

BUT, when I set the alpha to 0.5, it works!

aView.alpha = 0.5;
...
if (aView.alpha == 0.5) {
    //it's OK.
}

Anything wrong?

fannheyward
  • 18,599
  • 12
  • 71
  • 109

1 Answers1

1

Never compare floats using equality. It can work (apparently "positive zero" and "negative zero" are exact values) but you need to check that there is a very small difference, not that they are equal. Like:

#define TINY_DELTA (.0001f)

if(fabsf(floatA - floatB) < TINY_DELTA) {
    // equal for all intensive porpoises
}

(Actually you have doubles there. In general, use "0.5f" to use floats. It is generally faster on most of the hardware out there.)

Community
  • 1
  • 1
Adam Eberbach
  • 12,309
  • 6
  • 62
  • 114