正弦和余弦函数返回错误结果 [英] Sin and Cos Functions returning incorrect results

查看:86
本文介绍了正弦和余弦函数返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
获得正弦180的值为1.22465e-16

Possible Duplicate:
getting value of sine 180 as 1.22465e-16

我正在计算圆的圆周上的一个点.我有圆的半径和中心点. 在这里,您会说,没什么大不了的,有一个直接的公式可以解决这个问题. 是的,角度在弧度内

I am calculating a point on the circumference of the circle. I have the radius and the center point of the circle. Here you would say, big deal, there is a direct formula for the same. Yeah, angle is in rad

x = x + r*sin(angle)
y = y + r*cos(angle)

好的,现在的问题是即使我以弧度传递角度.但是对于以下提到的角度,我没有得到正确的答案

Okay, now the problem here is even though i am passing angle in radians. Yet I dont get correct answers for the below mentioned angle

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

我正在使用

return degrees * M_PI / 180;

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

I am not sure as to why this is happening. There must be something seriously wrong.

这里是用于转换的代码

float angle = DegreesToRadians(90);

float x = sin(angle);
float y = cos(angle);

有人可以帮我吗?

推荐答案

M_PI在"math.h"中定义为

M_PI is defined in "math.h" as

#define M_PI        3.14159265358979323846264338327950288

仅(不合理)数字Pi.因此

which is only approximately the (irrational) number Pi. Therefore

cos(M_PI/2), sin(M_PI), cos(3*M_PI/2), sin(2*M_PI)

为零. Pi不能完全表示为floatdouble.

are only approximately zero. Pi cannot be represented exactly as a float or double.

从您的输出中,我假设您使用了float. 由于float的有效数字位数约为7,并且sin()cos()在该点的斜率(一阶导数)为+/- 1,因此我想说结果是尽可能的好预计.使用double会得到更好的结果,但不完全是零.

From your output I assume that you used float. Since the number of significant digits of a float is about 7, and the slope (first derivative) of sin() and cos() at that points is +/- 1, I would say that the results are as good as you can expect. Working with double would give better results, but not exactly zero.

因此,没有什么严重错误,您只是不能期望浮点计算的结果是准确的.

So there is nothing seriously wrong, you just can't expect the result of a floating point computation to be exact.

这篇关于正弦和余弦函数返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆