Binary Decimals in Python

Chris Kaynor ckaynor at zindagigames.com
Tue Mar 30 16:19:33 EDT 2010


Chris


On Tue, Mar 30, 2010 at 11:14 AM, John Nagle <nagle at animats.com> wrote:

> aditya wrote:
>
>> On Mar 30, 10:49 am, Raymond Hettinger <pyt... at rcn.com> wrote:
>>
>>> On Mar 30, 8:13 am, aditya <bluemangrou... at gmail.com> wrote:
>>>
>>>  To get the decimal representation of a binary number, I can just do
>>>> this:
>>>> int('11',2) # returns 3
>>>> But decimal binary numbers throw a ValueError:
>>>> int('1.1',2) # should return 1.5, throws error instead.
>>>> Is this by design? It seems to me that this is not the correct
>>>> behavior.
>>>>
>>> The int() constructor returns integers.
>>> So, look to float() for non-integral values.
>>> Binary representation isn't supported yet,
>>> but we do have hex:
>>>
>>>    >>> float.fromhex('1.8')
>>>    1.5
>>>
>>> Raymond
>>>
>>
>> That looks very elegant, thanks!
>>
>
>   Hex floats are useful because you can get a string representation
> of the exact value of a binary floating point number.  It should
> always be the case that
>
>         float.fromhex(float.hex(x)) == x
>
> That's not always true of decimal representations, due to rounding
> problems.
>

Actually, any number you can represent exactly in base 2 (or any power there
of) you can also represent exactly in decimal - its the other way around
thats a problem.


>
> Long discussion of this here: "http://bugs.python.org/issue1580"
>
>
>                                John Nagle
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100330/2ecf5301/attachment-0001.html>


More information about the Python-list mailing list