# Recursive problems in Sage

I've been trying to figure out how to run a basic recursive problem in sage. The basic structure of the problem I have figured out, its just a matter of putting it in terms of a for/ while loop.

#Initializing values
k,k1,vk,beta,vk1=var('k,k1,vk,beta,vk1')
vk= log(k-k1)+beta*log(k1)

#I want to loop this procedure
FOC=vk.diff(k1)
k1star=solve(FOC==0,k1)
vk=(vk).subs(k1star)
vk


Any help is appreciated.

edit retag close merge delete

I don't see the point : the value of k1 that nullifies $\frac{\partial vk}{\partial k1}$ is by definition an expression that does not depend on k1.

#Initializing values
k,k1,beta,vk1=var('k,k1,beta,vk1')
vk(k1)= log(k-k1)+beta*log(k1)
S1=vk.diff(k1).solve(k1)


At this point :

sage: S1
[k1 == beta*k/(beta + 1)]
sage: vk(k1=S1.rhs())
beta*log(beta*k/(beta + 1)) + log(-beta*k/(beta + 1) + k)


But, of course :

sage: vk(k1=S1.rhs()).diff(k1)
0


So there's nothing to iterate.

Aren't you trying to implement something like Newton's method of root-finding when solve doesn't give a explicit answer ?

@EmmanuelCharpentier I see the issue with my approach. Though I actually made a video on solving a planners problem which is similar to this that uses value function iteration, https://www.youtube.com/watch?v=Bv_tP.... I just want to be able to code something like this.

Sort by » oldest newest most voted

Below is what I was able to come up with. I checked the first couple iterations to make sure they were correct. After that, it looks right at a glance, but I haven't verified. This is from my old SAGE 8.4 installation (I have 9.0 on a different computer), so the print statement will be formatted differently in version 9.0.

The key is to substitute the result back into v0 before substituting back into vk.

sage: v0 = log(k)
sage: for n in range(5):
....:     vk = log(k-k1) + beta*v0(k=k1)
....:     FOC = vk.diff(k1)
....:     k1star = solve(FOC==0, k1)
....:     print(n, k1star)
....:     v0 = (vk).subs(k1=k1star.rhs())
....:
(0, [k1 == beta*k/(beta + 1)])
(1, [k1 == (beta^2 + beta)*k/(beta^2 + beta + 1)])
(2, [k1 == (beta^3 + beta^2 + beta)*k/(beta^3 + beta^2 + beta + 1)])
(3, [k1 == (beta^4 + beta^3 + beta^2 + beta)*k/(beta^4 + beta^3 + beta^2 + beta + 1)])
(4, [k1 == (beta^5 + beta^4 + beta^3 + beta^2 + beta)*k/(beta^5 + beta^4 + beta^3 + beta^2 + beta + 1)])

more

I'm genuinely surprised how little code is needed for this problem. Thank you!