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\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?

Answers


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.


Need Your Help

Do you need to create an NSAutoreleasePool within a block in GCD?

iphone objective-c cocoa osx grand-central-dispatch

Normally, if you spawn a background thread or run an NSOperation on an NSOperationQueue you need to create an NSAutoreleasePool for that thread or operation because none exists by default.

How to parse data in javascript file through .net?

c# javascript asp.net xml parsing

How to parse data in a java script file through .net .

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.