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
", 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…