Binary Decimals in Python
Mensanator
mensanator at aol.com
Tue Mar 30 14:03:27 EDT 2010
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,
It is supported in the gmpy module.
>>> import gmpy
>>> help(gmpy.mpf)
Help on built-in function mpf in module gmpy:
mpf(...)
mpf(n): builds an mpf object with a numeric value n (n may be any
Python number, or an mpz, mpq, or mpf object) and a
default
precision (in bits) depending on the nature of n
mpf(n,bits=0): as above, but with the specified number of bits (0
means to use default precision, as above)
mpf(s,bits=0,base=10): builds an mpf object from a string s made
up of
digits in the given base, possibly with fraction-part
(with
period as a separator) and/or exponent-part (with exponent
marker 'e' for base<=10, else '@'). If base=256, s must be
a gmpy.mpf portable binary representation as built by the
function gmpy.fbinary (and the .binary method of mpf
objects).
The resulting mpf object is built with a default precision
(in
bits) if bits is 0 or absent, else with the specified
number
of bits.
>>> gmpy.mpf('1.1',0,2)
mpf('1.5e0')
> but we do have hex:
>
> >>> float.fromhex('1.8')
> 1.5
>
> Raymond
More information about the Python-list
mailing list