IEEE754 单精度 - 表示数字一半的通用算法

IEEE754 single precision - General algorithm for representing the half of a number

假设N是根据IEEE754单精度标准表示的任意数。我想在 IEEE754.

中再次找到 N/2 的最精确表示

我想找到一个通用算法(用文字描述,我只想考虑必要的步骤和情况)来获得表示。

我的方法是:

说的数字代表:b0_b1_b2_b3...b_34.

  1. 隔离确定数字符号 (-/+) 的第一位。
  2. 根据无符号表示计算幂 (p) 的表示 b_1...b_11
  3. 如果power = 128我们有一个特例。如果尾数的所有位都等于 0,则取决于 b_0,我们有负无穷大或正无穷大。我们不改变任何东西。如果尾数至少有一位等于 1,则我们有 NaN 值。同样,我们什么也没改变。
  4. if e is inside]-126, 127[then we have a normalized mantissa米。新幂 p can be calculated asp' = p - 1and belongs in the interval]-127, 126]. We then calculatem/2` 我们从右边开始表示它并丢失任何不能被包含在尾数的23位中。
  5. 如果e = -126,那么在计算这个数字的一​​半时,我们传入一个非规范化的尾数。我们表示p = 127,计算尾数的一半并从右边开始再次表示它丢失任何不能包含的信息。
  6. 最后如果 e = -127 我们有一个非规范化的尾数。只要 m/2 可以用尾数中可用的位数表示而不丢失信息,我们就表示并保留 p = -127。在任何其他情况下,我们将数字表示为正数或负数 0,具体取决于 b_0

我遗漏了任何步骤、可以进行的任何改进(我相信有)或任何看起来完全错误的地方?

我在 Java 中实现了除以二的算法,并针对所有 32 位输入对其进行了验证。我试图遵循您的伪代码,但在三个地方出现了分歧。首先,infinity/NaN 指数是 128。其次,在情况 4(正常 -> 正常)中,不需要对分数进行运算。第三,你没有描述当你对分数进行操作时,半圆是如何工作的。否则为 LGTM。

public final class FloatDivision {
  public static float divideFloatByTwo(float value) {
    int bits = Float.floatToIntBits(value);
    int sign = bits >>> 31;
    int biased_exponent = (bits >>> 23) & 0xff;
    int exponent = biased_exponent - 127;
    int fraction = bits & 0x7fffff;
    if (exponent == 128) {
      // value is NaN or infinity
    } else if (exponent == -126) {
      // value is normal, but result is subnormal
      biased_exponent = 0;
      fraction = divideNonNegativeIntByTwo(0x800000 | fraction);
    } else if (exponent == -127) {
      // value is subnormal or zero
      fraction = divideNonNegativeIntByTwo(fraction);
    } else {
      // value and result are normal
      biased_exponent--;
    }
    return Float.intBitsToFloat((sign << 31) | (biased_exponent << 23) | fraction);
  }

  private static int divideNonNegativeIntByTwo(int value) {
    // round half to even
    return (value >>> 1) + ((value >>> 1) & value & 1);
  }

  public static void main(String[] args) {
    int bits = Integer.MIN_VALUE;
    do {
      if (bits % 0x800000 == 0) {
        System.out.println(bits);
      }
      float value = Float.intBitsToFloat(bits);
      if (Float.floatToIntBits(divideFloatByTwo(value)) != Float.floatToIntBits(value / 2)) {
        System.err.println(bits);
        break;
      }
    } while (++bits != Integer.MIN_VALUE);
  }
}