Bit twiddling floating point numbers
mensanator at aol.com
Wed Mar 5 22:27:36 CET 2008
On Mar 5, 2:25 pm, "Jeff.Goldfin... at gmail.com"
<Jeff.Goldfin... at gmail.com> wrote:
> Hi All
> Is there a simple way to twiddle the bits of a float? In particular, I
> would like to round my float to the n most significant bits.
> For example - 0.123 in binary is 0.000111111
> Rounding to 4 bits I get 0.0001.
> I can pack and unpack a float into a long
> but then I'm not sure how to work with the resulting long.
> Any suggestions?
>>> import gmpy
# create a base 10 float
>>> f = gmpy.mpf('123.456')
# format in base 2, fixed point
>>> f2 = gmpy.fdigits(f,2,0,0,99)
# seperate the characteristic from the mantissa
>>> fs = f2.split('.')
# re-assemble with the mantissa truncated to desired # of bits
>>> f3 = fs+'.'+fs[:4]
# convert the string back to a base 10 float
>>> f4 = gmpy.mpf(f3,0,2)
>>> print f4
# check: print as base 2 and see how many digits are past radix point
>>> print gmpy.fdigits(f4,2,0,0,99)
More information about the Python-list