Bit twiddling floating point numbers
Jeff.Goldfinkle at gmail.com
Jeff.Goldfinkle at gmail.com
Thu Mar 6 08:21:07 CET 2008
On Mar 5, 11:27 pm, Mensanator <mensana... at aol.com> wrote:
> 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
> > e.g.
> > struct.unpack('I',struct.pack('f',0.123))[0]
> > but then I'm not sure how to work with the resulting long.
>
> > Any suggestions?
>
> Here's one.
>
> >>> import gmpy
>
> # create a base 10 float>>> f = gmpy.mpf('123.456')
> >>> f
>
> mpf('1.23456e2')
>
> # format in base 2, fixed point>>> f2 = gmpy.fdigits(f,2,0,0,99)
> >>> f2
>
> '1111011.01110100101111000110101001111110111110011101101100100010111'
>
> # seperate the characteristic from the mantissa
>
> >>> fs = f2.split('.')
>
> # re-assemble with the mantissa truncated to desired # of bits>>> f3 = fs[0]+'.'+fs[1][:4]
> >>> f3
>
> '1111011.0111'
>
> # convert the string back to a base 10 float>>> f4 = gmpy.mpf(f3,0,2)
> >>> print f4
>
> 123.4375
>
> # check: print as base 2 and see how many digits are past radix point>>> print gmpy.fdigits(f4,2,0,0,99)
>
> 1111011.0111
excellent - thanks that does exactly what I need.
More information about the Python-list
mailing list