I was given the below problem and I want to make sure I fully understand before submitting it.

Explain briefly the problem that might arise if the following algorithm is implemented. (Hint: remember the problem of rounding error with floating point numbers)

assign n the value 0.1 
while (n is not equal to 1.0) 
   print the value of n 
   assign n the value n + 0.00001
end while

I believe the answer is that is does not say what to do if the value of n is equal to 1.0. Am I looking at this right or am I missing something obvious?

有帮助吗?

解决方案

The problem is that 0.00001 is not exactly representable in standard floating point so when you keep adding you will reach a number like 0.999999999998 instead of 1.0.

Therefore n will never be equal to 1.0

Therefore the loop will never terminate.

其他提示

The comparison might not stop because of rounding. It should address what happens when n is greater than 1.0

You could loop by integer and compare to integer, or if you want to use floats, change the last comparison to

while (n is less than 1.0) 

Such loop can have sense, just to look at the results and to understand, that the equality will never happen. For you work in binaries and in binary system 10-5 is not finite. So, it is cut and the counting is not precise.

On the other hand, if you do not use any concrete language, it could be so, that you can fulfill the algorithm on the machine based on decimal arithmetic. There this algorithm works OK.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top