将浮点范围转换/量化到整数范围 [英] Convert/Quantize Float Range to Integer Range
问题描述
显而易见的解决方案如下所示: 如果我做适当的四舍五入,我只是改变了这个问题: 这里的结果 如何在浮点范围的均匀分布下进行量化?理想情况下,如果我量化均匀分布的随机花车,我希望得到一个平均分布的整数。
<$ (unsigned char)(a * 255.0f); p $ p> 无符号字符QuantizeFloat(float a)
{
$ b $ p
$ b这个工作到目前为止,我得到的所有数字从0到255,但整数的分布是不均匀的。如果a正好是 1.0f
,那么函数只返回 255
。不是一个好的解决方案。
unsigned char QuantizeFloat(float a)
{
return(unsigned char)(a * 255.0f + 0.5f);
$ / code> 0
只覆盖浮点范围的一半,而不是任何其他数字。
有什么想法吗?
< hr>
btw:另外我的代码是在C这个问题是语言不可知的。对于非C人员:假设 float
为 int
转换会截断浮点数。
编辑:因为我们在这里有一些困惑:我需要一个映射,将最小的输入float(0)映射到最小的unsigned char, (1.0f)到最高的无符号字节(255)。
如何 a * 256f
检查减少256到255?例如:
$ b $ pre $ return(unsigned char)(min(255,(int)(a * 256f)));
(对于你平台上的一个合适的min函数 - 我不记得它的C函数。 )
基本上你想把范围分成256等份,这就是应该做的。 1.0到256的边界情况,要求舍去只是因为域包含在两端。
Say I have a float in the range of [0, 1] and I want to quantize and store it in an unsigned byte. Sounds like a no-brainer, but in fact it's quite complicated:
The obvious solution looks like this:
unsigned char QuantizeFloat(float a)
{
return (unsigned char)(a * 255.0f);
}
This works in so far that I get all numbers from 0 to 255, but the distribution of the integers is not even. The function only returns 255
if a is exactly 1.0f
. Not a good solution.
If I do proper rounding I just shift the problem:
unsigned char QuantizeFloat(float a)
{
return (unsigned char)(a * 255.0f + 0.5f);
}
Here the the result 0
only covers half of the float-range than any other number.
How do I do a quantization with equal distribution of the floating point range? Ideally I would like to get a equal distribution of integers if I quantize equally distributed random floats.
Any ideas?
Btw: Also my code is in C the problem is language-agnostic. For the non-C people: Just assume that float
to int
conversion truncates the float.
EDIT: Since we had some confusion here: I need a mapping that maps the smallest input float (0) to the smallest unsigned char, and the highest float of my range (1.0f) to the highest unsigned byte (255).
How about a * 256f
with a check to reduce 256 to 255? So something like:
return (unsigned char) (min(255, (int) (a * 256f)));
(For a suitable min function on your platform - I can't remember the C function for it.)
Basically you want to divide the range into 256 equal portions, which is what that should do. The edge case for 1.0 going to 256 and requiring rounding down is just because the domain is inclusive at both ends.
这篇关于将浮点范围转换/量化到整数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!