Reputation: 3560
While I write code like below
NSLog(@"%f",acos(cos(1)));
it returns 1
as result but if I tried to obtain result from degree instead of radian then facing problem as below
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
NSLog(@"%f",acos(cos(DEGREES_TO_RADIANS(1))));
then it returns 0.017453
instead of 1
.
If I write like below
NSLog(@"%f",acos(cos(DEGREES_TO_RADIANS(1)))*180/M_PI);
then I'm getting proper 1
as result.
But if I'll write like below
NSString *a1 = [NSString stringWithFormat:@"%f",(cos(DEGREES_TO_RADIANS(1)))];
NSString *a2 = [NSString stringWithFormat:@"%f",(acos([a1 doubleValue])*180/M_PI)];
NSLog(@"%f",[a2 doubleValue]);
then I'm getting 0.998999
as result.
Then where the problem is?
Please help me
Upvotes: 1
Views: 1260
Reputation: 131418
Arc Cosine is the inverse of cosine.
Cosine takes an angle as input, and returns a value ranging from -1 to 1. Arc Cosine (acos) takes a value from -1 to 1 as input, and returns an angle.
The input to acos() is not an angle, so you should not try to convert it between degrees and radians. The result is an angle. That's what you convert.
So you would write
x = RADIANS_TO_DEGREES(acos(1)).
That would give you the angle at which the cosine is 1, expressed in degrees. (The value of acos(1) is 0, which is the same in degrees or radians.)
Better to use acos(0) as a test value. The cosine function = 0 at pi/2 (or 90 degrees.)
So
acos(0) == pi/2. (~1.5707)
RADIANS_TO_DEGREES(acos(0)) == 90.
I see now that in your question you were taking acos(cos(DEGREES_TO_RADIANS(1)), which is correct.
However, you still need to convert the result of acos() to degrees if you want your answer in degrees, as described above. (And Kevin's answer is also correct. My mistake)
Note that cos(1) is a little strange, in both degrees and radians. That isn't going to give an even answer in either.
cos(0) = 1, cos(pi) = -1, cos(2pi) = 1. (or in degrees) cos(180) = -1, and cos(360) = 1)
cos(1) in degrees is going to be an strange decimal value, and so will cos(1) in radians.
Upvotes: 1
Reputation: 76194
0.017453 is about how many radians are in one degree.
If you want your logging line to output 1
, you'll need to convert back to degrees.
#define RADIANS_TO_DEGREES(angle) ((angle) * 180.0 / M_PI)
NSLog(@"%f", RADIANS_TO_DEGREES(acos(cos(DEGREES_TO_RADIANS(1)))));
Note that you may get a result like 0.9999, though, due to the limited accuracy of trigonometric functions, and of floats in general.
Upvotes: 5