开发者

How do arbitrary floating point values compare to infinity?

开发者 https://www.devze.com 2023-02-03 18:39 出处:网络
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 tha

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 va开发者_开发百科lue.

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;
  }
}


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)


I think this depends on what behaviour you expect if the sequence is empty. If you want infinity your implementation is fine, otherwise you should use the first value.

auto i = something.begin();
auto e = semething.end();
if (i == e)
  throw std::exception("empty sequence");

auto leastValue = (*i)->GetValue();

for (++i; i != e; ++i)
{
  auto value = (*i)->GetValue();
  if (value < leastValue)
  {
    leastValue = value;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消