Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

ios4 - Value of sine 180 is coming out as 1.22465e-16

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just to be clear, your program is giving you the correct answer. That is to say, it is doing exactly what you told it to do in your code.

180*M_PI is correctly rounded (per IEEE-754), and gives the value:

565.4866776461627750904881395399570465087890625

dividing that by 180 is also correctly rounded, and gives the result:

3.141592653589793115997963468544185161590576171875

which is not exactly the mathematical value of π. In fact, it is:

π - 0.0000000000000001224646799147...

the first order term of the Taylor series for sin(x) around π is (π-x), so sin(π - x) is, for small x, nearly exactly -x. In fact, the result that you're getting is the correctly rounded result. The library couldn't possibly deliver a more accurate answer.

As Ben Voigt suggested, if this is actually a problem for you, you can work around it by reducing the argument into the range [-90, 90) before converting from degrees to radians. An even better suggestion is njuffa's to use a sinpi function that will do this work for you. iOS does not have such a function, but it does have vvsinpi, which implements sin(π*x) for vectors, and can be made to do what you want:

double result;
int vectorLength = 1;
vvsinpi(&result, &operand, &vectorLength);

Please also file a bug requesting that sinpi be added to the math library as an extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...