为什么浮动溢出

时间:2017-05-18 08:45:22

标签: python floating-point python-3.5

据我所知,浮点数的精度有限。但我不明白为什么64位浮点数(我假设这些浮点数)会溢出这些值:

ipdb> (-1e+10 - 0.01)
-10000000000.01  # 0.01 still visible
ipdb> (-1e+20 - 0.01)
-1e+20  # 0.01 is gone, I assume because of floating point precision 

这可能是相关的:

ipdb> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

请注意,我想要解决的实际问题是将这些值规范化为0到1之间[-1.3229999632394e+32, 15000.0, -11.432000160217285, -11.321000099182129]

1 个答案:

答案 0 :(得分:0)

通常不需要具备这种精确度,但有些包可以为您完成,例如Bigfloat

from bigfloat import *

print (-1e+20 - 0.01) == -1e20

with precision(64*2):
    a = BigFloat.exact(-1e+20)
    b = BigFloat.exact(0.01)
    print a == b

将输出:

True
False

缩放也有效

来自bigfloat导入精度,BigFloat

listy = [-1.3229999632394e+32, 15000.0, -11.432000160217285, -11.321000099182129]
m = min(listy) #do this before import, as BigFloat
M = max(listy)

with precision(128):
    scale = lambda x : (x-BigFloat(m)) / (BigFloat(M)-BigFloat(m))
    print [ scale(BigFloat(i)) for i in listy ]