473,387 Members | 1,863 Online

# Next float?

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
Nov 22 '07 #1
10 2998
On Nov 22, 2007 2:04 PM, Steven D'Aprano
<st****@remove.this.cybersource.com.auwrote:
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
Nov 22 '07 #2

"Steven D'Aprano" <st****@REMOVE.THIS.cybersource.com.auwrote in message
news:pa*********************@REMOVE.THIS.cybersour ce.com.au...
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
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]
>>f2b(1.0)
1065353216
>>hex(f2b(1.0))
'0x3f800000'
>>b2f(0x3f800000)
1.0
>>b2f(0x3f800001)
1.0000001192092896
>>b2f(0x3f7fffff)
0.99999994039535522

-Mark

Nov 22 '07 #3
Steven D'Aprano <st****@REMOVE.THIS.cybersource.com.auwrites:
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
Nov 22 '07 #4
Steven D'Aprano 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.
Courtesy of Tim Peters:

http://mail.python.org/pipermail/pyt...st/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
an underlying truth."
-- Umberto Eco

Nov 22 '07 #5
Steven D'Aprano 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.
Heh:

http://mail.python.org/pipermail/pyt...er/357771.html

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
an underlying truth."
-- Umberto Eco

Nov 22 '07 #6
On Thu, 22 Nov 2007 00:44:34 -0600, Robert Kern wrote:
Steven D'Aprano 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.

Heh:

http://mail.python.org/pipermail/pyt...er/357771.html
Damn, I don't remember writing that!

:-/

--
Steven.
Nov 22 '07 #7
On Nov 22, 2007 4:04 AM, Steven D'Aprano
<st****@remove.this.cybersource.com.auwrote:
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
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
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
Nov 22 '07 #8
On Nov 21, 11:48 pm, "Mark T" <nos...@nospam.comwrote:
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]
>f2b(1.0)
1065353216
>hex(f2b(1.0))
'0x3f800000'
>b2f(0x3f800000)
1.0
>b2f(0x3f800001)
1.0000001192092896
>b2f(0x3f7fffff)

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)
Nov 22 '07 #9
On Nov 22, 5:41 pm, Mark Dickinson <dicki...@gmail.comwrote:
On Nov 21, 11:48 pm, "Mark T" <nos...@nospam.comwrote:
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]
>>f2b(1.0)
1065353216
>>hex(f2b(1.0))
'0x3f800000'
>>b2f(0x3f800000)
1.0
>>b2f(0x3f800001)
1.0000001192092896
>>b2f(0x3f7fffff)
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
Nov 22 '07 #10
"Steven D'Aprano" <steve..IS.cybersource.com.auwrote:

Damn, I don't remember writing that!
It is caused by drinking too much Alzheimer's Light.

: - )

- Hendrik

Nov 23 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

### Similar topics

 10 by: george | last post by: Can anyone help? I query a database and return a result on the column "reference". There might be 7 listings. Each row is displayed in a table, with links through to a detail page. I am working... 3 by: David Ross | last post by: I sometimes place a sidebar on a Web page, using the following: ..sideright { float: right; background-color: #fff; width: 40%; font-size: 90%; text-align: justify; margin-left: 1em;... 13 by: Peter Ammon | last post by: I have a floating point number. I'd like to get the nearest floating point number that is larger or smaller than the given number. I investigated FLT_EPSILON but it only seems to be useful if the... 9 by: Steven D'Aprano | last post by: I'm looking for some way to get the next floating point number after any particular float. (Any mathematicians out there: I am aware that there is no "next real number". But floats are not real... 22 by: ashkaan57 | last post by: Hi, I am trying to put text on left and right side of the page and used:
blah blah blah blah
The 2nd text does go to the right but the... 6 by: Harlan Messinger | last post by: Please take a look at http://www.gavelcade.com/list_next_to_float.html How can I style a list so that if it appears next to a left-floated box as the first list does in this example, the list... 0 by: removeps-groups | last post by: Now I'm wondering how to display 3 elements next to each other. I came up with the following solution using float:left, but would like opinions if this is the right way to go. The idea is to... 15 by: dlite922 | last post by: I'm back again, Intro: I've got a floating div (outerDIV) with fixed width that contains an image (IMG) and a div that contains a short text (innerDIV) Problem: In FF, the innerDIV is... 5 by: p309444 | last post by: Hi. I have an application in which the user can select a location and view it's distance from several Points Of Interests (POIs). When I retrieve these distances, I would also like to retrieve... 0 by: taylorcarr | last post by: A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,... 0 by: Charles Arthur | last post by: How do i turn on java script on a villaon, callus and itel keypad mobile phone 0 by: aa123db | last post by: Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function \$name\$ (\$parameters\$) { } ... 0 by: ryjfgjl | last post by: If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming... 0 by: emmanuelkatto | last post by: Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel 1 by: Sonnysonu | last post by: This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to... 0 by: marktang | last post by: ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,... 0 by: Hystou | last post by: Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can... 0 by: jinu1996 | last post by: In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...