Pages

Thursday, September 15, 2016

Converting to decimal

Give a number n in some number base b, how can we convert the given number from base b to its decimal (base 10) equivalent?

Let nb represent our number n in base b. And let's consider, say, the case where nb has five digits to the left of the decimal point and two digits to the right of the decimal point:
ddddd0 . d-1 d-2
To convert nb to n10 simply evaluate the following mathematical expression:
d4*(b4) + d3*(b3) + d2*(b2) + d1*(b1) + d0*(b0) + d-1*(b-1) + d-2*(b-2)
So if nb is 10210.123 (base 3) then the value of n10 (base 10) is:
1*(34) + 0*(33) + 2*(32) + 1*(31) + 0*(30) + 1*(3-1) + 2*(3-2)
= 1*(81) + 0*(27) + 2*(9) + 1*(3) + 0*(1) + 1*(1/3) + 2*(1/9)
= 81 + 0 + 18 + 3 + 0 + 1/3 + 2/9
= 102 + 5/9
= 102.555...
Note that the same value may have a finite number of digits after the decimal point in one number base while having an infinite number of digits after the decimal point in another base. In the example above, 102.555... is an example of a repeating decimal; the same value in base 3 has only two non-zero digits after the decimal point! This is why computers sometimes return surprising results when you attempt to perform what, on the surface, appears to be very simple arithmetic using floating point numbers.

For example, when I use JavaScript to evaluate the expression 2 - 1.1 in the web browser I'm using to compose this post, the result returned is 0.8999999999999999! Although 1.1 (base 10) has only one digit to the right of the decimal point, the binary equivalent of 1.110 is 1.000110011001100...2.

Since computers perform computations using binary approximations of numbers, sometimes the binary approximation of a number can be exact and sometimes it's a little bit more than or a little big less than the actual value due to the fact that only a finite number of bits may be used to represent any given binary number using any real computer. Similarly, many numbers are too large or too small to be represented given a finite number of bits. More about this later!