与 numpy 打平局 [英] Tie breaking of round with numpy

查看:26
本文介绍了与 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:

  1. 使用 gmpy2,如此答案中所述.这使您可以完全控制舍入模式,但使用 gmpy2 进行简单的浮点数学运算可能比 NumPy 慢.
  2. 通过ctypes使用fesetround手动设置舍入模式.这是特定于系统的,因为常量可能因平台而异;检查 fenv.h 以获取平台上的常量值.在我的机器上(Mac OS X):

  1. Use gmpy2, as outlined in this answer. This gives you full control over the rounding mode, but using gmpy2 for simple float math is likely to be slower than NumPy.
  2. Use fesetround via ctypes to manually set the rounding mode. This is system-specific because the constants may vary by platform; check fenv.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆