`
hellobin
  • 浏览: 62887 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

IEEE浮点数舍入(四舍六入五成双)

 
阅读更多
浮点数舍入相比向整数舍入,就复杂一些,IEEE定义了四种不同的舍入方式,默认的为向偶数舍入(round-to-even)。其他三个分别是向零舍入,向上舍入和向下舍入。
 
其他三个比较直观,就不再说明,以十进制为例说明“向偶数舍入”,平常的四舍五入中,以舍入到小数点后两位为例,如果第3位小数小于5,则舍去,大于等于5的则进1。向偶数舍入除了最中间的这个值(第3位小数为5)以外,其他与平常的舍入相同,中间的这个值,则要保证在舍入的时候舍入位必须为偶数。比如1.40, 1.60, 1.50, 2.50, -1.50向偶数舍入的结果分别为1, 2, 2, 2, -2
 
至于为什么要想偶数舍入,这是CSAPP(2e)中的原文:
 
[plain] view plaincopyprint?
 
  1. The problem with such a convention is that one can easily imagine scenarios   
  2. in which rounding a set of data values would then introduce a statistical bias   
  3. into the computation of an average of the values. The average of a set of numbers   
  4. that we rounded by this means would be slightly higher than the average of   
  5. the numbers themselves. Conversely, if we always rounded numbers halfway   
  6. between downward, the average of a set of rounded numbers would be   
  7. slightly lower than the average of the numbers themselves. Rounding toward   
  8. even numbers avoids this statistical bias in most real-life situations.   
  9. It will round upward about 50% of the time and round downward about 50% of the time.  
也就是如果在一组数据中,向偶数舍入一般既有向上舍入也有向下舍入,可以一定程度上消除统计平均数时由于总是向上舍入时所带来的统计偏差。
 
扩展成二进制,就是对形如 XX···X.YY···Y100···二进制模式位的数(最右边的Y是要舍入的位置),根据舍入位是否为偶数来选择是向上舍入还是向下舍入。(至于为什么是100,我还没想明白)
比如10.010, 10.011, 10.110, 11.001向偶数舍入(保留小数点后一位)的结果分别为10.0, 10.1, 11.0, 11.0。
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics