| | |
Binary Real to Decimal Algorithm
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Mar 2008
Posts: 9
Reputation:
Solved Threads: 0
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:
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.
python Syntax (Toggle Plain Text)
myinput = raw_input("Enter a binary real number: ") (myint, myfrac) = myinput.split(".") x = int(myint[0]) y = 0 t = len(myint) while y < (t - 1): if y == t: z = 0 else: z = int(myint[y + 1]) x = x * 2 + z y = y + 1 b = int(myfrac[-1]) k = len(myfrac) a = 1 while a <= k: if a == k: c = 0 else: c = int(myfrac[(-1 - a)]) b = b * 2 + c a = a + 1 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.
•
•
Join Date: Dec 2006
Posts: 1,037
Reputation:
Solved Threads: 293
Python Syntax (Toggle Plain Text)
while y < (t - 1): if y == t:
Python Syntax (Toggle Plain Text)
t = len(myint) ##while y < (t - 1): for y in range(0, t):
![]() |
Similar Threads
Other Threads in the Python Forum
- Previous Thread: read array from file.
- Next Thread: Alittle Newbie Help, finished script
| Thread Tools | Search this Thread |
abrupt ansi anti approximation array assignment avogadro backend beginner binary bluetooth builtin calculator character chmod code converter countpasswordentry curved customdialog dan08 decimals dictionaries dictionary drive dynamic examples excel exe file float format function gnu graphics gui heads homework http ideas import input java launcher leftmouse line linux list lists loop module mouse mysqlquery number numbers output parsing path plugin pointer port prime programming progressbar projects py2exe pygame pysimplewizard python random recursion scrolledtext sqlite statistics stdout string strings sum table terminal text textarea thread threading time tkinter tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable windows write wxpython xlib






