使用optim()解方程

时间:2019-05-28 02:00:44

标签: r

我有2个方程需要通过优化来解决

{(4x^2-20x+1/4 y^2+8=0
  1/2 xy^2+2x-5y+8=0)

我已经运行了代码,但是我很困惑应该是1个答案还是2个,因为函数只会返回最后一行的结果

我应该这样做

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

>  myfunc=function(x){
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

或者我应该这样做

> myfunc=function(x){
+  4*x[1]^2-20*x[1]+(x[2]^2/4)+8
+  (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
+  }
> optim(c(0,0),myfunc,method="BFGS")

对于第二个函数,它仍然只给我第二个函数的答案,因此哪种方法是正确的。

2 个答案:

答案 0 :(得分:1)

最小化应等于零的两个表达式的平方和,并确保最佳值等于0(直到浮点近似)。

myfunc <- function(z) {
  x <- z[1]
  y <- z[2]
  (4*x^2-20* x + 1/4*y^2 + 8)^2 + (1/2 * x*y^2 + 2*x- 5*y + 8)^2
}
optim(c(0, 0), myfunc)

给予:

$par
[1] 0.5000553 2.0002986

$value
[1] 1.291233e-06

$counts
function gradient 
      67       NA 

$convergence
[1] 0

$message
NULL

答案 1 :(得分:0)

您还可以使用软件包来求解非线性方程组,例如nleqslv

通过使函数返回一个包含每个方程式结果的向量来稍微重新定义函数

myfunc <- function(x){
    y <- numeric(length(x))
    y[1] <- 4*x[1]^2-20*x[1]+(x[2]^2/4)+8
    y[2] <- (1/2)*(x[1]*x[2]^2)+2*x[1]-5*x[2]+8
    y
}

定义求解器的起始值

xstart <- c(0,0)  

然后执行

library(nleqslv)
nleqslv(xstart,myfunc)

给予

$x
[1] 0.5 2.0

$fvec
[1] -1.472252e-09 -7.081979e-10

$termcd
[1] 1

$message
[1] "Function criterion near zero"

$scalex
[1] 1 1

$nfcnt
[1] 7

$njcnt
[1] 1

$iter
[1] 7

还有更多可以解决方程系统的软件包,例如BBpracma

相关问题