Jonathan
Jonathan

Reputation: 3034

atan(x) gives me wrong values?

I got this function in my code:

-(void)printAngle
{
    int width = p2_t.x-cp1_t.x;
    int height = p2_t.y-cp1_t.y;
    if (width != 0) {
        CCLOG(@"%i * %i", width, height);
        CCLOG(@"%f", (float)atan(height/width)*(180/M_PI));
    }
}

Heres a snippet from the output:

2011-12-06 20:46:52.074 x[12392:c503] 24 * 13
2011-12-06 20:46:52.074 x[12392:c503] 0.000000
2011-12-06 20:46:52.108 x[12392:c503] 25 * 15
2011-12-06 20:46:52.108 x[12392:c503] 0.000000

That means that arctan(13/24) in degrees is 0. Which is not correct. So why am i getting 0? Is it something with types im doing wrong?

It gets some angles correct:

2011-12-06 20:51:11.956 x[12436:c503] 12 * 129
2011-12-06 20:51:11.957 x[12436:c503] 84.289404
2011-12-06 20:51:11.989 x[12436:c503] 10 * 132
2011-12-06 20:51:11.990 x[12436:c503] 85.601292

Upvotes: 3

Views: 2220

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185663

You're using integer math and expecting a floating point result. This won't work. Change width and height to be float instead and you should get the expected results.

In case you are unaware, in C, doing division with integers produces an integral result. So evaluating 13/24 is producing 0 instead of 0.541666667. By either casting one of the variables to (float) before performing the division, or just using float to begin with, you'll get the floating-point number you expect.

Upvotes: 12

Related Questions