mpap
mpap

Reputation: 123

How to solve simple optimization problem in R

I have three equations and I would like to solve for a parameter that minimizes the differences between them.

DifferenceA:   100/(1+d)^50 - 75/(1+d)^25
DifferenceB:   100/(1+d)^50 - 50/(1+d)^15
DifferenceC:   75/(1+d)^25 - 50/(1+d)^15

I would like to solve for the parameter d* that minimizes the sum of the squared residuals in the above differences preferably using R where:

enter image description here

I haven't done optimization in R and was wondering what packages and how to set-up solving a simple minimization problem like this in R? thanks.

Upvotes: 0

Views: 486

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226911

Since this is a single-input objective function you can use optimize() (optim() is for R^n → R, i.e. a vector of parameters):

fA <- function(d) 100/(1+d)^50 - 75/(1+d)^25
fB <- function(d)  100/(1+d)^50 - 50/(1+d)^15
fC <- function(d)   75/(1+d)^25 - 50/(1+d)^15

fn <- function(d) {
  vals <- c(fA(d), fB(d), fC(d))
  sum(vals^2)
}


optimize(fn, interval = c(-200, 2e5))

However, a quick graph (or some mathematical analysis I was too lazy to do) shows that all of these differences decrease to zero as d → ∞ — so the answer will be infinite, or numerically equal to the upper bound of the interval you try (or wherever the gradient of the differences becomes so small that R gives up).

curve(fA, from = 1e-5, to = 1e6, log="x")
curve(fB, add = TRUE, col = 2)
curve(fC, add = TRUE, col = 4)

curve(fA(x)^2, from = 1e-5, to = 1e6, log="xy")
curve(fB(x)^2, add = TRUE, col = 2)
curve(fC(x)^2, add = TRUE, col = 4)

curves, log-x scale

same curves, log-log

Upvotes: 4

Related Questions