将浮动转换为最小精度损失 [英] convert float to short with minimal loss of precision
问题描述
我有这个正弦波产生浮点值(例如0.37885),但我希望它们是短路。直接铸造与短给我的价值为0.那么是什么解决方案?
任何人都可以告诉我怎么做 - 理想情况下,没有精度损失 - 或损失最小的精度,如果这是所有可能的?
public static short floatToShort(float x){
if(x return Short.MIN_VALUE;
}
if(x> Short.MAX_VALUE){
return Short.MAX_VALUE;
}
return(short)Math.round(x);
}
您将失去小数部分:
float 4字节浮点数
双字节8字节浮点数(正常)
短2字节整数
int 4字节整数(普通)
长8字节整数
编辑: 可能你想知道如何将 float (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);
I have this sine wave which generates floating point values (e.g. 0.37885) but I want them as shorts. Direct casting with short gives me a value of 0. so what is the solution?
Can anyone tell me how to do it - ideally without loss of precision - or minimal loss of precision if this is all that is possible?
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);
}
You'll loose the fractional part:
float 4 byte floating-point
double 8 byte floating-point (normal)
short 2 byte integer
int 4 byte integer (normal)
long 8 byte integer
Edit:
Maybe you wanted to know how to save the bits of a float (4 bytes) into an int (4 bytes): (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);
这篇关于将浮动转换为最小精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!