Next float?

Fredrik Johansson fredrik.johansson at gmail.com
Thu Nov 22 04:35:16 EST 2007


On Nov 22, 2007 4:04 AM, Steven D'Aprano
<steven at remove.this.cybersource.com.au> wrote:
> 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

You could use the library functions for floating-point math in mpmath
(http://code.google.com/p/mpmath/), which support directed rounding.
Load a floating-point number, add a tiny number and round in the
wanted direction, then convert back to a Python float:

>>> from mpmath.lib import *
>>> eps = (1, -2000, 1)    # 2**-2000, smaller than any finite
positive IEEE 754 double
>>> a = from_float(1.0, 53, ROUND_HALF_EVEN) # note: exact
>>> to_float(fadd(a, eps, 53, ROUND_UP))
1.0000000000000002
>>> to_float(fsub(a, eps, 53, ROUND_DOWN))
0.99999999999999989

This currently probably doesn't work if the numbers are subnormal, however.

Fredrik



More information about the Python-list mailing list