A float
(a.k.a. single) value is a 4-byte value, and supposed to represent any real-valued number. Because of the way it is formatted and the finite number of bytes it is made off, there is a minimum value and a maximum value it can represent, and it has a finite precision, depending on it's own value.
I would like to know if there is a way to get the closest possible value above or below some reference value, given the finite precision of a float. With integers, this is trivial: one simply adds or subtracts 1. But with a float
, you can't simply add or subtract the minimum float value and expect it to be different from your original value. I.e.
float FindNearestSmaller (const float a)
{
return a - FLT_MIN; /* This doesn't necessarily work */
}
In fact, the above will almost never work. In the above case, the return will generally still equal a
, as the FLT_MIN
is far beyond the precision of a
. You can easily try this out for yourself: it works for e.g. 0.0f
, or for very small numbers of order FLT_MIN
, but not for anything between 0 and 100.
So how would you get the value that is closest but smaller or larger than a
, given floating point precision?
Note: Though i am mainly interested in a C/C++ answer, I assume the answer will be applicable for most programming languages.
memcpy
into an integer, add one,memcpy
back intofloat
? – Cyanogen