c++ - Visual C++ math.h 错误

标签 c++ floating-point math.h

我正在调试我的项目,但找不到错误。最后我找到了它。看看代码。你认为一切都很好,结果会是“OK!OK!OK!”,不是吗?现在用 VC 编译它(我试过 vs2005 和 vs2008)。

#include <math.h>
#include <stdio.h>


int main () {
    for ( double x = 90100.0; x<90120.0; x+=1 )
    {
        if ( cos(x) == cos(x) )
            printf ("x==%f  OK!\n", x);
        else
            printf ("x==%f  FAIL!\n", x);
    }

    getchar();
    return 0; 
}

魔术双常数是 90112.0。当 x < 90112.0 时一切正常,当 x > 90112.0 时——不行!你可以把 c​​os 换成 sin。

有什么想法吗?不要忘记 sin 和 cos 是周期性的。

最佳答案

可能是这样的:http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18

I know it's hard to accept, but floating point arithmetic simply does not work like most people expect. Worse, some of the differences are dependent on the details of your particular computer's floating point hardware and/or the optimization settings you use on your particular compiler. You might not like that, but it's the way it is. The only way to "get it" is to set aside your assumptions about how things ought to behave and accept things as they actually do behave...

(with emphasis on the word "often"; the behavior depends on your hardware, compiler, etc.): floating point calculations and comparisons are often performed by special hardware that often contain special registers, and those registers often have more bits than a double. That means that intermediate floating point computations often have more bits than sizeof(double), and when a floating point value is written to RAM, it often gets truncated, often losing some bits of precision...

just remember this: floating point comparisons are tricky and subtle and fraught with danger. Be careful. The way floating point actually works is different from the way most programmers tend to think it ought to work. If you intend to use floating point, you need to learn how it actually works...

关于c++ - Visual C++ math.h 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1363665/

相关文章:

c++ - c++ string::compare() fn 的意外行为

c++ - 继承 react

c++ - 有序列表的最佳数据结构(性能)

c++ - 为什么不允许指针的运算符重载工作?

c++ - 与 `std::chrono` 类型相比,为什么使用 `float` 进行时差测量会给出更多有效数字的 `double` 类型?

php - 为什么 PHP 似乎无法正确评估此条件?

mysql - 检查 MySQL Float 字段的相等性

c++ - 使用 cmath 时禁用 math.h 废话

c - -lm 不工作,除非它在命令的末尾

c - 为什么必须链接C 中的数学库?