On Jan 19, 2006, at 10:31, Guido van Rossum wrote:

To keep it simple, the proposal is for the value to be any int or long. With an underlying __base__ method call, it wouldn't be hard for someone
to build it out to support other numeric types if the need arises.

Let's not. What would 3.14 be expressed in base 3?

10.010210001

It turned out to be a fun aside, and I've attached my quick and dirty script as a strawman.

For what it's worth, I don't like the name base() because it sounds like something I would call on a class to get it's bases. Perhaps nbase? And maybe fbase for the floating point one...

Thanks,
-Shane Holloway

#!/usr/bin/env python
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Imports 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

import math

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Definitions 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

def ibase(n, radix=2, maxlen=None):
    r = []
    while n:
        n,p = divmod(n, radix)
        r.append('%d' % p)
        if maxlen and len(r) > maxlen:
            break
    r.reverse()
    return ''.join(r)
 
def fbase(n, radix=2, maxlen=8):
    r = []
    f = math.modf(n)[0]
    while f:
        f, p = math.modf(f*radix)
        r.append('%.0f' % p)
        if maxlen and len(r) > maxlen:
            break
    return ''.join(r)
 
def base(n, radix, maxfloat=8):
    if isinstance(n, float):
        return ibase(n, radix)+'.'+fbase(n, radix, maxfloat)
    elif isinstance(n, (str, unicode)):
        n,f = n.split('.')
        n = int(n, radix)
        f = int(f, radix)/float(radix**len(f))
        return n + f
    else:
        return ibase(n, radix)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Main 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if __name__=='__main__':
    pi = 3.14
    print 'pi:', pi, 'base 10'

    piBase3 = base(pi, 3)
    print 'pi:', piBase3, 'base 3'

    piFromBase3 = base(piBase3, 3)
    print 'pi:', piFromBase3, 'base 10 from base 3'

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to