Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...