View Single Post
  #5 (permalink)  
Old June 18th, 2012, 02:43 PM
drpepper drpepper is offline
Authorized User
Points: 267, Level: 5
Points: 267, Level: 5 Points: 267, Level: 5 Points: 267, Level: 5
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
Join Date: May 2012
Posts: 66
Thanks: 0
Thanked 4 Times in 4 Posts


Thank you for posing the question. You have prompted me to think a little deeper to explore the concepts behind the code. I had not attempted to compile and run the code. I just played computer with it.

I compiled and ran the code and discovered that it does loop endlessly. Here is the code I wrote to test for failure to end the loop:
//does this terminate?

#include <iostream>

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

int main()
	for (double x = 0.0; x!= 1.0; x+= 0.1)
             cout << x << endl;

	return 0;
I believe the problem lies in the fact that 0.1 does not have an exact binary floating point equivalent. There are only approximations. This creates a situation where x will never equal exactly 1.0; therefore, the loop never satisfies the condition and continues until terminated manually.

If I understand the concept properly, the only floating point values which will result in a loop which terminates as desired must result in a value which is an exact power of two. Increments of 0.5, 0.25, 0.125, ... would terminate in the above code.

I am currently working my way through Chapter 3, but had not reached the Floating-Point Loop Counters topic prior to now. My attempt to resolve the loop termination problem prompted me to read ahead of my current progress to find an answer.

Did I come up with the correct answer to your question?
Next code never stopped, and you known why?) I know)

Last edited by drpepper; June 18th, 2012 at 02:45 PM.. Reason: typo