Re: OT: Need help with numeric bases
From: | H. S. Teoh <hsteoh@...> |
Date: | Tuesday, February 25, 2003, 15:42 |
On Mon, Feb 24, 2003 at 10:22:17PM -0600, Peter Clark wrote:
[snip]
> #! /usr/bin/env python
> from sys import argv
> def ash(n):
> n = int(n) - 1
> if n >= 0:
> return str(ash(n / 8)) + str((n % 8) + 1)
>
> def dec(n):
> acc = 0
> for digit in n:
> acc = acc * 8 + int(digit)
> return acc
>
> a = ash(argv[1])[4:]
> print a
> print dec(a)
> ---
> One problem with translating this code: Python returns "None" on empty
> returns, which is what happens at the last level of recursion in ash(). Thus,
> the full return to ash(517) is "None785", hence the [4:] when printing the
> answer.
[snip]
Just have it return an empty string in an else-clause. I don't know how
Python represents an empty string, but I suspect an 'else: return ""'
should do the trick. :-)
> Next up: floating numbers!
[snip]
Hmm, I had a crack at it this morning, but it turns out to be more tricky
than I thought. One reason is that under your system, 2 ash can also be
written as 1.8 ash, or 1.78 ash, or even 1.777778 ash. So depending on
whether you want to force a specific number of octals/ashals, you'll have
the script returning 1.778 ash for 2 ash, etc..
And I'm not sure what your convention is for fractions between 0 and 1: I
suppose you just have a single octal point in front followed by the
mantissa? In which case, 1 ash = .8 ash = .78 ash = .778 ash, ... etc..
Very interesting system, I must say, though having multiple possible
representations of the same number may not necessarily be something
desirable. Perhaps one solution is to force rounding up if the last digit
of the mantissa comes out as 8.
T
--
Give me some fresh salted fish, please.
Replies