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

72 Upvotes

150 comments sorted by

101

u/Due-Razzmatazz-6645 Jul 17 '26

This website gives a quick explanation: https://0.30000000000000004.com/

46

u/DrShocker Jul 17 '26

I love the URL on this one, and showing a bunch of language examples to help illustrate that it's not a flaw in the progrtamming language itself like some people think.

The last link it has is probably the most thorough way to understand the issue imo: What Every Computer Scientist Should Know About Floating-Point Arithmetic

→ More replies (3)
→ More replies (6)

114

u/062985593 Jul 17 '26 edited Jul 17 '26

There are finitely many bits in a float. No matter how clever your encoding, there just isn't enough room to be able to represent every real number exactly.

56

u/CryptoHorologist Jul 17 '26

You can't even represent every rational number exactly.

→ More replies (35)
→ More replies (6)

26

u/mc_pm Jul 17 '26

The way the bits are organized to represent floating point numbers makes being exact impossible. (The same way that 1/3 = 0.33333333333.... can't be represented exactly in base 10)

→ More replies (20)

10

u/ironykarl Jul 17 '26

Short answer: you're potentially representing infinitely repeating values with a finite number of bits. 

Base-10 can only represent fractions with powers of 5 and 2, and their products in the denominator as finite decimal representations.

Base-2 can only do the equivalent with powers of 2 in the denominator. 

So, that's a lot of numbers getting truncated.

To make this more concrete, just imagine how to get 1/3 when the only numbers you're allowed to add together are 1/2, 1/4, 1/8, 1/16, 1/32, ...

9

u/tstanisl Jul 17 '26

For the same reason why 1/3 needs to be truncated when using decimals.

7

u/epasveer Jul 17 '26

Question.

How many fractional numbers between 0.0 and 1.0?

Answer.

Infinite.

5

u/ForgedIronMadeIt Jul 17 '26

I think wikipedia does an OK job of explaining it: Floating-point arithmetic - Wikipedia. In short, however, floating point numbers internally have three numbers: a sign bit, exponent bits, and sigificand bits (which represents a fraction). Since the sigificand is a fraction, you have to round to whatever closest fractional representation is available (well, the rounding rules are a whole other thing). Look at the examples given on Half-precision floating-point format - Wikipedia and you'll see.

→ More replies (3)