cos 给出错误的值
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 )
也返回正确的值。什么给?
编辑:代码有错误,但与问题无关。在y = x * s + y * c;
上,x 应该引用顶部声明的值,但由于前面的等式覆盖了该值,因此末尾的y
将是错误的。
感谢您对指数的澄清。我有点困惑。
cos(90)
(度(大约为零,如0.0
.担心得到一个e-17
与e-9
的数字是没有意义的,它们基本上都是零。
结果的实际接近程度取决于它们如何表示pi
、90.0
、180.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度
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 为 freebsd 11 编译 gcc4.8.5 时出错: 错误: 未知类型名称 'choke'
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 我同时使用了莱布尼茨和瓦利斯公式来估算π但输出数字错误,我不知道我哪里出错了
- 显示错误消息框时出错.我该如何显示它
- 使用 swig 时出错:输入 (1) 中的语法错误
- 编译类 C++ 中的线程时出错(错误 xthread)
- 在 Visual Studio 2015 社区中消除错误时出错