Possible Duplicate:
CGFloat addition bug?
I have some code where I’m doing a lot of multiplying and dividing of CGFloats in order to figure out the correct dimensions for transformations. I notice sometimes when I’m suppose to get a value of 320, I’ll get 320.00000092 instead. Can anyone explain why this is happening and how to correct it? Is it suppose to be doing this? Here is some sample code where it’s possible the problem might be happening:
- (void) setMinimumSize
{
CGSize superViewSize = self.superview.bounds.size;
CGSize size = self.frame.size;
CGFloat xScale = superViewSize.width / size.width;
CGFloat yScale = superViewSize.height / size.height;
CGFloat minimumScale = MIN(xScale, yScale);
self.minimumSize = CGSizeMake(size.width * minimumScale, size.height * minimumScale);
}
- (void) scaleToMinimumSize
{
self.transform = CGAffineTransformScale(self.transform, self.minimumSize.width / self.frame.size.width, self.minimumSize.height / self.frame.size.height);
}
Don’t compare for equality, won’t work for float (or double), rather compare
the difference against some delta that suits your needs for accuracy
This is always an issue with decimal and floating points numbers.
Ask a middle school student (1/3.0)*3.0, all will say 1. Computer says 0.999999.
You cant expect, most of the time,
0to be0.000000it will never be near to that.EDIT:
If float is in so much of use, you should read this one
http://en.wikipedia.org/wiki/IEEE_754-2008
And also What Every Computer Scientist Should Know About Floating-Point Arithmetic,