[Tutor] Binary Real to Decimal
Dave Angel
davea at ieee.org
Mon Mar 30 12:45:35 CEST 2009
I don't know what "sufficient numbers" means, but perhaps it's "significant digits" that was intended. And you have to decide if you want ten digits to the right of the decimal point, or ten significant digits in the whole number. That determines whether you want to round decnum2 or the final value you get from combining decnum1 and decnum2.
But you have two other problems to address before you do any rounding, I'll address only the first.
1) The present value displayed are simply wrong.
2) You need to combine the two integers decnum1 and decnum2 into a single real.
If the user enters 1.1010 you display 1 . 10 which is not the correct decimal representation of the value entered. 1.1010 binary is 1.625 in decimal.
A few more samples:
11.0001 is not 3.1 but is actually 3.0625
110.00001 is not 6.1 but is actually 6.03125
110.00011 is not 6.3 but is actually 6.09375
In particular, your logic doesn't take into account the number of digits entered to the right of the binary point. decnum2 must be divided by some power of two to get the right value.
Once you get a useful representation for the decnum2 part, it should be obvious how to combine the two.
Chris Castillo wrote:
> 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
>
>
More information about the Tutor
mailing list