您的位置:首页 > 其它

舍入模式(rounding mode)

2010-01-21 15:13 302 查看
一看到舍入,不知道你是否想到了四舍五入,进而想到取整,注意,这是两个概念。

取整是指取一个有理数的整数部分,而这里介绍的舍入模式是和cpu内部浮点处理相

关的,是指对结果的截取。

首先,我们简要介绍一下单精度浮点数的表示:

bit 31 30-23 22-0

含义 符号 指数 尾数

具体介绍请参看http://en.wikipedia.org/wiki/Floating_point

我们知道,浮点数能够表示的精度有限,其实只有23个有效位,但是注意,这个是

表示上,或者说存储上,但是实际在cpu里不是这样的,记得80bit的long double

吗?与其相似,float在cpu内部计算的时候也会有“额外精度”。

如果得到一个浮点计算结果(2进制),例如:

a=1.0001 0000 1000 0011 1001 0111

注意,它有24个小数位,那么我们取两个数b和c,满足b<a<c

b=1.0001 0000 1000 0011 1001 011

c=1.0001 0000 1000 0011 1001 100

最后的结果就从这两个里面取,具体取哪个,取决于舍入模式的设置。

Round to nearest (even)

Rounded result is the closest to the infinitely precise result. If two

values are equally close, the result is the even value (that is, the

one with the least-significant bit of zero).

Round down (toward −∞)

Rounded result is closest to but no greater than the infinitely

precise result.

Round up (toward +∞)

Rounded result is closest to but no less than the infinitely precise

result.

Round toward zero (Truncate)

Rounded result is closest to but no greater in absolute value than

the infinitely precise result.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: