Next floating point number

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Dec 17 18:43:30 EST 2005


On Sat, 17 Dec 2005 03:27:11 -0500, Tim Peters wrote:

> While the C99 standard defines such a function (several, actually),
> the C89 standard does not, so Python can't rely on one being
> available.  In general, Python's `math` module exposes only standard
> C89 libm functions, plus a few extras it can reliably and portably
> build itself on top of those.  It does not expose platform-specific
> libm functions.  You can argue with that policy, but not successfully
> unless you take over maintenance of mathmodule.c <0.5 wink>.

*rueful smile*


>> So I came up with a pure Python implementation, and hoped that somebody
>> who had experience with numerical programming in Python would comment.
> 
> If you're happy with what you wrote, who needs comments ;-)  

Because I don't know _quite_ enough numeric programming to tell whether my
happiness is justified or just the happiness of somebody who hasn't
noticed the great big enormous bug staring him right in the face :-)


> Here's a
> careful, "kinda portable" implementation in C:
> 
>     http://www.netlib.org/toms/722
> 
> If you ignore all the end cases (NaNs, infinities, signaling underflow
> and overflow, ...), the heart of it is just adding/subtracting 1 to/from
> the 64-bit double representation, viewing it as an 8-byte integer.  That
> works fine for the IEEE-754 float representations (but does not work for
> all float representations).

Will Python always use 64-bit floats?

> I've used this simple routine based on that observation, which ignores
> all endcases, and only works if both input and result are >= 0:
> 
> """
> from struct import pack, unpack
> 
> def next(x, direction=+1):
>     bits = unpack(">Q", pack(">d", x))[0] return unpack(">d", pack(">Q",
>     bits + direction))[0]
> """

Nice! I played around with struct.pack and unpack using a format string of
"f", but didn't get anywhere, so thanks for this.



-- 
Steven.




More information about the Python-list mailing list