Basically i want to search for the smallest (positive) value from a bunch of values and need a default value to compare to the first one. The naïve assumption would be, they always compare "less than" (except NaNs, but let's not consider those) but I'm not quite sure.
I'm using the float
type and I think it can safely be assumed that my target hardware implements a infinity value.
Here's some example code:
auto leastValue = std::numeric_limits<float>::infinity();
for (auto i = something.begin(), e = something.end(); i != e; ++i)
{
auto value = (*i)->GetValue();
if (value < leastValue)
{
leastValue = value;
}
}
To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.
Comparing for equality Simple values like 0.1 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations or the precision of intermediates can change the result.
They are: Bitwise comparison. Direct ("exact") IEEE-754 comparison. Absolute margin comparison.
If we do have to compare two floating-point numbers then rather than using “==” operator we will find the absolute difference between the numbers (which if were correctly represented, the difference would have been 0) and compare it with a very small number 1e-9 (i.e 10^-9, this number is very small) and if the ...
For IEEE 754 floats, except NaN and infinity, everything is less than infinity. Chances are you'll have those on your platform. If you're paranoid, check with numeric_limits<float>::is_iec559
. If your platform happens to be not conforming, use numeric_limits<float>::max()
; if your sequence is nonempty, it will not give you a wrong result.
I support Michael Madsen comment: You don't need an infinite value for this test,
Store the first value of your bunch in a variable and then start your testing with the second value of the bunch. (and it will even save you one test :P)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With