[Tutor] base n fractional
Alan Gauld
alan.gauld at btinternet.com
Mon Apr 6 10:19:04 CEST 2009
"Chris Castillo" <ctcast at gmail.com> wrote
> well i want to use a for loop to work from the right most digit to the
> left
> most digit at a negative 1 increment. For each digit i want to divide it
> by
> 1/base and add the next digit. Then I need to take that sum and multiply
> it
> by 1/b to get the decimal equivalent
>
> so when I say that to myself i see:
> number = 234
> mysum = 0
> for digit in range(len(number) -1, -1, -1):
> mysum = (mysum) * (1/base) + int(number[digit])
Lets walk that algorithm for base 10...
Loop 1 - mysum = 0 * 1/10 + 4 => 4
Loop 2 - mysum = 4 * 1/10 + 3 => 3.4
Loop 3 - mysum = 3.4 * 1/10 +2 => 2.34
That's not what you were looking for I suspect?
You still need the final division...
But I still think its easier to get the digits directly using
>> for digit in reversed(list('234')):
And the calculation then becomes:
mysum = mysum * (1/base) + int(digit)
But that gives the same result.
I think you want:
mysum = (mysum + int(digit))/base
So walking the loop gives
loop 1 - mysum = (0 + 4)/10 -> 0.4
loop 2 - mysum = (0.4 + 3)/10 -> 0.34
loop 3 - mysum = (0.34 + 2)/10 -> 0.234
However I still think converting to int and then dividing by base**len(n)
is easier.
mysum = int('234')/10**len('234') -> 234/1000 -> 0.234
Is there a particular reason for you using the looping algorithm
rather than the tools in Python?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list