浮点数的紧凑格式 [英] Compact format for floating-point numbers

查看:162
本文介绍了浮点数的紧凑格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有特殊格式(base-128),用于传输 protobufs中使用的整数其他地方。当大多数整数很小时,它们是有利的(对于最小的数字,它们需要一个字节,并且可能会浪费一个字节给他人)。

There are special formats (base-128) designed for transmitting integers used in protobufs and elsewhere. They're advantageous when most the integers are small (they need a single byte for smallest numbers and may waste one byte for others).

我想知道是否有类似的东西浮点数假设大多数实际上是小整数?

I wonder if there's something similar for floating point numbers under the assumption that most of them are actually small integers?

为了解决爱丽丝的答案:我正在考虑像

void putCompressedDouble(double x) {
    int n = (int) x;
    boolean fits = (n == x);
    putBoolean(fits);
    if (fits) {
        putCompressedInt(n);
    } else {
        putUncompressedLong(Double.doubleToLongBits(x));
    }
}

这有效(除了负零,我真的不在乎),但是在符合== true 的情况下是浪费的。

This works (except for the negative zero, which I really don't care about), but it's wasteful in case of fits == true.

推荐答案

这取决于你的数字的分布。大小并不重要,因为它通过一个浮点数的指数字段表示。它通常是在存储方面贡献最大的重量的尾数。

It depends on the distribution of your numbers. Magnitude doesn't really matter that much, since its expressed through the exponent field of a float. Its usually the mantissa that contributes the most "weight" in terms of storage.

如果你的浮点主要是整数,你可以通过转换成int(通过Float获得)。 floatToIntBits()),并检查有多少个零(有小的int值应该有最多23个尾随零)。当使用简单的方案来编码小int时,可以简单地实现编码浮点数:

If your floats are mainly integers, you may gain something by converting to int (via Float.floatToIntBits()), and checking how many trailing zeros there are (for small int values there should be up to 23 trailing zeros). When using a simple scheme to encode small int's, you may implement encoding floats simply as:

int raw = Float.floatToIntBits(f);
raw = Integer.reverse(raw);
encodeAsInt(raw);

(解码只是逆转进程)。
这样做只是将尾数中的尾随零移动到int表示的最高有效位,这对于小整数设计的编码方案很友好。

(Decoding is simply reversing the process). What this does is simply move the trailing zeros in the mantissa to the most significant bits of the int representation, which is friendly to encoding schemes devised for small integers.

同样可以应用于double< - > long。

Same can be applied to double<->long.

这篇关于浮点数的紧凑格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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