[R] dynamics of functions

Thomas Lumley tlumley at u.washington.edu
Thu Jun 5 18:45:41 CEST 2003


On Thu, 5 Jun 2003, Tobias Verbeke wrote:

> Dear Thomas,
>
> > What about the following function?
> >
> > iterate<-function(f,n,x){
> >   if(n==0) return(x)
> >   y<-x
> >   for(i in 1:n)y<-f(y)
> >   y
> > }
> > iterate(sqrt,3,256)
>
> Thank you very much, this certainly helps.
> I'm still curious, though, to know how to
> write the expression of my function
> immediately as the argument f.
> I can define it outside of the function
> > aap <- function(x) -x^3
> and use it as argument
> > iterate(aap,3,256),
> but I seem not to be clever enough
> to write a function that receives
> the following as input
>
> > iterate(-x^3,3,256)
>

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)
        }
    }


}




More information about the R-help mailing list