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

本文详细解释了浮点数舍入中的向偶数舍入方式,包括其原理和应用,通过举例说明如何在二进制下进行向偶数舍入,以及它在消除统计平均数偏差上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

浮点数舍入相比向整数舍入,就复杂一些,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 plain copy print ?
 
  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。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值