为了在将双打加在一起时保持精度,您需要使用Kahan Summation,这是相当于有一个进位寄存器的软件。
这对于大多数值来说都很好,但是如果您遇到溢出,那么您将达到IEEE 754 双精度的限制,大约是。此时您需要一个新的表示。您可以在加法时检测溢出 by ,也可以检测到大的指数以评估 by 。此时,您可以通过移动指数并跟踪此移动来修改双精度数的解释。e709.783doubleMax - sumSoFar < valueToAddexponent > 709.783
这在很大程度上类似于您的指数偏移方法,但此版本以 2 为底,不需要初始搜索即可找到最大指数。因此。value×2shift
#!/usr/bin/env python
from math import exp, log, ceil
doubleMAX = (1.0 + (1.0 - (2 ** -52))) * (2 ** (2 ** 10 - 1))
def KahanSumExp(expvalues):
  expvalues.sort() # gives precision improvement in certain cases 
  shift = 0 
  esum = 0.0 
  carry = 0.0 
  for exponent in expvalues:
    if exponent - shift * log(2) > 709.783:
      n = ceil((exponent - shift * log(2) - 709.783)/log(2))
      shift += n
      carry /= 2*n
      esum /= 2*n
    elif exponent - shift * log(2) < -708.396:
      n = floor((exponent - shift * log(2) - -708.396)/log(2))
      shift += n
      carry *= 2*n
      esum *= 2*n
    exponent -= shift * log(2)
    value = exp(exponent) - carry 
    if doubleMAX - esum < value:
      shift += 1
      esum /= 2
      value /= 2
    tmp = esum + value 
    carry = (tmp - esum) - value 
    esum = tmp
  return esum, shift
values = [10, 37, 34, 0.1, 0.0004, 34, 37.1, 37.2, 36.9, 709, 710, 711]
value, shift = KahanSumExp(values)
print "{0} x 2^{1}".format(value, shift)