How do you find the largest float below some value?

Viewed 116

Given a float x, I would like to find the largest floating point number that is less than x. How can I do this in Python?

I've tried subtracting machine epsilon from x (x - numpy.finfo(float).eps), but this evaluates to x for sufficiently large floats, and I need the value I get back to be strictly less than x.

There's some information about how to do this in C# here, but I have no idea how to do the same bitwise conversion in Python. Anybody know how to do this, or have another method for getting the same value?

(Bigger-picture problem -- I'm trying to numerically find the root of an equation with a singularity at x, within the bounds 0 < root < x. The solver (Scipy's toms748 implementation) evaluates on the boundaries, and it can't handle nan or inf values, so I can't give it exactly x as a bound. I don't know how close the root might be to the bound, so I want to give a bound as close to x as possible without actually producing an infinite value and crashing the solver.)

1 Answers

You are describing the basic usage of numpy.nextafter.

>>> import numpy as np
>>> np.nextafter(1.5, 0.0)  # biggest float smaller than 1.5
1.4999999999999998
>>> np.nextafter(1.5, 2.0)  # smallest float bigger than 1.5
1.5000000000000002
Related