【发布时间】:2013-11-27 23:11:49
【问题描述】:
此问题仅适用于 Python 程序员。这个问题是not duplicate not working Increment a python floating point value by the smallest possible amount 见底部解释。
我想为任何浮点数添加/减去一些最小值,这将改变这个浮点值大约mantissa/significant part 的一位。如何在纯 Python 中高效地计算这么小的数字。
例如我有这样的 x 数组:
xs = [1e300, 1e0, 1e-300]
生成最小值的功能是什么?所有断言都应该是有效的。
for x in xs:
assert x < x + smallestChange(x)
assert x > x - smallestChange(x)
考虑1e308 + 1 == 1e308,因为1 确实意味着0 用于尾数,所以`smallestChange' 应该是动态的。
纯 Python 解决方案将是最好的。
为什么这不是 Increment a python floating point value by the smallest possible amount 的重复项 - 两个简单的测试证明它的结果无效。
(1)Increment a python floating point value by the smallest possible amount区别没有回答问题:
Increment a python floating point value by the smallest possible amount 不工作试试这个代码:
import math
epsilon = math.ldexp(1.0, -53) # smallest double that 0.5+epsilon != 0.5
maxDouble = float(2**1024 - 2**971) # From the IEEE 754 standard
minDouble = math.ldexp(1.0, -1022) # min positive normalized double
smallEpsilon = math.ldexp(1.0, -1074) # smallest increment for doubles < minFloat
infinity = math.ldexp(1.0, 1023) * 2
def nextafter(x,y):
"""returns the next IEEE double after x in the direction of y if possible"""
if y==x:
return y #if x==y, no increment
# handle NaN
if x!=x or y!=y:
return x + y
if x >= infinity:
return infinity
if x <= -infinity:
return -infinity
if -minDouble < x < minDouble:
if y > x:
return x + smallEpsilon
else:
return x - smallEpsilon
m, e = math.frexp(x)
if y > x:
m += epsilon
else:
m -= epsilon
return math.ldexp(m,e)
print nextafter(0.0, -1.0), 'nextafter(0.0, -1.0)'
print nextafter(-1.0, 0.0), 'nextafter(-1.0, 0.0)'
Increment a python floating point value by the smallest possible amount 的结果无效:
>>> nextafter(0.0, -1)
0.0
应该是非零的。
>>> nextafter(-1,0)
-0.9999999999999998
应该是'-0.9999999999999999'。
(2) 没有询问如何加/减最小值,而是询问如何在特定方向上加/减值 - 建议解决方案需要知道 x 和 y。这里只需要知道x。
(3) Increment a python floating point value by the smallest possible amount 中提出的解决方案不适用于边界条件。
【问题讨论】:
-
如果您关心这一点,那么您可能在 numpy 非常有帮助的领域工作。
numpy.nextafter对你有用吗?您可以使用numpy.nextafter(x, numpy.inf)始终保持积极态度。 -
我不想使用 numpy 来减少内存占用,但可能需要学习 numpy 代码来提取小函数。我更喜欢使用简单的 python 模块。
-
减少内存占用?在我的机器上导入 NumPy 只需要大约 8 MB。你在写什么样的程序?
-
当然对于简单的 PC 没关系我会使用 GAE 一些额外的 +8Mb 将花费和加载时间会更长 - 这是不同的规模你不能知道这一点 :) 如果我将使用 PC我不会像你一样在乎......
标签: python python-2.7