[Tutor] Binary Real to Decimal
spir
denis.spir at free.fr
Mon Mar 30 09:20:37 CEST 2009
Le Sun, 29 Mar 2009 22:42:43 -0500,
Chris Castillo <ctcast at gmail.com> s'exprima ainsi:
> myinput = raw_input("Please enter a binary real number: ")
> myinput = myinput.split(".")
>
> binstr1 = myinput[0]
> binstr2 = myinput[1]
>
> decnum1 = 0
> decnum2 = 0
>
> for i in binstr1:
> decnum1 = decnum1 * 2 + int(i)
>
> for k in binstr2:
> decnum2 = decnum2 * 2 + int(k)
>
>
>
> print "\nThe binary real number ", binstr1, ".", binstr2, " converts to ",
> decnum1,".",decnum2," in decimal."
>
>
> that is what I have so far but I need to create a condition where I need
> only 10 sufficient numbers from the variable decnum2. I know I need
> something like
> if len(decnum2) > 11:
> decnum2 = decnum2[0:11]
>
> but I keep getting unsubscriptable errors. I know it has to do with types
> but it's late and I just need some help. thank you in advance. - chris
This is a symptom that you mistake numeral values for textual ones. Your loops
for k in binstr2:
decnum2 = decnum2 * 2 + int(k)
build integers. They are numbers for python, not text snippets that happen to represent numbers for humans.
When you print (decnum1,".",decnum2), python silently converts both integers to standard representations of integers (eg 123 --> "123") that happen to be what you expect to see. Then if you join together two integer representations with '.' as glue, sure you will get something that looks like a (representation of a) real number -- but this is only superficial appearance. You have never built a real real (!) number (type float).
You cannot use the result to compute anything, for instance.
To get the result, you need to process together decnum1 (integral part) and decnum2 (fractional part) into a single (real) number. Then print the result.
Denis
------
la vita e estrany
More information about the Tutor
mailing list