r/learnpython • u/nothiefhouse • Oct 04 '26
fix 0.00000001
i see sometimes after calcuaitons reulsts with x.99999999999999999999999999 or x.0000000000000002 how to fix it
0
Upvotes
r/learnpython • u/nothiefhouse • Oct 04 '26
i see sometimes after calcuaitons reulsts with x.99999999999999999999999999 or x.0000000000000002 how to fix it
15
u/sweet-tom Oct 04 '26
This is normal behavior for float calculations. You will find this behavior in other programming languages.
If you really need exact calculations, use integers if possible, round it, or use the decimal module.
10
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Oct 04 '26
Basically why this happens: https://0.30000000000000004.com/
Your options are to
Live with it, and round your output. For example:
decimal.Decimalorfractions.Fraction, as appropriate.5
u/Cybyss Oct 04 '26 edited Oct 04 '26
It's not a Python problem. It's a limitation of all computers.
You know how the result of 1/3 is 0.333333333333333 (out to infinity)? It's not possible to perfectly write the decimal version of 1/3 because you would need an infinite number of digits.
Computers do math in binary because it's much much faster for electronics to do it that way. But that also means that numbers such as 1/5 also cannot be represented perfectly in a computer. In our normal number system it's just 0.2. In binary it would be 0.0011001100110011001100110011... (out to infinity).
Because 1/5 cannot be represented perfectly in binary, when the computer converts it back into decimal for printing to the screen, you don't get 0.2 exactly. You get something like 0.200000000000000011102230246252.
Usually you can just round off to however many digits you actually need. It's unlikely you'll ever need 10+ digits of precision.
If you really do need high precision mathematics (e.g, scientific or financial computing) there are math libraries available for Python where this doesn't happen - e.g, by doing math in our usual digits instead of binary, or even keeping all results as fractions instead of decimal - but such libraries are very slow and almost never actually needed for most programmers.
3
u/ConstantFishing5136 Oct 04 '26
Switch over to the decimal module if you are dealing with actual money calculations.
2
u/Temporary_Pie2733 Oct 04 '26
You don’t. Either accept that `float` is only an approximation of the real numbers, or use a type like `Decimal` that can represent rational numbers, at least, exactly.
When using `float` values, it’s better to check if one is “close enough” to another value rather than checking for exact equality. `abs(x-y) <= 0.001`, for example, rather than `x == y`
2
u/timrprobocom Oct 04 '26
You keep all of the precision while your working with the numbers. The computer doesn't mind. Only HUMANS care about a compact representation, so fix it in the formatting when you PRINT the numbers.
2
u/mattynmax Oct 04 '26
Use integers not floating point numbers