[R] Evaluate function on a grid

David Winsemius dwinsemius at comcast.net
Sat Feb 16 22:57:31 CET 2008


"Giu Mac" <neox86 at gmail.com> wrote in
news:ed24494f0802161253xae811baj17794deaeaec0b28 at mail.gmail.com: 

> I have a function in R^2, say
> 
> f <- function(x,y) { ...skipped }
> 
> I want to plot this function using contour, persp. wireframe, etc. I
> know that the function has a global
> minimum at (x0, y0)
> 
> The naive approach is to evaluate the function on the outer product
> of two arrays, like this:
> 
> sx <- c(seq(-3, x0, len = 100), seq(x0, 3, len = 100)[-1])
> sy <- c(seq(-3, y0, len = 100), seq(y0, 3, len = 100)[-1])
> 
> fout <- outer( sx, sy, f)
> persp(fout)
> 
> This works pretty well, but I would like to achieve better results
> by using information o the curvature of
> the function.
> I know that the curvature of the function is very high in a
> neighborhood of (x0, y0), but it
> is rather flat for (x,y) not belonging to this neighborhood.
> 
> So in principle I have to choices: increase the number of points
> were the function is evaluated; evaluate the function more densely 
> in a neighborhood of (x0,y0) and more sparsely outside that
> neighborhood. 
> 
> Since the function is rather costly to evaluate, I would like to
> efficiently use the information on the curvature. Does anybody has a
> suggestion on out to form sx and sy in such a way to reflect the
> curvature of the function? 
> 
> I can make this on a per cases base, but I would like to have an
> automatic procedure.

This does not use the local curvature, but perhaps you can save cycles 
by setting your grid with an exp(-anding) function:

x0=4;y0=2
sx<-c(x0 - (exp(seq(1, 0, len = 100))-1),
      x0 + (exp(seq(0, 1, len = 100))-1)[-1])
sy<-c(y0 - (exp(seq(1, 0, len = 100))-1),
      y0 + (exp(seq(0, 1, len = 100))-1)[-1])
      
 f <- function(x,y) log((x-4)^2) + log((y-2)^2)
 fout <- outer( sx, sy, f)

#log(0) does not plot well
persp(fout,zlim=c(-15,5))

-- 
David Winsemius



More information about the R-help mailing list