我是靠谱客的博主 舒心老虎,最近开发中收集的这篇文章主要介绍舍入模式(rounding mode),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一看到舍入,不知道你是否想到了四舍五入,进而想到取整,注意,这是两个概念。

取整是指取一个有理数的整数部分,而这里介绍的舍入模式是和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.

 

最后

以上就是舒心老虎为你收集整理的舍入模式(rounding mode)的全部内容,希望文章能够帮你解决舍入模式(rounding mode)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部