What would be the output of the following code :
a = 5.0
x = 0.8
trials = 10000
for i in xrange(trials):
x = a*x*(1-x)
print "Answer:", x/(1-x)
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Algorithmically, the value of x would always be 0 . 8 . Then, x/(1-x) = 0.8/0.2 = 4.0. Hence, 'without execution', one may say that the solution would be
Answer: 4.0
However, when you actually execute the code, you would find that the value of x will drift (around the 25th to 30th iteration) and by the 40th iteration or so, will become a large negative number. If stopped at this stage, the solution would be
Answer: -1.0
But, the code is to run for significantly larger number of iterations, with each subsequent iteration now (i.e., after the 40th iteration), the magnitude would get squared and the sign is negative. However, any processor is of finite precision and has a maxvalue. Hence, x quickly 'settles' to -inf.
Hence, on completion the answer would be - ∞ / ( 1 − ( − ∞ ) ) which is not defined.
Therefore, the correct solution would be
Answer: nan
This just illustrates that a code does not necessarily execute in a manner which coincides with its logic.