将float转换为short以最小的精度损失

use*_*530 4 java floating-point short

我有这个正弦波产生浮点值(例如0.37885),但我希望它们作为短路.短流程直接铸造给我的值为0.那么解决方案是什么?

任何人都可以告诉我如何做到这一点 - 理想情况下不会损失精确度 - 或者如果可能的话,最小的精度损失最小化?

Joo*_*gen 7

public static short floatToShort(float x) {
    if (x < Short.MIN_VALUE) {
        return Short.MIN_VALUE;
    }
    if (x > Short.MAX_VALUE) {
        return Short.MAX_VALUE;
    }
    return (short) Math.round(x);
}
Run Code Online (Sandbox Code Playgroud)

你将失去小数部分:

float    4 byte floating-point
double   8 byte floating-point (normal)
short    2 byte integer
int      4 byte integer (normal)
long     8 byte integer
Run Code Online (Sandbox Code Playgroud)

编辑:

也许你想知道如何将一个浮点数(4个字节)保存到一个int(4个字节):( http://docs.oracle.com/javase/7/docs/api/java/lang/Float. html #floatToRawIntBits(float))

float x = 0.1f;
int n = Float.floatToRawIntBits(x);
float y = Float.intBitsToFloat(n);
Run Code Online (Sandbox Code Playgroud)


Arw*_*win 6

原则上,你可以将它乘以100000,将其转换为int,然后减去-32,767并将其转换为short.如果仍然在所有值的-32,767到32,767范围内,那么这可能是你能做到的最好的.否则,您必须限制精度并乘以10000.

当你使用短路时,你必须记住把它分开.