Skip to content

optimizing function over x,y

3 messages · Ravi Varadhan, Esmail

#
Hello all,

I would like to maximize or minimize a given math function over a
specific set of values.

I was checking out Wolfram Alpha (http://www70.wolframalpha.com/)
and it can do simple optimization problems in math, such as

     maximize 15*x - x**2 over 0 to 15

     (http://www70.wolframalpha.com/input/?i=maximize+15*x+-+x**2+over+0+to+15)

which finds the maximum value and input for x in the range 0 to 15.
Very cool. (This is of course a very simple example).

Reading the R documentation I found out that with R I can do this:


  f<-function(x) (15*x)-x**2
  optimize(f, c(0,15), lower=0,upper=15, maximum=TRUE)

which works very nicely too!


What I would like to do, but what Wolfram Alpha apparently can't do
(according to a post in their community forum) is to maximize (or
minimize) functions that contain two variables, x and y, or more. So
for example a very simple example would be

    minimize x**2 + y**2 over x:0 to 15, y:0-12  -- this does not work
                                                 -- though I'm unclear about
                                                 -- the correct syntax too.

Is there a way to do this in R in just a neat and easy way as R
optimizes a 1-D function?

For this particular instance I am interested in the minimum of

   x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10

so an example of this in R would be great, though in other problems
the range may not be identical for x and y.

Thanks,

Esmail

ps: Has anyone written any programs in Python that they then have used
     to call R functions? I am thinking of writing some of my scripts in
     Python, but then accessing some of R's functions.
#
Look at nlminb() or optim(), in particular the option `method = "L-BFGS-B"' or the function spg() in "BB" package.

With these you can optimize over any number of variables.

Ravi. 

____________________________________________________________________

Ravi Varadhan, Ph.D.
Assistant Professor,
Division of Geriatric Medicine and Gerontology
School of Medicine
Johns Hopkins University

Ph. (410) 502-2619
email: rvaradhan at jhmi.edu


----- Original Message -----
From: Esmail <esmail.js at gmail.com>
Date: Saturday, May 23, 2009 10:01 am
Subject: [R] optimizing function over x,y
To: R mailing list <r-help at r-project.org>
#
Ravi Varadhan wrote:
Hi Ravi,

Thanks for the leads, I'll take a look, though right now I have
run into problems with even the simple (?) optimize function, so
I'll first have to figure out what I'm doing wrong with it.

Best,
Esmail