Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a bug in numeric_limits or am I just confused?

I encountered some queer behavior, at least in my own mind, while debugging some code involved with determining if an addition operation would underflow a double. Here is an example program demonstrating what I found.

#include <iostream>
#include <limits>

using std::cout;
using std::endl;
using std::numeric_limits;

int main()
{
    double lowest = numeric_limits<double>::lowest();
    bool truth = (lowest + 10000) == lowest;
    cout << truth << endl;
}

When I execute this code, I get true as a result. Is this a bug or am I just sleep deprived?

like image 554
Matthew Papageorge Avatar asked Sep 11 '14 05:09

Matthew Papageorge


1 Answers

The smallest double is:

-1.7976931348623157e+308

Adding 10,000, or 1e4, to this would only have a noticeable effect if doubles had 300+ digits of precision, which they most definitely do not. Doubles can only hold 15-17 significant digits.

The difference in magnitude between these two numbers is so great that adding 10,000 does not produce a new number. In fact, the minimum double is such a huge number (so to speak) that you could add a googol to it—that's 1 followed by a hundred zeros—and it wouldn't change.

like image 125
John Kugelman Avatar answered Oct 18 '22 04:10

John Kugelman