"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Is there a simple, elegant way in Python to get the next float from a > given one? By "next float", I mean given a float x, I want the smallest > float larger than x. > > Bonus points if I can go in either direction (i.e. the "previous float" > as well as the next). > > Note to maths pedants: I am aware that there is no "next real number", > but floats are not reals. > > > -- > Steven
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 -Mark -- http://mail.python.org/mailman/listinfo/python-list