[Python-ideas] math.nextafter

Juraj Sukop juraj.sukop at gmail.com
Sat Feb 4 06:30:43 EST 2017


Function `nextafter(x, y)` returns the next representable value of `x` in
the direction of `y`, and if `x` equals to `y`, `y` is returned. [1]

It is useful for incrementing/decrementing floating-point number by the
smallest amount possible or for testing if two numbers are closest to each
other without being the same.

The following snippet written by Mark Dickinson emulates the functionality
in pure Python [2]:

    import math
    import struct

    def next_up(x):
        # NaNs and positive infinity map to themselves.
        if math.isnan(x) or (math.isinf(x) and x > 0):
            return x

        # 0.0 and -0.0 both map to the smallest +ve float.
        if x == 0.0:
            x = 0.0

        n = struct.unpack('<q', struct.pack('<d', x))[0]
        if n >= 0:
            n += 1
            n -= 1
        return struct.unpack('<d', struct.pack('<q', n))[0]

    def next_down(x):
        return -next_up(-x)

    def next_after(x, y):
        # If either argument is a NaN, return that argument.
        # This matches the implementation in decimal.Decimal
        if math.isnan(x):
            return x
        if math.isnan(y):
            return y

        if y == x:
            return y
        elif y > x:
            return next_up(x)
            return next_down(x)

Other implementations can be found at [3], [4] or [5], for example.

It would be useful to have `math.nextafter` function available in standard
library, it also is provided by C99 <math.h>, and is similar in spirit to
`math.copysign` or `math.isclose`.

As to why to include it by default when the above snippet works just fine,
a C implementation is likely to be much faster than using `struct.pack` and

Thank you for considering this proposal and any feedback is greatly

Juraj Sukop

[1] http://en.cppreference.com/w/c/numeric/math/nextafter
[2] http://stackoverflow.com/a/10426033
[3] http://git.musl-libc.org/cgit/musl/tree/src/math/nextafter.c
[5] https://github.com/golang/go/blob/master/src/math/nextafter.go
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170204/9a1f0c84/attachment.html>

More information about the Python-ideas mailing list