用numpy打成一团 [英] Tie breaking of round with numpy
问题描述
标准的numpy圆形平局打破遵循IEEE 754约定,将一半舍入到最接近的偶数.有没有一种方法可以指定不同的舍入行为,例如向零或向-inf四舍五入?我不是在谈论天花板或地板,我只需要打破常规即可.
Standard numpy round tie breaking is following IEEE 754 convention, to round half towards the nearest even number. Is there a way to specify different rounding behavior, e.g. round towards zero or towards -inf? I'm not talking about ceil or floor, I just need different tie breaking.
推荐答案
NumPy对内部舍入模式没有任何控制.这有两种选择:
NumPy doesn't give any control over the internal rounding mode. Here's two alternatives:
- 使用
gmpy2
,如此答案所述.这样可以完全控制舍入模式,但是使用gmpy2
进行简单的浮点数学运算可能会比NumPy慢. -
通过
ctypes
使用fesetround
手动设置舍入模式.这是特定于系统的,因为常量可能随平台而有所不同.在平台上检查fenv.h
的常量值.在我的计算机上(Mac OS X):
- Use
gmpy2
, as outlined in this answer. This gives you full control over the rounding mode, but usinggmpy2
for simple float math is likely to be slower than NumPy. Use
fesetround
viactypes
to manually set the rounding mode. This is system-specific because the constants may vary by platform; checkfenv.h
for the constant values on your platform. On my machine (Mac OS X):
import numpy as np
import ctypes
FE_TONEAREST = 0x0000
FE_DOWNWARD = 0x0400
FE_UPWARD = 0x0800
FE_TOWARDZERO = 0x0c00
libc = ctypes.CDLL('libc.dylib')
v = 1. / (1<<23)
print repr(np.float32(1+v) - np.float32(v/2)) # prints 1.0
libc.fesetround(FE_UPWARD)
print repr(np.float32(1+v) - np.float32(v/2)) # prints 1.0000002
这篇关于用numpy打成一团的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!