Floating point inaccuracies in c

I know that floating point values ​​are limited in numbers that can be expressed exactly, and I found many sites that describe why this happens. But I did not find any information on how to solve this problem effectively. But I'm sure NASA is out of order with 0.2 / 0.1 = 0.199999. Example:

#include <stdio.h>
#include <float.h> 
#include <math.h>

int main(void)
{
    float number = 4.20;
    float denominator = 0.25;

    printf("number = %f\n", number);
    printf("denominator = %f\n", denominator);
    printf("quotient as a float = %f should be 16.8\n", number/denominator);
    printf("the remainder of 4.20 / 0.25 = %f\n", number - ((int) number/denominator)*denominator);
    printf("now if i divide 0.20000 by 0.1 i get %f not 2\n", ( number - ((int) number/denominator)*denominator)/0.1);
}

output:

number = 4.200000
denominator = 0.250000
quotient as a float = 16.799999 should be 16.8
the remainder of 4.20 / 0.25 = 0.200000
now if i divide 0.20000 by 0.1 i get 1.999998 not 2

So, how do I do arithmetic with floats (either decimal or double) and get accurate results. I hope I have not just missed something beyond the obvious. Any help would be awesome! Thank.

+4
source share
3 answers

, float , . ( a.k.a.), GNU MP Bignum. . . . .

(float, double ..), , (, ==). - , , .

+3

, . , :

  • float double. double , ; float . , , , double.

  • , . C , . , , , , , , int long int, , .

  • , , . "" , . , , , .

  • 16.8 16.799999. , , . , , , %.1f, printf . ( , , .)

  • , 0,1 ( , 1/3 ). , , "" , .

  • (MP "bignum" ), , () , , , . , , , .

  • . , , 1/3 (1, 3), , 0.333333333.

" ", , . , , - , : https://www.eskimo.com/~scs/cclass/handouts/sciprog.html#precision. , .

+1

, .

, . , , , , . .

, , . , . " " "" , , . , , , . , .

If you are doing math, and not processing data, just do not use C or C ++. Use a symbolic algebra package like Maple, which stores values ​​like sqrt (2) as an expression, not a floating point number, so sqrt (2) * sqrt (2) will always give exactly 2, not a very close to 2.

-1
source

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


All Articles