Floating Point Inaccuracy

I fully understand the problems associated with floating points, but I saw a very interesting behavior that I can not explain.

float x = 1028.25478;
long int y = 102825478;
float z = y/(float)100000.0;
printf("x = %f ", x);
printf("z = %f",z);

Conclusion:

x = 1028.254761 z = 1028.254780

Now, if the floating numbers could not represent this particular random value (1028.25478) when I assigned this to the variable x. Why is this not the same with the variable z?

PS I use pellesC IDE to check the code (C11 compiler).

+4
source share
3 answers

, , ; printf. , .

GCC 7.2.0 :

-Wall -Werror -ffast-math -m32 -funsafe-math-optimizations -fexcess-precision=fast -O3

x = 1028.254761 z = 1028.254800

.

-fexcess-precision=fast :

-fexcess-precision=style

           ,             , IEEE             . -fexcess-precision=fast            ; ,             , ,             ,            , , .             C, -fexcess-precision=standard ,             , ISO C99;             , ,             ( -ffloat-store            ). [-fexcess-precision=standard] C,             , -std=c99. -ffast-math            -fexcess-precision=fast , ,             .

C11

+5

IEEE754, .

1028.25478 1028.2547607421875. x.

y / (float)100000.0; y float C . float 102825478 - 102825480. IEEE754 , 1028.2547607421875 ( z): 1028.25480.

, . , ; , , IEEE754.

+2

, z double y/(float)100000.0 y/100000.0.

float x = 1028.25478;
long int y = 102825478;
double z = y/100000.0;

// output
x = 1028.254761 z = 1028.254780

FLT_EVAL_METHOD. .

#include <float.h>
#include <stdio.h>
printf("FLT_EVAL_METHOD %d\n", FLT_EVAL_METHOD);

cast... , , , , . , FLT_EVAL_METHOD.

-1 ; 0 ;
1 ... float double double, long double ... long double ;
2 ... long double.

, , z float z = y/(float)100000.0; .


@Antti Haapala, , .

+2

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


All Articles