Solving a system of nonlinear equations in R

前端 未结 2 791
悲哀的现实
悲哀的现实 2021-01-03 10:36

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

2条回答
  •  生来不讨喜
    2021-01-03 11:03

    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.

提交回复
热议问题