Incorrect visual C float / double conversion?

In Visual C ++, I wrote the following example in a C ++ program:

float f1 = 42.48f;
double d1 = 42.48;
double d2 = f1;

I compiled the program using Visual Studio 2005. In the debugger, I see the following values:

f1  42.480000   float
d1  42.479999999999997  double
d2  42.479999542236328  double

d1 is ok in my knowledge, but d2 is wrong.

The problem also occurs when / fp = exact, as with / fp = strict, since / fp = fast.

What is the problem? Any hint on how to avoid this problem? This leads to serious numerical problems.

+3
source share
3 answers

V++ - - , . . IEEE-754.

, float double , double float , . , , , . , round float , .

+4

f1 d2 . 42.480000, 42.479999542236328, , . , . , .

d1 4.48, , d1 4.48, f1 d2 4.48. d2? f1 "", " " 4.48, , , " ".

, . , d1 d2 , , , , , d1 == d2 :

fabs(d1 - d2) <= (d2 * FLT_EPSILON)

, , , . , , - d2 , , NaN, , .

, d2 , float / .

+3

, .

- , , 42.479999999999997 42.48, double.

: http://docs.sun.com/source/806-3568/ncg_goldberg.html

, . , .

+2

Source: https://habr.com/ru/post/1740122/


All Articles