Bug in fminf and fmaxf on iOS 64bit processors
Question
I came across a bug with the 64bit processors that I wanted to share.
CGFloat test1 = 0.58;
CGFloat test2 = 0.40;
CGFloat value;
value = fmaxf( test1, test2 );
The result would be:
value = 0.5799999833106995
This obviously is a rounding issue, but if you needed to check to see which value was picked you would get an erroneous result.
if( test1 == value ){
// do something
}
however if you use either MIN( A, B ) or MAX( A, B ) it would work as expected.
I thought this is was worth sharing
Thanks
Solution
This has nothing to do with a bug in fminf
or fmaxf
. There is a bug in your code.
On 64-bit systems, CGFloat
is typedef'd to double
, but you're using the fmaxf
function, which operates on float
(not double
), which causes its arguments to be rounded to single precision, thus changing the value. Don't do that.
On 32-bit systems, this doesn't happen because CGFloat
is typedef'd to float
, matching the argument and return type of fmaxf
; no rounding occurs.
Instead, either include <tgmath.h>
and use fmax
without the f
suffix, or use float
instead of CGFloat
.