C/C++提供sin(a)
,cos(a)
,tan(a)
等需要与弧度单位而非度一个参数函数。 double DegreesToRadians(d)
执行的转换是关闭,但转换结果是四舍五入的近似值。此外,机器M_PI
已接近,但与数学非理性π
的值不同。
OP与180
代码传递给DegreesToRadians(d)
然后sin()/cos()
给出不同比预期由于四舍五入的double()
有限精度和用于PI
可能弱值的结果。
一个改进是在调用trig函数之前在度中执行自变量减少。下面将角度先减小到-45°到45°范围,然后再调用sin()
。这将确保sind(90.0*N) --> -1.0, 0.0, 1.0
的N
的较大值。 。注:sind(360.0*N +/- 30.0)
可能不完全等于+/-0.5
。需要一些额外的考虑。
#include <math.h>
#include <stdio.h>
static double d2r(double d) {
return (d/180.0) * ((double) M_PI);
}
double sind(double x) {
if (!isfinite(x)) {
return sin(x);
}
if (x < 0.0) {
return -sind(-x);
}
int quo;
double x90 = remquo(fabs(x), 90.0, &quo);
switch (quo % 4) {
case 0:
// Use * 1.0 to avoid -0.0
return sin(d2r(x90)* 1.0);
case 1:
return cos(d2r(x90));
case 2:
return sin(d2r(-x90) * 1.0);
case 3:
return -cos(d2r(x90));
}
return 0.0;
}
int main(void) {
int i;
for (i = -360; i <= 360; i += 15) {
printf("sin() of %.1f degrees is % .*e\n", 1.0 * i, DBL_DECIMAL_DIG - 1,
sin(d2r(i)));
printf("sind() of %.1f degrees is % .*e\n", 1.0 * i, DBL_DECIMAL_DIG - 1,
sind(i));
}
return 0;
}
输出
sin() of -360.0 degrees is 2.4492935982947064e-16
sind() of -360.0 degrees is -0.0000000000000000e+00 // Exact
sin() of -345.0 degrees is 2.5881904510252068e-01 // 76-68 = 8 away
// 2.5881904510252076e-01
sind() of -345.0 degrees is 2.5881904510252074e-01 // 76-74 = 2 away
sin() of -330.0 degrees is 5.0000000000000044e-01 // 44 away
// 0.5 5.0000000000000000e-01
sind() of -330.0 degrees is 4.9999999999999994e-01 // 6 away
sin() of -315.0 degrees is 7.0710678118654768e-01 // 68-52 = 16 away
// square root 0.5 --> 7.0710678118654752e-01
sind() of -315.0 degrees is 7.0710678118654746e-01 // 52-46 = 6 away
sin() of -300.0 degrees is 8.6602540378443860e-01
sind() of -300.0 degrees is 8.6602540378443871e-01
sin() of -285.0 degrees is 9.6592582628906842e-01
sind() of -285.0 degrees is 9.6592582628906831e-01
sin() of -270.0 degrees is 1.0000000000000000e+00 // Exact
sind() of -270.0 degrees is 1.0000000000000000e+00 // Exact
...
'我知道它应该是:sin 0.0547,cos 0.99'更像“0和-1”。 – deviantfan
PI的正弦为0,余弦为-1。这听起来像是你得到的。 –
“0.0547的余弦和0.99的余弦”Huh?它应该完全是0和-1。你的代码正确派生了(最多舍入错误)。 –