Here’s a fun little experiment you can do which is an interesting way of revealing some ‘gotchas’ with the internal math used by your computer. Here’s the code:
float x;
x = .5;
if(x == .5)
NSLog(@"x is .5");
else
NSLog(@"Whoah! X is actually %f",x);
x = .7;
if(x == .7)
NSLog(@"x is .7");
else
NSLog(@"Whoah! X is actually %f",x);
x = .7;
if(x == .7f)
NSLog(@"x is .7");
else
NSLog(@"Whoah! X is actually %f",x);
You can run this yourself, or just check the actual output below.
x is .5
Whoah! X is actually 0.700000
x is .7
At first glance this might seem odd. You would expect that .7 is .7 is .7. But such is not the case as far as your computer is concerned. In the second example (where the values are found to be unequal, and yet the output appears to show that they are equal), the lack of the “f” on the end of the comparison value means that the compiler interprets that literal .7 value as a double. And a float with .7 is not equal to a double with .7. The specifics of why this is so can be explained by floating point math ‘lack of precision’, which is all fine and dandy, but at first glance it sure seems strange that .7 does not always equal .7, especially since .5 in this case always equals .5!
This is a perfect example of why sometimes it is important to understand the inner workings of how the processor actually performs its math and value comparisons, especially with floating point variables. I find this kind of stuff fascinating because normally as I code I think of the computer as processing these kinds of instructions in the most fundamentally logical and reasonable way (ie, .7 = .7 = .7), and yet it’s fun to bump into these little situations where things don’t behave quite the way you might expect at first.
In other news, for those of you who are visiting to check the status of the recent updates announced for several of BravoBug’s shareware apps (EasyBatch, IconBurglar, Blackout etc.), I wanted to thank you both for your support in registering and also for your patience, I am working on getting those updates out as quickly as possible. Thank you for visiting, -Matt.