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.
0.1
in binaryThe 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 .
0.1
in floating-pointThe 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.
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)
0.1
in 17 significant digits using the format()
method.0.1
using the from_float()
method of the Decimal
library.0.1
in 17 significant digits using the Decimal
library’s function.bitstring
library’s function.Free Resources