Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do arbitrary floating point values compare to infinity?

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;
  }
}
like image 674
kiw Avatar asked Jan 13 '11 00:01

kiw


People also ask

How do you compare floating point values?

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.

Why should we never compare floating point values by using exact equality comparison?

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.

What are the two approaches used for comparing floating point numbers?

They are: Bitwise comparison. Direct ("exact") IEEE-754 comparison. Absolute margin comparison.

How do equality and floating point numbers compare?

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 ...


2 Answers

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.

like image 74
etarion Avatar answered Oct 08 '22 16:10

etarion


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)

like image 40
Jason Rogers Avatar answered Oct 08 '22 17:10

Jason Rogers