Skip to content
Prev 32975 / 398506 Next

dynamics of functions

On Thu, 5 Jun 2003, Tobias Verbeke wrote:

            
That's because -x^3 isn't a function. It's an expression.

You want
   iterate(function(x) -x^3, 3, 256)



This might also be a good time to point out that this problem is one where
storing past values helps a lot.

The function below returns a function that iterates for a particular f and
x.  It stores its past results, so if you ask for the same n again you get
it immediately and if you ask for an n a little bigger than a past one it
only has to do the remaining steps

You would do something like


ff<-iterator(function(z) 4*z*(1-z), x=0.3)

and then ff(10) gives the tenth iterate or
sapply(10*(1:100),ff)
gives the tenth, 20th, 30th,.. 1000th iterate.

	-thomas


iterator<-function(f,x){

    memo<-new.env()

    function(n){
        if (n==1)
            return(f(x))
        v<-paste("n",n,sep="")
        if (exists(v,envir=memo))
            return(get(v,envir=memo))
        else{
            rval<-f(Recall(n-1))
            assign(v,rval,envir=memo)
        }
    }


}