Binary Real to Decimal Algorithm

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Mar 2008
Posts: 9
Reputation: xRuP7uR3x is an unknown quantity at this point 
Solved Threads: 0
xRuP7uR3x xRuP7uR3x is offline Offline
Newbie Poster

Binary Real to Decimal Algorithm

 
0
  #1
Mar 24th, 2008
Greetings once more. I have been working on a script to convert a user provided number in basetwo and convert it to baseten. What I've got so far:
  1. myinput = raw_input("Enter a binary real number: ")
  2. (myint, myfrac) = myinput.split(".")
  3. x = int(myint[0])
  4. y = 0
  5. t = len(myint)
  6. while y < (t - 1):
  7. if y == t:
  8. z = 0
  9. else:
  10. z = int(myint[y + 1])
  11. x = x * 2 + z
  12. y = y + 1
  13. b = int(myfrac[-1])
  14. k = len(myfrac)
  15. a = 1
  16. while a <= k:
  17. if a == k:
  18. c = 0
  19. else:
  20. c = int(myfrac[(-1 - a)])
  21. b = b * 2 + c
  22. a = a + 1
  23. print myinput + " in basetwo is equivalent to %d.%d in baseten." % (x, b)

It seems to work, but I feel like I'm going about this the entirely wrong way ie. there is a simpler way to write this algorithm.

Thanks in advance for your thoughts.
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 1,037
Reputation: woooee is a jewel in the rough woooee is a jewel in the rough woooee is a jewel in the rough 
Solved Threads: 293
woooee woooee is offline Offline
Veteran Poster

Re: Binary Real to Decimal Algorithm

 
0
  #2
Mar 25th, 2008
  1. while y < (t - 1):
  2. if y == t:
Note that (t-1) < t, so y is always less than t and the if() portion will never be executed. You can also use a for loop
  1. t = len(myint)
  2. ##while y < (t - 1):
  3. for y in range(0, t):
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC