Question

I am just curious about something.

I have the following code:

if (d1 == 2.3)
    cout << "2.3 is my value\n";
if (d1 == 2.2999999999999998)
    cout << "2.2999999999999998 is my value\n";

VS2013 c++11 screenshots

enter image description here

enter image description here

And it goes into both ifs. I know the precision for double is with 15decimals, so I will have to use a more appropiated type for this kind of data.

Could anybody link me a detailed reference? And also a "way" to storage just "2.3" or a data with more precision than 2.2999999999999998? (long double throws me complie error

Error   1   error C2398: Element '1': conversion from 'long double' to 'const 
std::complex<double>::_Ty &' requires a narrowing conversion...

Thanks.

Edit: Added complex

enter image description here

Was it helpful?

Solution

This is the nature of floating point - there is no way to represent 2.3 exactly as a floating point binary.

The "2.3" in your first test can't be represented exactly in binary, so it's stored as the closest possible double, which is 2.2999999999999998.
In other words, both ifs perform the same comparison.

OTHER TIPS

maybe reading this might help you: http://www.cplusplus.com/forum/beginner/34088/

As far as i can tell there seems to be no real reference except with the compiler you use. Try http://msdn.microsoft.com I suppose 2.2999999999999998 is beeing rounded to the closest double value which would be 2.3, or the other way around as the other answerer suggests. if you want long double literals, you need to add a L at the end of your literal:

//checks for equalty to a double
if (d1 == 2.2999999999999998)
    cout << d1 << " == 2.2999999999999998 ?\n";
//checks for equalty to a long double
if (d1 == 2.2999999999999998L)
    cout << d1 << " == 2.2999999999999998L ?\n";

btw: why dont you use

complex<long double>

?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top