在R中使用nleqslv求解许多非线性方程的循环 [英] Loop for solving a number of non-linear equations with nleqslv in R
问题描述
为了解决到默认距离的度量,我在求解R中带有nleqslv
的多个非线性方程式时遇到问题.这是我的第一个R代码,因此我仍在努力解决一些问题.我的代码如下所示(最小化为三格data.frame):
I have a problem in solving a number of non-linear equations with nleqslv
in R in order to solve for a distance-to-default measure. This is my first R code, so I am still struggling with some problems. My code looks like this (miniaturized to a three-case-data.frame):
library("nleqslv")
D <- c(28000000, 59150000, 38357000)
VE <- c(4257875, 10522163.6, 31230643)
R <- c(0.059883, 0.059883, 0.059883)
SE <- c(0.313887897, 0.449654737, 0.449734826976691)
df <- data.frame(D, VE, R, SE)
for(i in 1:nrow(df)){
fnewton <- function(x){
y <- numeric(2)
d1 <- (log(x[1]/df$D[i])+(df$R[i]+x[2]^2/2))/x[2]
d2 <- d1-x[2]
y1 <- df$VE[i]-(x[1]*pnorm(d1)-exp(-df$R[i])*df$D[i]*pnorm(d2))
y2 <- df$SE[i]*df$VE[i]-pnorm(d1)*x[2]*x[1]
y
}
xstart <- c(df$VE[i], df$SE[i])
df$VA[i] <- nleqslv(xstart, fnewton, method="Newton")$x[1]
df$SA[i] <- nleqslv(xstart, fnewton, method="Newton")$x[2]
i=i+1
}
我的问题是,我的代码仅给我一个解决方案,这意味着我的循环首先无法正常工作.该循环应克服以下事实:fnewton
首先是长度为2的向量,但是我的数据(或示例)是比2更长的向量.我尝试了一些尝试,但我无法解决问题,我认为有一个简单的解决方案,但是我看不到我的错误.
My problem is, that my code only gives me one solution, meaning that my loop does not work properly in the first place. The loop should overcome the fact, that fnewton
is a vector of length 2 in the first place, but my data (or my example) is a longer vector than 2. I tried some things but I cannot handle the problem, I think there is a simple solution for this, but I do not see my mistake.
推荐答案
通过在一次for循环外定义fnewton
函数并将变量df
和i
在参数中.像这样
The code by skwon
can be made more efficient by defining the fnewton
function once outside the for loop and by putting the variables df
and i
in the arguments. Like so
fnewton <- function(x,df,i){
d1 <- (log(x[1]/df$D[i])+(df$R[i]+x[2]^2/2))/x[2]
d2 <- d1-x[2]
y <- numeric(2)
y[1] <- df$VE[i]-(x[1]*pnorm(d1)-exp(-df$R[i])*df$D[i]*pnorm(d2))
y[2] <- df$SE[i]*df$VE[i]-pnorm(d1)*x[2]*x[1]
y
}
,然后将循环更改为此
for(i in 1:nrow(df)){
xstart <- c(df$VE[i], df$SE[i])
z <- nleqslv(xstart, fnewton, method="Newton",control=list(trace=1), df=df,i=i)
df$VA[i] <- z$x[1]
df$SA[i] <- z$x[2]
}
如果功能fnewton
变得更加复杂,您还可以使用软件包compiler
加快速度(一点点).
If the function fnewton
becomes more complicated you can also use package compiler
to speed it up (a little bit).
最后,您真的应该通过测试z$termcd==1
来测试nleqslv
是否确实找到了解决方案.如果不是,则跳过z$x
值的分配.我会留给你的.
Finally you really should test that nleqslv
has in fact found a solution by testing if z$termcd==1
. If not then skip the assigning of the z$x
values. I'll leave that for you.
这篇关于在R中使用nleqslv求解许多非线性方程的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!