<p>为什么不用对数呢?在</p>
<p>您需要计算:</p>
<pre><code>RESULT = x1 * x2 * x3 * x4 ... * xn
</code></pre>
<p>表示为:</p>
^{pr2}$
<p>如果存储自然对数,非常小的正数可以很好地存储到浮点数中:</p>
^{3}$
<p>不是存储数字本身,而是存储值的日志。在</p>
<p>假设您向自身添加<code>ln(0.0000011)</code>次。你得到大约<code>-13815510.558</code>。与<code>float</code>相比,作为<code>float</code>丢失的精度更小</p>
<p>不管你最后得到的是什么数字,你知道你的结果就是<code>e</code>的幂次。例如,<code>RESULT = e^-13815510.558</code></p>
<p>您可以使用以下代码:</p>
<pre><code>import math
class TinyNum:
def __init__(self, other=None, *, pow=None):
"""
x = TinyNum(0.0000912922)
x = TinyNum("0.12345") # strings are okay too
x = TinyNum(pow = -110) # e^-110
y = TinyNum(x) # copy constructor
"""
if other:
if isinstance(other, type(self)):
self._power = other._power
else:
self._power = math.log(float(str(other)))
else: # other == None
self._power = float(str(pow))
def __str__(self):
return "e^"+str(self._power)
def __mul__(lhs, rhs):
rhs = type(lhs)(rhs)
return type(lhs)(pow=lhs._power + rhs._power)
def __rmul__(rhs, lhs):
lhs = type(rhs)(lhs)
return type(rhs)(pow=lhs._power + rhs._power)
def __imul__(total, margin):
total._power = total._power + type(total)(margin)._power
lyst = [
0.00841369,
0.004766949,
0.003188046,
0.002140916,
0.004780032
]
sneaky_lyst = map(TinyNum, lyst)
print(math.prod(sneaky_lyst))
</code></pre>
<p>打印到控制台的消息是:</p>
<pre><code>e^-27.36212057035477
</code></pre>