Thompson
Thompson

Reputation: 1098

CGAffineTransformMakeRotation on CGPoint unexpected values

I am rotating CGPoints using a CGAffineTransformRotation

Executing this code:

double degToRad(double degrees) {
  return ((degrees) * (M_PI / 180.0));
}

CGAffineTransform rotate = CGAffineTransformMakeRotation(degToRad(-90.0));

NSLog(@"before n.nP %@",NSStringFromCGPoint(node.nodePoint));

node.nodePoint = CGPointApplyAffineTransform(node.nodePoint, rotate);

NSLog(@"after  n.nP %@",NSStringFromCGPoint(node.nodePoint));

Gives these results:

before n.nP {96, 196}
after n.nP  {196, -95.999999999999986}

This is understandable; -95.999... as opposed to -96 is due to some internal rounding/the limit on the degree of expression of M_PI. The degree of difference in this instance is negligible.

But these results:

before n.nP {0, 768}
after n.nP  {768, 4.702643708725836e-14}

...are what puzzle me. I expect {768, 0} or pretty dang close as a return value. Why is the degree of difference in this case so large?

Upvotes: 1

Views: 55

Answers (1)

Ryan
Ryan

Reputation: 3993

So the difference isn't so large. In fact, it's very tiny! Before we jump into why there is this difference, let's explain what that difference means:

after n.np {768, 4.702643708725836e-14}

Notice the e-14 at the end. That means 4.702643708725836 x 10^-14, or .00000000000004702643708725836, which is very close to 0. To learn more about E Notation, read this!

Now, why this happens is both the inaccuracy of M_PI and floating point representation. Floating point numbers (floats) are how the C language (and many others) represent non-integral (int) numbers. It uses an approximation-based method as it's impossible to represent all numbers in a realistic number of bits. Doubles are just like floats, but use two times as many bits (hence double) to represent real numbers, and thus have more accuracy. But they are still approximations, and sometimes have small artifacts of inaccuracy, and thus you shouldn't directly compare floats typically.

Upvotes: 1

Related Questions