gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:26 24 4
gpt4 key购买 nike

我正在调试我的项目,但找不到错误。最后我找到了它。看看代码。你认为一切都很好,结果会是“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com