Sin和Cos函数返回不正确的结果

Kun*_*jal 5 math objective-c

可能重复:
将正弦180的值设为1.22465e-16

我正在计算圆周上的一个点.我有半径和圆的中心点.在这里你会说,大不了,有一个直接的公式相同.是的,角度是rad

x = x + r*sin(angle)
y = y + r*cos(angle)
Run Code Online (Sandbox Code Playgroud)

好吧,现在这里的问题是即使我以弧度传递角度.然而,我没有得到下面提到的角度的正确答案

for 90 degree (rads = 1.5708) i get y axis = -4.3774e-08
for 180 degree (rads = 3.14159) i get x axis = -8.74228e-08
for 270 degree (rads = 4.71239) i get y axis = 1.19249e-08
for 360 degree (rads = 6.28319) i get x asix = 1.74846e-07
Run Code Online (Sandbox Code Playgroud)

我正在将Degree转换为Radians

return degrees * M_PI / 180;
Run Code Online (Sandbox Code Playgroud)

我不确定为什么会这样.一定有严重的错误.

这是用于转换的代码

float angle = DegreesToRadians(90);

float x = sin(angle);
float y = cos(angle);
Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?

Mar*_*n R 8

M_PI 在"math.h"中定义为

#define M_PI        3.14159265358979323846264338327950288
Run Code Online (Sandbox Code Playgroud)

这只是大约(无理的)数字Pi.因此

cos(M_PI/2), sin(M_PI), cos(3*M_PI/2), sin(2*M_PI)
Run Code Online (Sandbox Code Playgroud)

只有大约为零.Pi不能完全表示为floatdouble.

从你的输出我假设你使用float.由于的显著数字的数量float大约是7,和斜率(一阶导数)sin(),并cos()在该点上+/- 1,我要说的是,结果是,你可以期望的那样好.使用double会产生更好的结果,但不会完全为零.

所以没有什么严重的错误,你只是不能指望浮点计算的结果是准确的.