首页 > 解决方案 > R中的while循环,需要更高效的代码

问题描述

我编写了一个 R 代码来联合求解以下方程。这些是需要数值程序的封闭形式的解决方案。

在此处输入图像描述

我进一步将(B)的分子和分母除以N得到算术平均值。

这是我的代码:

y=cbind(Sta,Zta,Ste,Zte)           # combine the variables
St=as.matrix(y[,c(1,3)])
Stm=c(mean(St[,1]), mean(St[,2]));   # Arithmetic means of St's
Zt=as.matrix(y[,c(2,4)])
Ztm=c(mean(Zt[,1]), mean(Zt[,2]));    # Arithmetic means of Zt's

theta=c(-20, -20);             # starting values for thetas
tol=c(10^-4, 10^-4);
err=c(0,0);                  
epscon=-0.1                

while (abs(err) > tol | phicon<0) {

### A 
eps = ((mean(y[,2]^2))+mean(y[,4]^2))/(-mean(y[,1]*y[,2])+theta[1]*mean(y[,2])-mean(y[,3]*y[,4])+theta[2]*mean(y[,4]))  
### B 
thetan = Stm + (1/eps)*Ztm              
 
err=thetan-theta
theta=thetan
epscon=1-eps

print(c(ebs,theta))

}

迭代不会因为没有满足 while 循环的第二个条件而停止,解决方案是正 epsilon。我想得到一个负的ε。我猜这需要网格搜索或 Thetas 的一系列起始值。

任何人都可以帮助以不同的方式和更有效地编码这个过程吗?或者如果我的代码有缺陷,请帮助纠正我的代码。谢谢

标签: rnumerical-methods

解决方案


如果我是对的,使用线性你的方程有形式

ΘA = a + b / ε
ΘB = c + d / ε
1/ε = e ΘA + f ΘB + g

这是一个简单的 3x3 线性系统。


推荐阅读