Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the addition of two float numbers is incorrect in C?

I have a problem with the addition of two float numbers. Code below:

float a = 30000.0f;
float b = 4499722832.0f;

printf("%f\n", a+b);

Why the output result is 450002816.000000? (The correct one should be 450002832.)

like image 516
Hengfeng Li Avatar asked Dec 16 '22 09:12

Hengfeng Li


1 Answers

Float are not represented exactly in C - see http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers and http://en.wikipedia.org/wiki/Single_precision, so calculations with float can only give an approximate result.

This is especially apparent for larger values, since the possible difference can be represented as a percentage of the value. In case of adding/subtracting two values, you get the worse precision of both (and of the result).

like image 123
Ofir Avatar answered Feb 24 '23 19:02

Ofir