我使用nleqslv
包来解决两个非线性方程组的系统
library(nleqslv)
read.table("C:\\Users\\Livia\\Desktop\\firm.txt",header=TRUE)
firm.txt<-"Q K r X.E t E0
"
firm<-read.table(textConnection(firm.txt),header=TRUE,stringsAsFactors=FALSE)
firm
#Loop with solver for 9 dates:
for(i in 1:9){
K<-firm[i,2]
r<-firm[i,3]
X.E<-firm[i,4]
t<-firm[i,5]
E0<-firm[i,6]
BS<-function(x){
f<-rep(NA,length(x))
f[1]<-(x[1]*pnorm((log(x[1]/K)+(r+(x[2]^2/2))*t)/(x[2]*sqrt(t)))-exp(-r*t)*K*pnorm((log(x[1]/K)+(r+(x[2]^2/2))*t)/(x[2]*sqrt(t))-x[2]*sqrt(t)))-E0
f[2]<-X.E*E0-pnorm((log(x[1]/K)+(r+(x[2]^2/2))*t)/(x[2]*sqrt(t)))*x[2]*x[1]
f
}
p0<-c((E0+K),X.E*E0/(E0+K))
print(p0)
ans<-nleqslv(p0,BS,control=list(trace=1,allowSingular=TRUE))
print(ans)
}
我真的很想了解它背后的逻辑。 我有两个未知数,我根据
设置起始值p0<-c((E0+K),X.E*E0/(E0+K))
迭代过程如何工作?我已经尝试从CRAN软件包“nleqslv”3.0 .pdf中获取它但是没有成功。
答案 0 :(得分:0)
请参阅我上面的评论以获取警告。
话虽如此,这就是你运行这个功能时发生的事情:
> nleqslv
function (x, fn, jac = NULL, ..., method = c("Broyden", "Newton"),
global = c("dbldog", "pwldog", "cline", "qline", "gline",
"hook", "none"), xscalm = c("fixed", "auto"), jacobian = FALSE,
control = list())
{
fn1 <- function(par) fn(par, ...)
if (is.null(jac)) {
jacfunc <- NULL
}
else {
if (!is.function(jac))
stop("argument 'jac' is not a function!")
jacfunc <- function(par) jac(par, ...)
}
method <- match.arg(method)
global <- match.arg(global)
xscalm <- match.arg(xscalm)
con <- list(ftol = 1e-08, xtol = 1e-08, btol = 0.001, stepmax = -1,
delta = "newton", sigma = 0.5, scalex = rep(1, length(x)),
maxit = 150, trace = 0, chkjac = FALSE, cndtol = 1e-12,
allowSingular = FALSE, dsub = -1L, dsuper = -1L)
if (global == "none")
con$maxit = 20
if (length(control)) {
namc <- names(control)
if (!is.list(control) || is.null(namc))
stop("'control' argument must be a named list")
if (!all(namc %in% names(con)))
stop("unknown names in control: ", paste(sQuote(namc[!(namc %in%
names(con))]), collapse = ", "))
con[namc] <- control
}
tmp <- con[["delta"]]
if (is.character(tmp)) {
k <- match(tolower(tmp), c("cauchy", "newton"))
con[["delta"]] <- as.numeric(-k)
}
else if (!is.numeric(tmp))
stop("control[\"delta\"] should be either character or numeric")
on.exit(.C("deactivatenleq", PACKAGE = "nleqslv"))
out <- .Call("nleqslv", x, fn1, jacfunc, method, global,
xscalm, jacobian, con, new.env(), PACKAGE = "nleqslv")
out
}
<environment: namespace:nleqslv>
如果你想看看其他功能是如何工作的,你可以用同样的方式探索它们(输入功能名称并按下回车键而不添加()
)。
如果您想深入了解,请参阅完整的源代码:
https://cran.r-project.org/src/contrib/nleqslv_3.0.1.tar.gz
在这里: