Why does 0.1 not exist in floating-point?
Overview
There are a lot of decimals with infinite representations in binary. One such example is 0.1. It looks complicated in binary, but it is one of the simplest decimals.
The number 0.1 in binary
The number 0.1 can be represented in binary as 0.00011001100110011....
The pattern of 0011 repeats infinitely. We can’t store the binary equivalent of decimal 0.1.
As we know, 0.1 is equal to 1/10. A binary of 10 is equal to 1010. When we divide 1 by 1010 to show 0.1 as a bicimal, then the division process will never terminate. In other words, it will repeat forever. We can abort this division process by writing it as .
The number 0.1 in floating-point
The finite representation of 1/10 is , but it can’t be represented in floating-point because we can’t deal with bars in floating-point. We can represent it only in fixed digits/bits using any data type. In floating-point, we can represent it using 53 bits.
Coding example
Different data types can store different numbers of significant digits according to their storage capacity. The following example shows the number 0.1 in decimal and binary. We can truncate the value to the specific significant digits or bits.
from decimal import Decimalfrom fractions import Fractionimport bitstringprint("----Representing 0.1 in 17 significant digits----")print(format(0.1, '.17g')) # 17 significant digitsprint("----Representing 0.1 in decimal----")print(Decimal.from_float(0.1))print("----Representing 0.1 in decimal using 17 significant digits----")print(format(Decimal.from_float(0.1), '.17')) # 17 significant digitsprint("----Representing 0.1 in binary----")bits = bitstring.BitArray(float=0.1, length=64) # 64 bitsprint(bits.bin)
Explanation
- Lines 1-3: We import different packages.
- Line 6: We print
0.1in 17 significant digits using theformat()method. - Line 8: We print
0.1using thefrom_float()method of theDecimallibrary. - Line 10: We print
0.1in 17 significant digits using theDecimallibrary’s function. - Line 13: We print the value in binary using the
bitstringlibrary’s function.
Free Resources