我打算用nleqslv包解决一个非线性方程组。这是下面的R脚本。
library("nleqslv")
require(nleqslv)
x <- c(1.4,1.6,1.8,2)
NMfun1 <- function(g) {
y <- numeric(3)
y[1] <- -(4/g[1])-(4*log(g[2]))-sum(log(x))+sum((g[2]*x)^g[1]*log(g[2]*x))+2*sum(g[3]*(g[2]*x)^g[1]*log(g[2]*x)*exp(-(g[2]*x)^g[1])*(1-g[3]*exp(-(g[2]*x)^g[1]))^(-1))
y[2] <- -(4*g[1]/g[2])+sum(g[2]*x*(g[2]*x)^(g[1]-1))+2*sum(g[1]*g[3]*x*(g[2]*x)^(g[1]-1)*exp(-(g[2]*x)^g[1])*(1-g[3]*exp(-(g[2]*x)^g[1]))^(-1))
y[3] <- (4/(g[3]-1))-2*sum(exp(-(g[2]*x)^g[1])*(1-g[3]*exp(-(g[2]*x)^g[1]))^(-1))
y
}
gstart <- matrix(runif(3*100,min=0,max=1), nrow=100, ncol=3)
ans <- nleqslv(gstart,NMfun1, method="Newton", global="dbldog")
ans$g
我相信我在代码中没有做正确的事情,因为在运行代码后我一直都是NULL。 我需要你的帮助。谢谢
答案 0 :(得分:1)
g
的结果中没有searchZeros()
个元素。因此,ans$g
会返回NULL
。
请参阅底部的here。从searchZeros()
返回的列表不包含名为g
的元素。以下是该功能的结束。
searchZeros <- function(x, fn, digits=4L, ... ) {
...
# return full precision solutions ordered with rounded ordering
res <- list(x=xsol[zidxo,,drop=FALSE], xfnorm=fnorm[idxcvg][notdups][zidxo],
fnorm=fnorm[idxcvg], idxcvg=idxcvg, idxxtol=idxxtol,
idxnocvg=idxnocvg, idxfatal=idxfatal,
xstart=solstart[zidxo,,drop=FALSE],cvgstart=xstartcvg)
res
}
答案 1 :(得分:1)
There are a number of issues with your problem. First, your code contains obvious flaws, i.e. g[2] can become negative resulting in taking the log of something negative which is undefined.
Inside searchZeros
there is the line if (!any(tcode == 1)) return(NULL)
. The object tcode
gets filled with output$termcd
from the function nleqslv
. In the helpfile of nleqslv
it says that a 1 for output$termcd
means that convergence has been reached. In summary, if the function does not detect convergence it simply stops without any further information and returns NULL
.
edit: Apologies to the creators of nleqslv
, the case is documented in contrast to what I said before (although it cannot be found by searching for NULL
).