Alex Rivera | Logout

How do you get the next value in the floating-point sequence?

Asked 2012-05-02T20:05:42.493
16

Does Python provide a function to get the floating-point value that results from incrementing the least significant bit of an existing floating-point value?

I'm looking for something similar to the std::nextafter function that was added in C++11.

Edit
Report

1 Answer

2

UPDATE:

Turns out this is a duplicate question (which comes up in google as result #2 for the search "c++ nextafter python"): Increment a python floating point value by the smallest possible amount

The accepted answer provides some solid solutions.

ORIGINAL ANSWER:

Certainly this isn't the perfect solution but using cython just a few lines will allow you to wrap the existing C++ function and use it in Python. I've compiled the below code and it works on my ubuntu 11.10 box.

First, a .pyx file (I called mine nextafter.pyx) defines your interface to the C++:

cdef extern from "cmath":
    float nextafter(float start, float to)

def pynextafter(start, to):
    cdef float float_start = float(start)
    cdef float float_to = float(to)
    result = nextafter(start, to)
    return result

Then a setup.py defines how to build the extension:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext 

ext_modules=[
    Extension("nextafter",
        ["nextafter.pyx"],
        libraries=[],
        library_dirs=[],
        include_dirs=[],
        language="c++",
    )
]

setup(
    name = "nextafter",
    cmdclass = {"build_ext": build_ext},
    ext_modules = ext_modules
)

Make sure those are in the same directory then build with python setup.py build_ext --inplace. I hope you can see how you would add the other variations of nextafter to the extension (for doubles, etc...). Once built, you should have a nextafter.so. Fire up python in the same directory (or put nextafter.so on your path somewhere) and you should be able to call from nextafter import pynextafter.

Enjoy!

answered 2012-05-02T20:19:23.543

Your Answer