Float doesn't change when I add 0.1 to it

I am new to c. Therefore, when I write a small demo version of the game, I encounter a really strange problem.

void testC() { float a = 825300160; float b = a + 0.1; assert(a != b); } 

The above statement cannot be transmitted. Very strange. My environment is mac os ml. gcc 4.2.1

+6
source share
3 answers

The fractional part of a float consists of 23 bits. You need 30 bits to represent 825300160, so the less significant part of the number will be deleted. Adding .1 does not matter - you need to add about 32 for the number:

 float a = 825300160; float b = a + 31.5; assert(a != b); // No change is detected float c = a + 32; assert(a != c); // Change is detected 
+8
source

There is not enough accuracy in the float type. If you really need to distinguish 0.1 addition to a number of size 825300160, use double.

+6
source

As this site shows, both a and b will be represented as

 0 10011100 10001001100010001010011 

in the IEEE standard for floats, where the first bit is a sign, the next 8 is a measure, and the remaining 23 is a mantissa. There is simply not enough space in these 23 bits to represent the difference, because the figure is so large.

+1
source

All Articles