Chris Castillo wrote:

Message: 1
Date: Sun, 5 Apr 2009 15:36:09 -0500
From: Chris Castillo <ctc...@gmail.com>
Subject: [Tutor] base n fractional
To: tutor@python.org
Message-ID:
        <50e459210904051336v60dfc6ddt280d3c9c8f6e0...@mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

I need some help converting the fractional (right side of the decimal) to
base 10.
I have this but it doesn't work

mynum = raw_input("Please enter a number: ")
myint, myfrac = mynum.split(".")
base = raw_input("Please enter the base you would like to convert to: ")
base = int(base)
mydecfrac = 0
fraclen = len(myfrac) - 1

for digit in range(len(myfrac) -1, -1, -1):
    mydecfrac = mydecfrac + int(myfrac[digit])
    mydecfrac = mydecfrac / base
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
<http://mail.python.org/pipermail/tutor/attachments/20090405/612ca99f/attachment-0001.htm>
First we need a clear statement (with examples) of your goal. Your prompts to the user indicate you want to convert from decimal to some other base. But your comments here and elsewhere on the thread indicate the exact opposite. The two problems are related, but mixing them will just confuse everybody.

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])

This just isn't valid python.  You can't subscript an integer.  You probably 
need a string here.  That is what raw_input() would produce.

So let's get a specific example, and try to work with it.


Perhaps you want
   base = 5
  myfrac = "234"

and you want to figure the value that .234 would mean if it's interpreted as base 5. First, let's do it by hand. The two is in the first digit to the right of the decimal place, and therefore represents 2/5
  The three is in the next place, and represents 3/25
  And the four is in the next place and represents 4/125
Result is 0.552 decimal

There are two ways to work a base conversion. One is to do the arithmetic in the source base, and do successive multiplies of the destination base. That would mean working in base 5 in this case, which is probably more work in Python. The other is to work in the result base, and do the multiplies of the source base. That's the approach you were taking, and it works great if the precision of a float is acceptable.


Your code is fine, although a bit convoluted. Only problem is that you're working in integers, when you need float. So just change mydecfrac to 0.0 and it'll work.

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to