【问题标题】:Solve non-linear equations using "nleqslv" package使用“nleqslv”包求解非线性方程
【发布时间】:2018-06-14 01:13:06
【问题描述】:

我尝试使用 nleqslv 求解这些非线性方程。但是它不能很好地工作。我确实知道它不这样做的原因,因为我没有将两个未知数分开到等式的不同方面。

我的问题是:1,是否有其他软件包可以解决这种问题 方程? 2,R中是否有任何有效的方法可以帮助我重新排列 方程,使其满足封装的要求 nleqslv?

谢谢你们。

这是代码,p[1] 和 p[2] 是我要解决的两个未知数。

   dslnex<-function(p){
   p<-numeric(2)
   0.015=sum(exp(Calib2$Median_Score*p[1]+p[2])*weight_pd_bad)

   cum_dr<-0 
   for (i in 1:length(label)){
   cum_dr[i]<-exp(Calib2$Median_Score*p[1]+p[2][1:i]*weight_pd_bad[1:i]/0.015
   }

   mid<-0
   for (i in 1:length(label)){
   mid[i]<-sum(cum_dr[1:i])/2
   }

   0.4=(sum(mid*weight_pd_bad)-0.5)/(0.5*(1-0.015))

   }

   pstart<-c(-0.000679354,-4.203065891)
   z<- nleqslv(pstart, dslnex, jacobian=TRUE,control=list(btol=.01))

【问题讨论】:

  • 无法重现,因为您没有提供自包含问题。当您想求解 A=B 形式的方程时,请将方程写为 y[..] &lt;- A - By[..] &lt;- B-A。将这两个方程重写为y[1]&lt;- 0.015 - (...)y[2]&lt;-0.4 - (...)。将 y 声明为长度为 2 的向量。最后pnleqslv 传递的值。不要在函数开始时用 p&lt;-numeric(2) 覆盖它。

标签: r nonlinear-optimization


【解决方案1】:

根据我的评论,我重写了您的函数,如下纠正错误和效率低下。 错误和其他更改以内联 cmets 形式给出。

# no need to use dslnex as name for your function
# dslnex <- function(p){
# any valid name will do

f <- function(p) {
    # do not do this
    # you are overwriting p as passed by nleqslv
    # p<-numeric(2)

    # declare retun vector
    y <- numeric(2)

    y[1] <- 0.015 - (sum(exp(Calib2$Median_Score*p[1]+p[2])*weight_pd_bad))

    # do not do this
    # cum_dr is initialized as a scalar and will be made into a vector
    # which will be grown as a new element is inserted (can be very inefficient)
    # cum_dr<-0 
    # so declare cum_dr to be a vector with length(label) elements

    cum_dr <- numeric(length(label))
    for (i in 1:length(label)){
        cum_dr[i]<-exp(Calib2$Median_Score*p[1]+p[2][1:i]*weight_pd_bad[1:i]/0.015
    }

    # same problem as above
    # mid<-0
    mid <- numeric(length(label))
    for (i in 1:length(label)){
        mid[i]<-sum(cum_dr[1:i])/2
    }

    y[2] <- 0.4 - (sum(mid*weight_pd_bad)-0.5)/(0.5*(1-0.015))

    # return vector y
    y
}

pstart <-c(-0.000679354,-4.203065891)
z <- nleqslv(pstart, dslnex, jacobian=TRUE,control=list(btol=.01))

nleqslv 用于求解f(x) = 0 形式的方程组,该方程组必须为正方形。 所以函数必须返回一个与x-vector 大小相同的向量。

如果您的方程组有解,您现在应该可以继续了。并且只要您的方程式中没有进一步的错误。我在cum_dr 的表达式和mid[i] 的表达式中有关于[1:i] 的双打。计算mid 的循环可能可以写成一条语句:mid &lt;- cumsum(cum_dr)/2。由你决定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 2019-10-02
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多