r/C_Programming • u/Altruistic-Tie1943 • 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
101
u/Due-Razzmatazz-6645 Jul 17 '26 •
This website gives a quick explanation: https://0.30000000000000004.com/
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.
31
u/ThatIsATastyBurger12 Jul 17 '26
https://en.wikipedia.org/wiki/IEEE_754
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)
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.
4
u/Alduish Jul 17 '26
It's basically the same problem as 1/3 for us but for a different base, we can write any whole number over any product of powers of two and powers of 5 (because we're using base 10) but for computers which use base 2 it's only exact for whole numbers (with a limit on said whole number because infinity can't really exist for computers) over powers of 2 which 0.1 isn't
3
u/WilliamMButtlickerIV Jul 17 '26
It's because you are trying to represent a fractional decimal in binary. It's simply not mathematically possible. Binary can only represent an approximation.
3
u/Independent_Art_6676 Jul 17 '26
while floats are pretty poor, double can store +- 2^53 exactly for int values or 15 digits of anything exactly. Its good enough for most purposes, and scientific software can do the math another way when it counts. You can access larger float values in the FPU directly; I do not know the current value but it used to be 80 bits back in early pentium days and is probably bigger now. If that isn't enough, you can use your own types to store high precision at the cost of calculation speed: note how we have jillions of digits of numbers like pi and e and so on should we ever need that much precision. But the standard advice is just to avoid float and stick to doubles, unless you have a compelling reason to use the smaller type (memory usage, low precision information, whatever).
2
u/mrflash818 Jul 17 '26
Perhaps this might help:
https://en.wikipedia.org/wiki/Floating-point_arithmetic
2
u/Zerf2k2 Jul 17 '26
You can toy around with numbers and calculate the error on this website: https://www.h-schmidt.net/FloatConverter/IEEE754.html
(There are more like it, if you search for it)
2
u/CowBoyDanIndie Jul 17 '26
Floating point types use fractions of 2, so .5 .25 .125 etc (and any sums of them) can be represented exactly in some cases, but any decimal that cannot be expressed as fractions of power of 2 cannot be. Just like you cannot write the exact decimal for 1/3
2
u/Educational-Paper-75 Jul 17 '26
Floating point numbers are represented in binary by a finite number of bits and can therefore only represent a finite amount of real numbers exactly.
2
u/SmokeMuch7356 Jul 17 '26
You can't squeeze an infinite number of values into a finite number of bits.
This isn't a problem with integers because there are no other integer values between
0and1or3and4or12345678and12345679. N bits can represent 2N integers with no missing values.However, there are an infinite number of real values between
0.0and1.0. There are an infinite number of real values between0.0and0.1, and there are an infinite number of real values between0.0and0.00001. N bits can represent 2N real values, but that's an infinitesimally small subset of the real values in the range from 0 to 2N-1 .It's like the odometer on your car can't represent anything between
100000.0and100000.1; it can't show you that you're halfway between those values, or one quarter of the way, or three quarters of the way, etc., because you only have that one digit after the..The only real values that can be represented exactly in floating-point format are values whose significands are sums of powers of 2 in 23 bits (for single precision float) or 52 bits (for double precision float).
Just like
1/3cannot be represented in a finite number of digits (0.33333333...),1/10cannot be represented in a finite number of bits (0.000110011001100...).For all the gory details:
2
u/Snezzy_9245 Jul 17 '26
Years ago I had this argument with PhD guys who should have known better. I'd tell them that the computer provided only a representation of an approximation to their desired number, and thus their proposed computer program was doomed to fail. I was mostly ignored, or received complaints that I should fix the computer. Hint: Do not test floats for equality.
2
u/polymeric Jul 17 '26
Other posters in this thread have motivated how floating point numbers are generally represented and stored in a computer.
You could develop some insights into this problem by practicing some base-10 to base-2 number conversions.
A conversion from the exact decimal number 0d0.1 yields an exact binary number with repeating digits 0b0.00011001100...
Which if approximated by rounding to some finite binary place value, will probably convert back into the exact decimal number 0d0.09999999999999987 (trusting that your source took the number after it had been cycled through an IEEE 754 double).
2
u/Quiet-Arm-641 Jul 18 '26
https://www.cs.tufts.edu/cs/40/docs/WhatEveryComputerScientistShouldKnowAboutFloatingPointArithmetic.pdf
1
u/ermezzz Jul 17 '26
okay so i'm going to give you a really basic summary but you can look up floating point precision or IEEE 754 if you reallt want details.
Lets say youre trying to store the fraction 1/3 in a decimal system. as we all know, that comes out to 0,3333.... repeating. If you wanted to store this number, you would eventually need to stop writing down 3s, theres a finite amount of space but infinite 3's to write. Kinda the same thing going on. Fractions like 3/10 for example when written in binary have an infinite number of digits to the right of the decimal point. That's why at some point you need to approximate them.
1
u/dmills_00 Jul 17 '26
IEEE754 single precision floating point is a 25 bit signed value (at least most of the time there is an implicit 1) with an 8 bit offset binary scale factor giving what power of two to scale the thing by.
0.1 does not have an exact binary representation, so certainally cannot be represented exactly in the 25 bits of precision that a float has.
In much the same way 1/3 does not have an exact finite decimal expansion.
For this reason floating point equalities are always a bug painting to happen, and there are actually floating point value that compare unequal to EVERY floating point value including themselves!
Floating point is useful, but like all sharp tools you need to understand the limits.
1
u/DrShocker Jul 17 '26
The fast explanation is that if you have some base (in the case of 0.1, base 10) then you can only represent in finite digits fractions that are a sum of fractions with denominators that are powers of the prime factors of the base.
to expand a bit more with examples:
(so for 10 that's 5 or 2). So you can write 0.1 because it's 1/10 or 1/(5*2), or you can write 1/5 as 0.2, or 0.15 is (3/20)
However, let's say you only want to use a certain number of digits, then you might do something like scientific notation to express more range for the same number of digits at the cost of precision. (0.2 * 10^-12) is less digits than 0.00.....2 for example.
Floating point numbers however are base 2, so while you need infinite digits to represet 1/3 in both, you you lose the ability to represent fractions that have a power of 5 in the denominator, so 0.2 or 0.1 are examples that are finite in base 10 but infinitely long in base 2. Then on top of that, because it's "floating" point, you are using fancy scientific notation style representations that fit in a specific amount of space, which means eventually you have to cut it off or round to the nearest value that fits in the space you have.
1
u/mapadofu Jul 17 '26
https://fabiensanglard.net/floating_point_visually_explained/
https://www.cs.cornell.edu/courses/cs3410/2024fa/notes/float.html
1
u/genafcvpxyr31 Jul 17 '26
Take a number of the form a/b, expressed in base c. a, b and c are all integers. a<b so we'll limit this to proper fractions.
If you perform prime factorisation on b and any of those factors is not a prime factor of c, the radix representation of a/b is non terminating. Since most fractions are of the recurring variety in base 2, you only get limited precision with float types.
0.1 in decimal can be represented as 1/10. 10 factorises to primes 2 and 5. 5 is not a factor of 2, the base used in floats and doubles etc. so in binary you get a recurring radix representation.
Floats, doubles and long doubles have to be consistent if they want to be standardised. IEEE-754 is the standard they generally conform to. For example a double guarantees 15 significant figures in decimal, you can input a non-integer number with 15 digits, convert to a double variable and when converted back into text it should be the same. This is actually guaranteed by the standard.
float.hhas these maximum values implemented as macro constants.1
u/GoblinToHobgoblin Jul 17 '26
Numbers are stored in base 2. Not all values have an exact representation in base 2
1
u/JGhostThing Jul 17 '26
First, modern computers store numbers in a binary format. This means that all stored numbers, even if they were originally in base 10, are stored in base 2.
0.1 is easily stored in base 10, so we think of this as such. Unfortunately, in base 2, this number is a repeating number (like 1/3 in base 10 being .3333333...). The difference between the number stored and 0.1 is very small, but it's still there.
1
u/ReallyEvilRob Jul 17 '26
Because numbers are stored in binary even though we use them to express values of base 10. Fractional numbers in base 10 frequently can only be approximated in binary due to the way different number bases work mathematically. Consider how some fractional numbers in our base 10 system are non-terminating, like how 1/3 is 0.3333333... Many numbers that terminate in base 10 are actually non-terminating in binary, such as 0.1. There is no way to represent these numbers in a fixed way.
1
u/Logical-Ad-57 Jul 17 '26
For a more lively, very broad view take a look at this:
https://chadnauseam.com/coding/random/calculator-app
1
u/KilroyKSmith Jul 17 '26
For the same reason that base-10 can't give a precise representation of 1/3, 1/6, 1/9, 1/11, pi, e, sqrt(2), etc.
It is possible to write a "rational number" math library that can precisely manipulate rational numbers by storing the numerator and denominator separately, and adding/subtracting/multiplying/dividing them the way we did in elementary school. It would be relatively slow, and the result that you got out would be interesting - numbers like (3581234 / 94313890) which are difficult to compare visually (is that greater than or less than (6789133 / 87356001)?). It would also not be able to deal with irrational numbers, like pi or e or sqrt(2), of which there are infinitely more than there are rational numbers, so this theoretical library would still only be of marginal use.
Instead, computer science decided to store a single floating-point number that simultaneously has a very large range (+/- 10^38 for float-32) and a reasonable number of significant digits (roughly 7 for float-32) that, for practical purposes, can approximately represent both the rational and irrational numbers, and can be operated on quickly (well, on modern hardware). If you need a bigger range or a higher precision, simple range extensions (float-64, float-128 or float-256) are defined.
Now, this number doesn't represent all possible numbers. For example, complex numbers (real + imaginary) are tremendously useful in RF engineering, but are represented and manipulated in a similar manner to the rational number library discussed above - the real and imaginary parts are stored individually, and a library written that knows how to perform basic functions on them. There is likely some computer language somewhere where complex numbers are a basic type - but I don't know of any hardware implementations that operate on them directly and quickly, though such a thing could certainly exist.
1
u/CounterSilly3999 Jul 17 '26
Approximation is performed rather by storing, not only by retrieving (formatting). Because what looks nice fraction in decimal, can't be saved using finite bits of binary encoding. And what is nice binary float encoding, can't be formatted in finite decimal fraction.
1
u/ivancea Jul 17 '26
It's stored in binary, not decimal. And there's no direct transformation between them.
For example, can you write 1/3 in decimal? No, you have to approximate it to either 0.33... o 0.34. With as many decimals as you want.
Here the same happens. You have a decimal number, that has no real representation in binary. b0.1 is 0.5, but now try writing 0.6. it's a funny exercise and you'll see the problem clearly
1
u/AndrewBorg1126 Jul 17 '26
You can represent 232 values with a 32 bit number, this quantity is finite. This is trivial combinatorics.
There are infinite real numbers.
1
u/Cerulean_IsFancyBlue Jul 17 '26
Binary could be hard for people to visualize so let’s do it metaphorically. Let’s say I told you that I wanted you to represent a large range of numbers and I was giving you six decimal digits to do it.
Unsigned integers: 0 … 999,999
Signed integers: let’s say it’s a positive number if the first digit is even and negative if odd. So 200010 is +10. Now you can represent -99,999 … 99,999
Add an exponent: digits 1-4 are Y and 5-6 is X, for y * 10^x. Now you can do as small as 0 and as large as 9999 * 10^99. That’s a much bigger range! But notice that there are some numbers you can’t do exactly.
5,555 would be stored as 5555-00. Perfect!
But 55,555 can’t be stored exactly. You would have to round to 55,550 or 55,560 and store it as 555601 or 555501.
You have traded a bigger range, for a problem with being precise. You can represent all the numbers in the range.
If you allow negative exponents, then you can do fractions as well as really large numbers. So now you can get really small or really big. And then, of course if you convert this to binary, you’re getting into our computers actually do floating point representation.
1
u/arihoenig Jul 17 '26
Every measured value is approximate on a classical computer. Possibly there are things that aren't approximate on a quantum computer.
1
u/jurniss Jul 17 '26
Let's assume you already understand the other comments explaining that we can only represent a finite #values, and the advantage of float over fixed point.
The next question might be: why not do something special to accomodate base 10, because numbers like 0.1 show up so often?
One could do that. It's possible to design something like IEEE float, but where the mantissa is binary coded decimal.
However, the hardware is binary, and BCD would waste space compared to raw binary. You use 4 bits (16 values) to represent only 10 values.
It comes down to the original design intent of floats, which is mainly scientific: integrating differential equations, statistics, optimization, and so on. In these domains one doesn't expect to see powers of 10 in the calculations any more often than powers of 2.
1
u/notFrank0 Jul 17 '26
Look up IEEE754 and try to convert 0.1 to a flotaing point manually and at the end you will end up with an infinite repeating series of 11001100.... This is similar to decimal when you do 1/3 you end up with 0.33333333....
Since there is finite amount of bits you can store this number in you will have to cut this series at some point and thus lose some precision.
1
u/P-39_Airacobra Jul 17 '26
I think “approximated” is a little misleading. More accurately, floating point numbers aren’t built to handle base-10 numbers. So when you do something like 0.1, it has to translate that decimal to the closest floating point format
1
u/Ecstatic_Student8854 Jul 17 '26
A “float” is a floating point number. It’s kind of like scientific notation of numbers: some decimal number followed by 10 to the power of some other number.
In floats we work in base 2, so the decimal number is somewhere in the range 0-1. This means we can just store the things after the dot, the leading digit is always a 1. We cannot do this with infinite precision though. Furthermore the base for the exponential part is also 2. Thus, in a 32 bit float have 23 bits of so called mantissa (the decimal number), 8 bits of the exponent, and a sign bit for negative numbers.
0.1 in base 10 is not neatly representable in base 2, just as 1/7 is not neatly representable in base 10: it’s a repeating decimal. In particular 0.1 in base 2 is 0.0 0011 0011 0011 …
So the floating point number just stores the first 23 bits of that approximation. When we then calculate what that is in base 10, it ends up being 09999990463256835938 or so.
1
u/sciencekm Jul 17 '26
Many decimal fractions simply can't map correctly in straight up binary. Think of it is the same problem as 1/3 is 0.333... in decimal.
There are ways around this - use a different encoding. For example, you can use BCD (binary coded decimal), which is used for financial data, because fractions of cents lost can become substantial after many many transactions.
1
u/detroitmatt Jul 17 '26
https://www.youtube.com/watch?v=dQhj5RGtag0
1
u/ohkendruid Jul 17 '26
Here is another angle on it: the question is wrong.
0.1 is already written in floating-point. The "point" is the dot between the 0 and the 1. It indicates the overall scale of the number you wrote down. You could also have written .01 or 01., and if you did, it would indicate a number ten times larger or smaller. So, the "floating" part means that the point can be moved around.
Computers also use floating point, but as others have discussed, they normally use base two instead of base ten.
The reason for the 0.1 losing some precision is not due to floating point exactly but because the base is getting changed. If it were left alone, or if you ran your C compiler in a mode that forced it to keep the base ten, it would stay what you wrote.
1
u/FitMatch7966 Jul 17 '26
You think in decimal and computers think in binary. Just the decimal <—> binary is approximate
1
u/mpattok Jul 17 '26
[jan Misali - how floating point works](https://youtu.be/dQhj5RGtag0?is=6KiLyDSC22JgSJdn)
[Nemean - Fast Inverse Square Root — A Quake III Algorithm](https://youtu.be/p8u_k2LIZyo?is=i9b3SI38VDkGYqxm) (an interesting application of IEEE-754)
1
u/Eisenfuss19 Jul 17 '26
Speed & Space
1
u/Afraid-Locksmith6566 Jul 17 '26
lets say you have 10 digits and 1 dot that separate decimal place. now try to express number with 11 figits, or 12 digits after decimal place. thats why
1
u/Prestigious_Boat_386 Jul 17 '26
This is kknda similar to decimal numbers actually which actually show intervals and not exact points.
If someone says a measurement is 0.1mm then that means the actual number is measured between 0.05 and 0.15.
Floating points are similar but you might wanna read up on fixed point numbers first, which similarly have each value given an interval around it. That's how we can do thkngs like 1/3 using a base 2 number. We simply check which interval 1/3 falls into and that is the value we assign it.
1
u/quarethalion Jul 17 '26
There are a few reasons behind this:
#1 + #2 is what limits the range of floating-point numbers (and integers, for whole numbers).
#1 + #3 is what limits the precision of floating-point numbers, requiring real numbers to be quantized to the nearest representable value.
#4 is why some numbers like 0.1 aren't exactly representable and wouldn't be no matter how many bits were used.
It is possible for computers to operate on arbitrarily large/precise numbers, but the mechanisms for doing so make the operations orders of magnitude slower than working with
floatanddouble, which are just fine for the vast majority of use cases.1
u/Dense-Sort-3867 Jul 17 '26
This video was recommended by my numerical analysis professor when I was getting my applied math degree.
https://youtu.be/9hdFG2GcNuA?is=x3Oe5XNPtk4a2ydi
1
u/hxtk3 Jul 18 '26
Most real numbers can’t be stored in a finite amount of RAM. In fact, 0% of the real numbers can be stored in finite memory because there are only countably infinite byte strings and there are uncountably infinite real numbers.
IEEE754 floating point can only represent 232 values, and 2 of them are 0, two if them are not numbers, and two of them are infinite.
Since 232 is considerably less than the number of real numbers, some of them have to share the same representation.
1
u/BlockOfDiamond Jul 18 '26
0.1 is 1/10, which cannot be represented exactly in binary, the same way 1/3 cannot be represented exactly in decimal, being
0.333...forever. The only numbers that can be represented exactly are Dyadic rationals (up to a point, of course).1
u/windswept_mystical Jul 18 '26
If you can’t express a number as a fraction with a power-of-two denominator, then you can’t actually represent it as IEEE 754 floating point. For example, 1/5 (0.2) has to be approximated in 32-bits as 1 + (5,033,165/2²³) × 2⁻³ = 0.20000000298023224.
1
u/Glittering-Work2190 Jul 18 '26
Read up on "machine epsilon"
1
u/petecasso0619 Jul 18 '26
In that case, you are trying to represent a decimal value 0.1 as a binary number which repeats forever in base 2. When we use floating point numbers we have to store that infinitely repeating binary number into a finite number of bits. The most common way to do this is to store the number as described in the IEEE-754 standard. This is NOT the only way to represent a floating point number but it is very common. In my opinion, the standard is pure genius.
If you want a detailed paper check out What Every Computer Scientist Should Know About Floating Point Numbers.
It is amazing to me how many devs think when you perform a series of floating point operations the error will remain machine epsilon. Its usually my first question when we are adding someone new to the team.
1
u/StudioYume Jul 18 '26 edited Jul 18 '26
Floating point numbers are like scientific notation except that, because the bit width is fixed, the number of significant figures is limited by the exponent of the base and a few other things.
When it's necessary to store exact values, it's best to store them as a string or as the parameters of a formula that produces the exact value, or a platform-dependent approximation.
1
u/GrandBIRDLizard Jul 18 '26
Because base 10 sucks. base 12 or 60 worked great and the Babylonians knew this millennia ago.
1
u/siuui1729 Jul 18 '26
Floating point numbers are represented on a base-2 grid. So base-2 numbers like 4, 2, 0.5, 0.25, etc.. lie exactly on the grid (no extra digits), but other numbers lie in between. The absolute error is on the order of the grid spacing dx, which changes depending on the order of magnitude of the number being represented: dx=machine epsilon*2n where n is the exponent part of the representation.
Machine epsilon in double precision is ~1e-16, so for numbers of order ~1 like 1.0772976839852897428 (n=0): dx~1e-16, which means that the error will be present around the ~16th decimal place and beyond. Meanwhile, for a number like 19345289754972.937681 (n=44), the spacing is on the order of: dx~1e-16 * 244 ~1e-3, so the error will be present only around the ~3rd decimal place and beyond. But if you count the number of significant digits of both numbers, you can see that both the 16th decimal place of the first number and the 3rd decimal place of the second number correspond to the 17th significant digit in both.
These examples show the main idea behind floating point representation: the grid spacing changes depending on the order of magnitude of the number being represented, such that the relative spacing error remains practically constant. This relative error is ~machine epsilon (~1e-16 for double precision), which means that for any order of magnitude (3.8176381936482937793, 0.000073628163829273682979, 18277741580374.71677, etc...), the error will be present around the ~16th significant digit and beyond. Similarly, for single precision the machine epsilon is ~1e-7, so the error will be present around the ~7th significant digit and beyond.
I recommend playing around with online converters like this one (only single precision) and this one (single+double precision) to get a more intuitive feel for how it works.
1
u/codeguru42 Jul 18 '26
It is similar to the fact that 0.3333 is an approximation to the fraction 1/3. You need infinite digits to represent 1/3 exactly. So with finite digits you can only approximate. Similarly a finite number of bits can only approximate most real numbers.
1
u/notacanuckskibum Jul 18 '26
The number 1/3rd can't easily be represented in base ten, the best we can do is 0.33333333333333... But in base 3 it would be easy (it would be 0.1) Computers store numbers in Binary (base 2). Some numbers that can be represented easily in base ten can't be easily represented in base 2.
1
u/f0xw01f Jul 19 '26
You can't represent an infinite number of numbers with a finite number of bits. Something has to give. We live with approximations.
1
u/horenso05 Jul 19 '26
Apart from what has been mentioned with floats being finite in storage (usually a 32-bit floating point number is called a float and a 64-bit variant is called a double) it is also crucial to understand that different numbering systems can prepresent different fractions.
In decimal we famously struggling to express 1/3 with finitely many places because it is exactly 0.333... repeating forever. In decimal we have tenths, hundredths, thousandths and so on. We cannot combine them so that we get exactly 1/3 except for going on forever.
In binary 2/10 (what in decimal is just clean 0.2) is an infinitely repeating pattern (0.2)(0.00110011...). The sequence (0011) loops forever. The reason this happens is that in binary you only got powers of two so halfs, quarter, eights, sixteenths, and so on. Again, no combination of these get there with a finite number of digits.
When using floats to represent 0.2 we're already rounding since we chop off that repeating pattern.
1
u/EmbedSoftwareEng Jul 20 '26
Because all primitive computer data types are stored in binary.
You're looking at a decimal equivalent representation, which is not equivalent.
It's like, asking "Why does `printf("%u\n", 0xFF);` print "255"? 255 decimal is equivalent to FF hexadecimal.
But in floating point, the mantissa is stored in binary, with the first bit being omitted, because it has to be a 1. Imagine a binary floating point value stored as 1.000000000101010101 * 2^10100010001010 being converted to decimal. It couldn't. Not and retain precisely the same numeric value.
1
u/Stu_Mack Jul 20 '26
Personally, I am perpetually annoyed by how this affects the == test.
0
u/Olovico75 Jul 19 '26
An interesting take on floating points in the Audio & DSP development and the practical side of approximations there :
https://gdvp.net/engineering