Use fmod for modulus calculations on floats

Everyone knows about the modulus operator (%) and that it returns the remainder of an integer division:

// mod = 1
int mod  = 11 % 2;

Occasionally you’ll need to get a remainder of a floating point calculation. I’m finding this more and more while using CoreAnimation and CoreGraphics since screen placement is handled through CGFloats. Fortunately the math.h library includes the function fmod to handle this:

#import <math.h>

CGFloat mod = fmod(47.236456, 5);
NSLog(@"%f", mod);
// prints 2.236456

While your CGRects and CGPoints will be whole numbers most of the time, when dealing with animations coordinates will often have trailing decimals. Additionally you’ll find that points on retina display interfaces will frequently be measured to the half pixel.

fmod reference on cplusplus.com

Advertisements

Posted on February 28, 2011, in Code and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: