Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c++11 - Finding the closest floating point value less than a specific integer value in C++?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm hoping there's a magic instruction I'm not aware of that I can use to achieve this!

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...