I want to implement a Sine and Cosine calculator in ios4:
if([operation isEqual:@"sin"]){
operand = (operand*M_PI/180.0);
operand=sin(operand);
}
The code gives me correct answer for values from 0 through 90.
When I give value of 180, I get 1.22465e-16
as an answer. I expect zero.
Where does this small difference come from?
This is caused by the inability of a binary number system to exactly represent PI.
One possible solution would be to use the symmetry of sin:
sindeg(x) = sindeg(180 - x)
(or alternatively):
sin(x) = sin(M_PI - x)
Transforming the angle into the range (-pi/2 : pi/2) reduces the error of the approximation.
Basically:
if([operation isEqual:@"sin"]){
operand = fmod(operand, 360);
if (operand > 270) operand -= 360;
else if (operand > 90) operand = 180 - operand;
operand=sin(operand*M_PI/180.0);
}