如何使用浮点数执行舍入到偶数 [英] How to perform round to even with floating point numbers

查看:24
本文介绍了如何使用浮点数执行舍入到偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 IEEE-754 单精度浮点,您如何执行舍入到最接近,其中将舍入到所需位置中最近的偶数(默认和迄今为止最常见的模式)?

In regards to IEEE-754 single precision floating point, how do you perform round to nearest, where ties round to the nearest even digit in the required position (the default and by far the most common mode)?

基本上我有保护位、圆形位和粘性位.因此,如果我们将它们形成一个向量并将其称为 GRS,则适用以下规则:

Basically I have the guard bit, round bit, and sticky bit. So if we form those into a vector and call it GRS, then the following rules apply:

  1. 如果 G = 0,向下取整(什么都不做)
  2. 如果 G = 1,并且 RS == 10RS == 01,则向上取整(尾数加一)
  3. 如果GSR = 111,四舍五入
  1. If G = 0, round down (do nothing)
  2. If G = 1, and RS == 10 or RS == 01, round up (add one to mantissa)
  3. if GSR = 111, round to even

所以我不确定如何进行最接近的舍入.非常感谢任何帮助.

So I am not sure how to perform the round to nearest. Any help is greatly appreciated.

推荐答案

为了确保我们在同一个页面上,G 是三个中最重要的位,R 紧随其后,而 S 可以被认为是最低有效位,因为它的值部分地代表了在计算中被截断的甚至更不重要的位.这三位仅在计算时使用,在计算前后不存储在浮点变量中.

Just to make sure we're on the same page, G is the most significant bit of the three, R comes next and S can be thought of as the least significant bit because its value partially represents the even less significant bits that have been truncated in the calculations. These three bits are only used while doing calculations and aren't stored in the floating-point variable before or after the calculations.

为了使用 GRS 将结果四舍五入到最接近的偶数,您应该这样做:

This is what you should do in order to round the result to the nearest even number using G, R and S:

GRS - 动作
0xx - 向下舍入 = 什么都不做(x 表示任何位值,0 或 1)
100 - 这是一个平局:如果 G 之前的尾数位为 1,则向上取整,否则向下取整=什么都不做
101 - 向上取整
110 - 向上取整
111 - 向上取整

GRS - Action
0xx - round down = do nothing (x means any bit value, 0 or 1)
100 - this is a tie: round up if the mantissa's bit just before G is 1, else round down=do nothing
101 - round up
110 - round up
111 - round up

四舍五入是通过在尾数的最低有效位位置的尾数上加 1 来完成的,就在 G 之前.如果尾数溢出(您将存储的 23 个最低有效位变为零),您必须将 1 添加到指数.如果指数溢出,则根据数字的符号将数字设置为 +infinity 或 -infinity.

Rounding up is done by adding 1 to the mantissa in the mantissa's least significant bit position just before G. If the mantissa overflows (its 23 least significant bits that you will store become zeroes), you have to add 1 to the exponent. If the exponent overflows, you set the number to +infinity or -infinity depending on the number's sign.

在平局的情况下,如果尾数为奇数,则尾数加 1,如果尾数为偶数,则不加任何内容.这就是使结果四舍五入到最接近的偶数值的原因.

In the case of a tie, you add 1 to the mantissa if the mantissa is odd and you add nothing if it's even. That's what makes the result rounded to the nearest even value.

这篇关于如何使用浮点数执行舍入到偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆