因为给出了错误的值
cos giving out the wrong value
#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 )
returns 也是正确的值。
给出了什么?
编辑:
代码有错误但与问题无关。在 y = x * s + y * c;
上,x 应该引用顶部声明的值,但由于前面的等式覆盖了该值,所以最后的 y
是错误的。
感谢指数的澄清。我有点糊涂了。
cos(90)
(度)近似为零,如 0.0
。担心取回 e-17
与 e-9
的数字没有意义,它们基本上都是零。
结果 实际上 的接近程度取决于它们如何表示 pi
、90.0
、180.0
以及cos
math.h
中的函数。
It should be something near to -3.2051033e-9 but I end up with 6.12303e-017.
我不知道你为什么这么想 "should be -3.2051033e-9" 因为 cos(90º)
是零,而 -0.0000000032051033
完全超出了你计算的误差范围,
您得到的值 0.0000000000000000612303
是 零,因此 正确,在误差范围内你的计算。
你的代码没有错误..
在余弦函数(cos)中,return值是实数。这里有一些例子;
(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**
你也可以用 inverse cos 和 cos(6.12303e-017) 检查它,你会看到它是 90度
#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 )
returns 也是正确的值。
给出了什么?
编辑:
代码有错误但与问题无关。在 y = x * s + y * c;
上,x 应该引用顶部声明的值,但由于前面的等式覆盖了该值,所以最后的 y
是错误的。
感谢指数的澄清。我有点糊涂了。
cos(90)
(度)近似为零,如 0.0
。担心取回 e-17
与 e-9
的数字没有意义,它们基本上都是零。
结果 实际上 的接近程度取决于它们如何表示 pi
、90.0
、180.0
以及cos
math.h
中的函数。
It should be something near to -3.2051033e-9 but I end up with 6.12303e-017.
我不知道你为什么这么想 "should be -3.2051033e-9" 因为 cos(90º)
是零,而 -0.0000000032051033
完全超出了你计算的误差范围,
您得到的值 0.0000000000000000612303
是 零,因此 正确,在误差范围内你的计算。
你的代码没有错误..
在余弦函数(cos)中,return值是实数。这里有一些例子;
(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**
你也可以用 inverse cos 和 cos(6.12303e-017) 检查它,你会看到它是 90度