如果我将epsilon
作为最小的正非零浮点数(无论是16
,32
还是64
位)并乘以{{1通过相同大小的非零浮点值:
我保证相同符号的非零结果 与原始 值?或者我冒险舍入错误(零或切换标志)?
环境:Python / Numpy
答案 0 :(得分:8)
没有
In [1]: import numpy
In [2]: x = numpy.nextafter(0, 1)
In [3]: x
Out[3]: 4.9406564584124654e-324
In [4]: x*x
Out[4]: 0.0
当精确结果介于0和最小正浮点数之间时,它必须舍入到其中一个选项,在这种情况下,0更接近。
如果由于某种原因您想要自定义此行为,NumPy允许您使用numpy.seterr
自定义下溢和其他IEEE 754浮点异常的行为,尽管它不会影响对普通Python对象的操作:< / p>
In [5]: numpy.seterr(under='raise')
Out[5]: {'divide': 'warn', 'invalid': 'warn', 'over': 'warn', 'under': 'ignore'}
In [6]: x # NumPy float, not regular float, despite its looks
Out[6]: 4.9406564584124654e-324
In [7]: x*x
---------------------------------------------------------------------------
FloatingPointError Traceback (most recent call last)
<ipython-input-7-a3ff2a28c75d> in <module>()
----> 1 x*x
FloatingPointError: underflow encountered in double_scalars
In [8]: (4.9406564584124654e-324)**2 # regular float
Out[8]: 0.0
无法更改舍入模式。
答案 1 :(得分:7)
当然不是,而且epsilon与它没什么关系。例如,
>>> x = 1e-200
>>> x
1e-200
远离epsilon,但
>>> x * x
0.0
下溢到0.如果我们实际上使用了epsilon,那么,例如,将它乘以0.25也会下溢到0。
如果你的平台C编译器和硬件支持754标准,那么零的符号将与被乘数的符号匹配:
>>> x * -x
-0.0