What will I Say?

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)
Answer: -1.0 Answer: nan Answer: 4.0 Buggy Code - Not Executed

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.

1 solution

Algorithmically, the value of x x would always be 0.8 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 ( ) ) \infty/(1-(-\infty)) 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.

The working version of this code is as follows:

1
2
3
4
5
6
7
from fractions import Fraction as frac
a = frac(5,1)
x = frac(8,10)
trials = 10000
for i in xrange(trials):
    x = a*x*(1-x)
print "Answer:", x/(1-x)

Floating point numbers work great in most scenarios, but I was definitely surprised to see it fail in this case.

It's strange how floats that can be represnted as the same number visually can be different when it comes to its real data. I answered 4.0 because I thought it could handle this, but I was wrong.

Interesting problem, Janardhanan.

Brock Brown - 6 years, 3 months ago

When I attempted the problem, the last statement (the print statement) had a single space at the front. This gives syntax error (indentation error). I've modified the problem.

Ivan Koswara - 6 years, 3 months ago

It's buggy dude you not say that it is a pseudocode

Mbah Abal - 5 years, 5 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...