用numpy打成一团 [英] Tie breaking of round with numpy

查看:92
本文介绍了用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天全站免登陆