cos 给出错误的值

cos giving out the wrong value

本文关键字:错误 出错 cos      更新时间:2023-10-16
#include <iostream>
#include <math.h>
#include "boost/math/constants/constants.hpp"
const double pi = boost::math::constants::pi<double>();
int main() {
    double x = 2;
    double y = 1;
    double angle = 90; //in degrees
    double rad { angle * pi / 180 }; //converting to rads
    std::cout << "rad: " << rad << std::endl; //1.5708 - OK
    double c = cos( rad );
    std::cout << "cos(rad): " << c << std::endl; //6.12303e-017 - Huh? Should be ~ -3.2051033e-9
    double s = sin( rad );
    std::cout << "sin(rad): " << s << std::endl; //1 - OK
    x = x * c - y * s;
    y = x * s + y * c;
    std::cout << "(" << x << "," << y << ")" << std::endl;
    return 0;
}

所以这很奇怪,我试图做一个旋转,但cos给了我错误的值。它应该是接近-3.2051033e-9的东西,但我最终得到了6.12303e-017.我已经将我的角度转换为弧度,它检查出来了。 sin( rad )也返回正确的值。什么给?

编辑:代码有错误,但与问题无关。在y = x * s + y * c;上,x 应该引用顶部声明的值,但由于前面的等式覆盖了该值,因此末尾的y将是错误的。

感谢您对指数的澄清。我有点困惑。

cos(90)(

度(大约为零,如0.0 .担心得到一个e-17e-9的数字是没有意义的,它们基本上都是零。

结果的实际接近程度取决于它们如何表示pi90.0180.0,以及cos函数在math.h中的实现。

它应该接近 -3.2051033e-9,但我最终得到 6.12303e-017。

我不知道你为什么认为它"应该是-3.2051033e-9",因为cos(90º)是零,而且-0.0000000032051033远远超出了你计算的误差范围,

您得到的值0.0000000000000000612303,因此计算的误差范围内是正确的。

您的代码中没有错误。

在 cos 函数 (cos( 中,返回值是实数。这里有一些例子;

(cos -1) returns 0.540302
(cos 0.0) returns 1.0
(cos (* pi 0.5)) returns 6.12303e-017 which is practically equal to **0**
你也可以用cos

(6.12303e-017(反cos检查它,你会看到它是90

相关文章: