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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…