Why are doubles added incorrectly in a specific Visual Studio 2008 project?

让人想犯罪 __ 提交于 2020-01-10 19:55:28

问题


Trying to port java code to C++ I've stumbled over some weird behaviour. I can't get double addition to work (even though compiler option /fp:strict which means "correct" floating point math is set in Visual Studio 2008).

double a = 0.4;
/* a: 0.40000000000000002, correct */

double b = 0.0 + 0.4;
/* b: 0.40000000596046448, incorrect
(0 + 0.4 is the same). It's not even close to correct. */

double c = 0;  
float f = 0.4f;  
c += f;
/* c: 0.40000000596046448 too */

In a different test project I set up it works fine (/fp:strict behaves according to IEEE754).

Using Visual Studio 2008 (standard) with No optimization and FP: strict.

Any ideas? Is it really truncating to floats? This project really needs same behaviour on both java and C++ side. I got all values by reading from debug window in VC++.

Solution: _fpreset(); // Barry Kelly's idea solved it. A library was setting the FP precision to low.


回答1:


The only thing I can think of is perhaps you are linking against a library or DLL which has modified the CPU precision via the control word.

Have you tried calling _fpreset() from float.h before the problematic computation?




回答2:


Yes, it's certainly truncating to floats. I get the same value printing float f = 0.4 as you do in the "inaccurate" case. Try:

double b = 0.0 + (double) 0.4;

The question then is why it's truncating to floats. There's no excuse in the standard for treating 0.0 + 0.4 as a single-precision expression, since floating point literals are double-precision unless they have a suffix to say otherwise.

So something must be interfering with your settings, but I have no idea what.



来源:https://stackoverflow.com/questions/1154221/why-are-doubles-added-incorrectly-in-a-specific-visual-studio-2008-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!