如何加速R中的模拟

时间:2015-06-02 13:30:36

标签: r function loops simulation

下面我有一个代码试图找到一个未知的均衡价格分布(我希望细节不重要 - 这是一个游戏理论经济学问题),使用粗略的进化算法(如主循环中所见)。 / p>

然而,代码运行相对较慢,我不知道如何提高效率。我怀疑函数“profit_p1”可以​​用基于向量的方式编写,这样可以避免使用sapply的函数“profit_all”。

我不是程序员,主要使用R来编写快速模拟,所以请耐心等待。如果有人能给我一个提示,我将不胜感激。非常感谢提前!

al <- 0.4           #Parameter constraints: al >= ah > 0; al + ah < 1
ah <- 0.3           #

R0 <- al*(1-al)/(ah*(1-ah)) #Calculate relevant boundaries for R=PH/PL: R0 and R1
R1 <- (1-al)/ah             #

grid <- seq(0.01, 1, 0.01)  #Sets up a grid on the relevant interval [0,1] (100 points currently)
iter <- 10000000            #Maximal number of iterations

l <- length(grid)           #Calculate number of points in grid
pfreq <- rep(1/l, l)        #Initial guess for (symmetric) first-period price distribution: uniform over grid

#--------------------

profit_p1 <- function(p1)   #Function that gives expected profit for arbitrary price in grid
    {
    x <- sum(pfreq[grid < p1/R0])*ah*p1 +
         (1-al)*al/(1-ah) * sum(pfreq[(grid >= p1/R0 & grid < p1)]*grid[(grid >= p1/R0 & grid < p1)]) +
         (al+ah)/2 * p1 * sum(pfreq[abs(grid-p1)<0.0001]) +
         al*p1*sum(pfreq[grid > p1 & grid <= p1*R0]) +
         (1-ah)*ah/(1-al) * sum(pfreq[(grid > p1*R0 & grid <= p1*R1)]*grid[(grid > p1*R0 & grid <= p1*R1)]) +
         (1-ah)*p1 * sum(pfreq[grid > p1*R1])
    return(x)
    }

profit_all <- function()    #Function that gives expected profit for all prices in grid
    {
    return(sapply(grid,profit_p1))
    }

#--------------------

for(count in 1:iter)        #Main loop
{

pfreq[which.max(profit_all())] <- pfreq[which.max(profit_all())] + 0.0001   # The freq. of the grid point which yields the highest expected profit is increased slightly
pfreq <- pfreq / sum(pfreq)                         # But of course, the total probability mass must sum up to 1

#--------------------

if(count %% 100 == 0)                               # Display price distribution and expected profits after every 100 iterations
{
plot(grid, profit_all(), ylim = c(0,0.5), type="l")
lines(grid, pfreq / max(pfreq)*0.4, col="orange")
}

#--------------------

}

0 个答案:

没有答案