LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   infinite loop that isnt infinite? (http://www.linuxquestions.org/questions/programming-9/infinite-loop-that-isnt-infinite-840809/)

frieza 10-27-2010 01:52 PM

infinite loop that isnt infinite?
 
i was playing around with c++ recently and for laughs and giggles i came up with this little program
Code:

#include <iostream>
using namespace std;
int main ()
{
  for (long double n=100; n>0; n = n/2) {
    cout << n << "\n ";
  }
  cout << "FIRE!\n";
  return 0;
}

theoretically that should be an infinite loop but it in fact does terminate eventually echoing out 'FIRE!'

just wondering if even though in theory this should be an infinite loop (a number repetedly divided by 2 should never reach 0 thus the conditions of the loop should never be satisfied, hence infinite loop) perhaps in practice limitations of the variable types prevent this?

no this is not homework just a question to help understand the mechanics of variables and loops

paulsm4 10-27-2010 02:11 PM

Hi -

Quote:

this is not homework just a question to help understand the mechanics of variables and loops
Actually, the answer to your question has to do with the pitfalls of "floating point precision" :

http://www.cygnus-software.com/paper...ringfloats.htm

PS:
On my system, I got down to "3.6452e-4951" :)

frieza 10-27-2010 02:16 PM

thanks, interesting article btw


All times are GMT -5. The time now is 11:16 AM.