So far, these are number bases I have covered:
So now that both positive and negative bases have been covered, we’re done right? Well not quite.
See that vacant space around 0 on the number line? That’s where values like ½, -¾ and so on are. This region is where fractional bases live. How you handle them is rather easy.
But first a definition about the characters is needed. While base 2 uses two characters and base 1 uses one character, how many characters does base ½ use? We can’t just take the ceiling of it because that gives us one character to work with, which isn’t enough. So we say that a fractional base uses the number of characters that its inverse uses. So the inverse of ½ is 2 and base 2 uses two characters, which is the number of characters that base ½ will use. Similarly base -0.12 will use nine characters, as its inverse is -8.33 and that base uses nine characters.
So how is a number converted into a fractional base? Simple. You first convert it into its inverse base. Then you move the fractional separator one character to the left and reverse the characters.
For example, say we want 34 in base 1/5. Convert 34 to base 5 which is 114. Next move the separator over one character and 114 becomes 11.4 Finally, reverse the order: 11.4 becomes 4.11. Thus 34 in base 1/5 is 4.11. To convert back we still use the definition of a base which for this value is 4(1/5)^(0) + 1(1/5)^(-1) + 1(1/5)^(-2) = 34.
In Python, the code looks like this:
def toInvertedB(n,B):
"""Converts a number from base 10 to base B Where -1<B<1 and B!=0.
Returns a list of digits"""
if not -1<B<1 or B==0:
E="this function does not accept a base of this value: {:.4f}".format(B)
raise TypeError(E)
invert=1./B#invert the base
#convert to base 1/B
if B<0:L=toBaseNegB(n,invert)#these return the value in a list
else:L=toBaseB(n,invert)
if L==[0]:return L
#handle negative values cleanly
add_neg=False
if'-'in L:
L.remove('-')
add_neg=True
#for a base 0<b<1:
# convert to base 1/b, shift fractional separator to the left one digit
# and swap all the digits
shift=L.index('.')-1
L.remove('.')
L.insert(shift,'.')
L.reverse()
#restore negative sign if negative value
if add_neg:L.append('-')
#remove any leading zeros
while L[0]==0:
#leave at least one leading zero in front of the fractional separator
if L[1]=='.':break
L=L[1:]
return L
My previous code deals with converting numbers in lists (so I can assign any character to them) so this is just some list handling.
So with this final piece the entire real number line is now available for use as a base. All that’s left is to put them together.
References:
1. http://roytanay.expertscolumn.com/article/how-convert-decimal-number-any-fractional-base-tutorial
2. number lines by C. Harman


Leave a comment