Guy
Guy

Reputation: 624

Bug while looping through list

So I read this question at math.se and decided to run a loop to check the answer for myself. I know the proof there is rigorous, so I never really doubted it, but it's good when you can see things work out. Apparently stackoverflow doesn't support LaTex, (which seems quite reasonable considering this is a programming site, not a math one) so I am posting a screenshot to the question in case the link goes down or something.

Ramanujan's famous nested radical

Now I wrote this code to simulate the above expression, obviously calculating it till infinity is absurd, so I decided to do it till n=999, seemed reasonable to me as I didn't have an idea of how fast the expression converges. For those without a math background, Ignore the lim I am trying to calculate the given expression for n=999.

>>>l=list(range(1,1000))
>>>from math import sqrt as s
>>>p=1
>>>while l:
       a=l.pop()
       a*=p
       a+=1
       a=s(a)
       p=a
>>>p
2.0

I expect the answer to be 3 not 2. Also note that I am not asking for a method to compute this function, I am asking for the bug in my code. You could provide me with a function of your own, but the primary intention of this question is to locate the bug in the code I wrote, which sadly I cannot find.

Upvotes: 1

Views: 81

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208505

It looks like you want to be using range(2, 1000). If you go all the way down to 1 you end up with an extra sqrt(1 + ...) where ... is the formula you are attempting to solve.

Upvotes: 5

Related Questions