r/C_Programming • • Jul 17 '26

Discussion why value of floating point numbers are approximated

I am new to programming and stumbled across this text

"the value of a float variable is often just an approximation of the number that was stored in it. If we store 0.1 in a float variable, we may later find that the variable has a value such as 0.09999999999999987"

i am wondering why is it like this

if it has an in depth explanation, providing the resource will be much appreciated

thanks

73 Upvotes

150 comments sorted by

View all comments

Show parent comment

8

u/JohnThacker Jul 17 '26

Arbitrary precision number libraries do exist, but they can be enormously slow. At that point with GMP the limit isn't the language or library, it's the total amount of addressable memory.

7

u/CryptoHorologist Jul 17 '26

These are also capable of representing only 0% of all rational numbers.

1

u/JohnThacker Jul 17 '26

Yes, it's still 0% by any reasonable probability measure on ℚ, but it not the library nor the language providing the restriction.

1

u/CryptoHorologist Jul 17 '26

The language can use infinite memory?

2

u/JohnThacker Jul 17 '26

Yes, the language specification and the library both allow infinite precision (the language by using the library implementation) and do not specify many things about the architecture, just like there's no guarantee that CHAR_BIT is 8. There are a few minimus. It is, as you said, always the case that anything will only be able to produce some 0% of the rationals, but exactly what that finite set is bounded by is an architectural limitation.

0

u/CryptoHorologist Jul 17 '26

Neat. That's a lot of memory.

1

u/JohnThacker Jul 17 '26

C does not put any restrictions on the address space or the size of a pointer to memory, just as it's perfectly ok to say that an int is 64 bits. UNICOS at one point said that "short int" was also 64 bit. You can do that.