1

Simple question, I know there must be a correct way to do this. I have a CGFloat that increases in increments of 1/16. I want to determine when this value becomes a whole number.

For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations and mod 16 it.

2
  • A better solution would be to increase an int by 1 and then divide it by 16 to get the whole number. Commented Nov 27, 2012 at 22:01
  • Generally, when comparing for equality, you should take the absolute value of the difference and then compare that to "epsilon" -- a value larger than the inherent error of floating point but smaller than the precision you require. Commented Nov 27, 2012 at 22:08

3 Answers 3

4

While you generally can't count on fractional floating point numbers to sum up to whole numbers, your case is exception to the rule since 1/16 is 2^(-4) and this number can be represented by float precisely:

- (void)testFloat { float a = 0.0f; while (a != 2.0f) { a += 0.0625f; } NSLog(@"OK!"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you must start from an exact multiple of 1/16 (such as 0.0f) if you want to reliably reach a whole number.
2

It's better to do it the other way around, i.e. use an integer loop counter and convert this to a float:

for (int i = 0; i < 100; ++i) { float x = (float)i / 16.0f; if (i % 16 == 0) { // if x is whole number... } } 

Comments

1

Floating point arithmetic is inexact so you can't count on the value of your variable ever being exactly 2.0000.

"For lack of knowing the right way I am coming up with ideas like having another variable to keep track of the number of iterations andmod 16 it."

This is a wonderful idea.

1 Comment

Yes you can count on it. 1.0/16.0 is exact, and thus repeatedly adding it will result in exact whole numbers. The only issue is that once your floating point value gets sufficiently large, adding to it will result in rounding and will eventually become a no-op.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.