Your code first computes appdelegate.userRed/255.0
where appdelegate.userRed
is 128. Mathematically, this is 128/255. However, since you are using floating-point arithmetic in a computer, the computer must return a value that is representable in that floating-point system rather than the exact mathematical value. In this case, 128/255.0
has type double
, and the double
that is closest to 128/255 is 0.5019607843137254832299731788225471973419189453125.
Then your code assigns that value to red
. Since red
is a float
, the value is converted to float
. Again, the value must be rounded. The float
value that is nearest to 0.5019607843137254832299731788225471973419189453125 is 0.501960813999176025390625.
Then you compare red
to 0.501961
. The compiler converts the source text 0.501961
to the nearest value representable as a double
, which is 0.50196099999999999052846533231786452233791351318359375.
Since 0.501960813999176025390625 is not equal to 0.50196099999999999052846533231786452233791351318359375, the comparison returns false.
It is difficult to suggest alternatives for you because you have not explained why you are making this comparison. If you merely wish to check whether the float
value of a pixel is the direct result of converting an integer 128 to float
by dividing by 255, then I suggest you use red==128/255.f
. (You may also wish to change appdeletegate.userRed/255.0
to appdelegate.userRed/255.f
so that you are nominally using float
, rather than double
throughout your code.)
However, if you are doing anything more involved with floating-point arithmetic, there are additional considerations. In particular, if a float
value is not the direct result of this conversion by dividing by 255 but is the result of additional arithmetic, then it is likely the value will contain additional rounding errors, and comparing it directly to 128/255.f
will not produce the desired result.