Solving a system of nonlinear equations in R

心已入冬 提交于 2020-01-03 02:21:41

问题


Suppose I have the following system of equations:

a * b = 5
sqrt(a * b^2) = 10

How can I solve these equations for a and b in R ?

I guess this problem can be stated as an optimisation problem, with the following function... ?

fn <- function(a, b) {

    rate <- a * b
    shape <- sqrt(a * b^2)

    return(c(rate, shape) )

}

回答1:


In a comment the poster specifically asks about using solve and optim so we show how to solve this (1) by hand, (2) using solve, (3) using optim and (4) a fixed point iteration.

1) by hand First note that if we write a = 5/b based on the first equation and substitute that into the second equation we get sqrt(5/b * b^2) = sqrt(5 * b) = 10 so b = 20 and a = 0.25.

2) solve Regarding the use of solve these equations can be transformed into linear form by taking the log of both sides giving:

log(a) + log(b) = log(5)
0.5 * (loga + 2 * log(b)) = log(10)

which can be expressed as:

m <- matrix(c(1, .5, 1, 1), 2)
exp(solve(m, log(c(5, 10))))
## [1]  0.25 20.00

3) optim Using optim we can write this where fn is from the question. fn2 is formed by subtracting off the RHS of the equations and using crossprod to form the sum of squares.

fn2 <- function(x) crossprod( fn(x[1], x[2]) - c(5, 10))
optim(c(1, 1), fn2)

giving:

$par
[1]  0.2500805 19.9958117

$value
[1] 5.51508e-07

$counts
function gradient 
      97       NA 

$convergence
[1] 0

$message
NULL

4) fixed point For this one rewrite the equations in a fixed point form, i.e. in the form c(a, b) = f(c(a, b)) and then iterate. In general, there will be several ways to do this and not all of them will converge but in this case this seems to work. We use starting values of 1 for both a and b and divide both side of the first equation by b to get the first equation in fixed point form and we divide both sides of the second equation by sqrt(a) to get the second equation in fixed point form:

a <- b <- 1  # starting values
for(i in 1:100) {
  a = 5 / b
  b = 10 / sqrt(a)
}

data.frame(a, b)
##      a  b
## 1 0.25 20



回答2:


Use this library.

library("nleqslv")

You need to define the multivariate function you want to solve for.

fn <- function(x) {

  rate <- x[1] * x[2] - 5
  shape <- sqrt(x[1] * x[2]^2) - 10

  return(c(rate, shape))

}

Then you're good to go.

nleqslv(c(1,5), fn)

Always look at the detailed results. Numerical calculations can be tricky. In this case I got this:

Warning message:
In sqrt(x[1] * x[2]^2) : NaNs produced

That just means the procedure searched a region that included x[1] < 0 and then presumably noped the heck back to the right hand side of the plane.



来源:https://stackoverflow.com/questions/48832731/solving-a-system-of-nonlinear-equations-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!