问题描述
我有一个输入浮点值是0.0f< =值< 1.0f(注意小于1)。当把这个值乘上一个更大的范围时,浮点精度自然会下降,这意味着这个值最终会超出等价范围。
例如,如果我从一个值开始,例如:
0.99999983534521f
>然后乘以100,得到:
100.000000000000f
这是好的,但是我怎样才能减少浮点表示成为最接近的浮点值仍然小于100?
我发现这个小手工诀窍:
$ $ $
$ b $
浮动浮动;
};
测试值;
value.floating = 1.0f;
printf(%x\\\
,value.integer);
然后我把这个十六进制值减一十六进制数字,然后明确地设置它:
unsigned int almost_one = 0x3f7fffff;
float value = 1.0f;
if(value> = 1.0f)std :: memcpy(& value,&; almost_one,sizeof(float));
对于这个特定的值,这个效果很好,但是我可以使用更通用的方法吗?
我希望有一个神奇的指令,我不知道,我可以用它来实现这一点!
我为C ++ 03开始了一个新的问题:
我希望有一个神奇的指令,我不知道,我可以用它来实现这个!
如果您有一个C ++ 11(或C99)标准库,那么 std :: nextafter(value,0.0f)从
< cmath>
(或 nextafter
from < math。 h>
)会给你最大的可表示值,它小于 value
。
在第一个参数之后给出下一个不同的值,在第二个参数的方向上;所以在这里,下一个截然不同的值接近零。
I have an input floating point value that is 0.0f <= value < 1.0f (note less than one).
When multiplying this value up to a larger range, naturally the floating point precision is decreased meaning the value can end up outside of the equivalent range.
For example if I start off with a value such as:
0.99999983534521f
Then multiply it by 100, I get:
100.000000000000f
Which is fine, but how do I then reduce the floating point representation to be the nearest floating point value that is still less than 100?
I found this little manual trick:
union test
{
int integer;
float floating;
};
test value;
value.floating = 1.0f;
printf("%x\n", value.integer);
Then I take that hex value and reduce it by one hex digit, then set it explicitly like so:
unsigned int almost_one = 0x3f7fffff;
float value = 1.0f;
if (value >= 1.0f) std::memcpy(&value, &almost_one, sizeof(float));
That works well for this specific value, but is there a more general approach I can use instead?
I'm hoping there's a magic instruction I'm not aware of that I can use to achieve this!
Edit: Great set of answers here, std::nextafter looks like what I'm after. Unfortunately I can't yet use C++11 math libraries so this won't work for me. To save complicating things, I'll tag this question with C++11 and accept Mike's answer below.
I've started a new question for C++03 : Alternative to C++11's std::nextafter and std::nexttoward for C++03?
If you've got a C++11 (or C99) standard library, then std::nextafter(value, 0.0f)
from <cmath>
(or nextafter
from <math.h>
) will give you the largest representable value smaller than value
.
It gives the "next" distinct value after the first argument, in the direction of the second; so here, the next distinct value closer to zero.
这篇关于在C ++中找到最接近的小于特定整数值的浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!