Next float?

Mark Dickinson dickinsm at gmail.com
Thu Nov 22 17:54:38 EST 2007


On Nov 22, 5:41 pm, Mark Dickinson <dicki... at gmail.com> wrote:
> On Nov 21, 11:48 pm, "Mark T" <nos... at nospam.com> wrote:
>
>
>
> > Here's some functions to get the binary representation of a float.  Then
> > just manipulate the bits (an exercise for the reader):
>
> > import struct
>
> > def f2b(f):
> >     return struct.unpack('I',struct.pack('f',f))[0]
>
> > def b2f(b):
> >     return struct.unpack('f',struct.pack('I',b))[0]
>
> > >>> f2b(1.0)
> > 1065353216
> > >>> hex(f2b(1.0))
> > '0x3f800000'
> > >>> b2f(0x3f800000)
> > 1.0
> > >>> b2f(0x3f800001)
> > 1.0000001192092896
> > >>> b2f(0x3f7fffff)
>
> > 0.99999994039535522
>
> And it's worth noting that thanks to the way the floating-point format
> is designed, the 'bit-twiddling' is actually just a matter of adding
> or subtracting one from the integer representation above.  This works
> all the way from zero, through subnormals, up to and including
> infinities.
>
> Mark (but not the same Mark)

And also worth noting that the 'f's above should probably be 'd's.
For example, the following works on my machine for positive floats.
Fixing this for negative floats is left as a not-very-hard exercise...

>>> from struct import pack, unpack
>>> def next_float(x): return unpack('d', pack('q', unpack('q', pack('d', x))[0]+1))[0]
...
>>> next_float(1.0)
1.0000000000000002

Mark



More information about the Python-list mailing list