Next float?

S

Steven D'Aprano

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.
 
A

Alex Holkner

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).

Not so elegant, but you could use ctypes to manipulate the bits
(assumes machine uses IEEE 754 doubles for Python floats, I'm not sure
if that's guaranteed on esoteric platforms):

import ctypes

def inc_float(f):
# Get an int64 pointer to the float data
fv = ctypes.c_double(f)
pfv = ctypes.pointer(fv)
piv = ctypes.cast(pfv, ctypes.POINTER(ctypes.c_uint64))

# Check for NaN or infinity, return unchanged
v = piv.contents.value
if not ~(v & (11 << 52)): # exponent is all 1's
return f

if v == 1 << 63: # -0, treat as +0
v = 1
elif v & (1 << 63): # negative
v -= 1
else: # positive or +0
v += 1

# Set int pointer and return changed float
piv.contents.value = v
return fv.value

def dec_float(f):
# Get an int64 pointer to the float data
fv = ctypes.c_double(f)
pfv = ctypes.pointer(fv)
piv = ctypes.cast(pfv, ctypes.POINTER(ctypes.c_uint64))

# Check for NaN or infinity, return unchanged
v = piv.contents.value
if not ~(v & (11 << 52)): # exponent is all 1's
return f

if v == 0: # +0, treat as -0
v = (1 << 63) | 1
elif v & (1 << 63): # negative
v += 1
else: # positive
v -= 1

# Set int pointer and return changed float
piv.contents.value = v
return fv.value
 
M

Mark T

Steven D'Aprano said:
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.

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]
0.99999994039535522

-Mark
 
P

Paul Rubin

Steven D'Aprano said:
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.

I think you have to do it by bit twiddling. But something like bisection
search could come pretty close, for well-behaved values of x:

def nextfloat(x):
dx = (x, x/2.0)
while x+dx[1] != x:
dx = (dx[1], dx[1]/2.0)
return dx[0]+x
 
R

Robert Kern

Steven said:
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.

Courtesy of Tim Peters:

http://mail.python.org/pipermail/python-list/2001-August/099152.html
Bonus points if I can go in either direction (i.e. the "previous float"
as well as the next).

Left as an exercise for the reader. :)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
R

Robert Kern

Steven said:
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.

Heh:

http://mail.python.org/pipermail/python-list/2005-December/357771.html

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
F

Fredrik Johansson

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.

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:
0.99999999999999989

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

Fredrik
 
M

Mark Dickinson

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]

0.99999994039535522

And it's worth noting that thanks to the way the floating-point format
is designed, the 'bit-twiddling' is actually just a matter of adding
or subtracting one from the integer representation above. This works
all the way from zero, through subnormals, up to and including
infinities.

Mark (but not the same Mark)
 
M

Mark Dickinson

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]
0.99999994039535522

And it's worth noting that thanks to the way the floating-point format
is designed, the 'bit-twiddling' is actually just a matter of adding
or subtracting one from the integer representation above. This works
all the way from zero, through subnormals, up to and including
infinities.

Mark (but not the same Mark)

And also worth noting that the 'f's above should probably be 'd's.
For example, the following works on my machine for positive floats.
Fixing this for negative floats is left as a not-very-hard exercise...
from struct import pack, unpack
def next_float(x): return unpack('d', pack('q', unpack('q', pack('d', x))[0]+1))[0] ....
next_float(1.0)
1.0000000000000002

Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top