python - 如何并行化while循环?
问题描述
我正在尝试执行价值函数迭代(对于Aiyagari 模型)。我希望优化的循环在这里(编辑为包括 MWE):
beta = 0.95
r =0.03
a_lb = -1.5
a_ub = 10
y_l = 0.9
y_h = 1.1
yGrid = [y_l, y_h]
aSz = 100
nstates = 2
V0 = np.zeros((nstates, aSz))
V1 = np.zeros((nstates, aSz))
aPol = np.zeros((nstates, aSz))
Tol = 0.0001
Iter_max = 300
err = 1.0
PI = np.matrix([[0.5, 0.5],[0.09, 0.91]])
aGrid = np.linspace(a_lb, a_ub, num = aSz)
#
#
#
Iter = 0
while (err> Tol) and (Iter < Iter_max):
V0l= intp.interp1d(aGrid, V0[0,:])
V0h= intp.interp1d(aGrid, V0[1,:])
for a_today in range(aSz):
for yix in range(nstates):
def objective(a_tomorrow):
c = yGrid[yix] + (1+r)*aGrid[a_today] - a_tomorrow
exp_cont_Val = PI[yix,0] * V0l(a_tomorrow) + PI[yix,1] * V0h(a_tomorrow)
return -(-1/c + beta* exp_cont_Val)
minima_val = opt.fminbound(objective , a_lb, min(a_ub, yGrid[yix] + (1+r) *aGrid[a_today] -0.00001))
aPol[yix, a_today] = minima_val
V1[yix, a_today] = -objective(aPol[yix, a_today])
err = (abs(V1-V0)).max()
Iter = Iter+1
V0=V1.copy()
print('Iteration ' + str( Iter) + ' with error ' + str( err))
这是一个更大的循环的一部分,该循环使用二分法来查找变量的值r
。首先,我猜测一个任意值r
并用它来填充c
数组中的值。根据我的测试,循环的第一部分非常快。对于第二部分(如上所示),我认为opt.fminbound
开销最大。我尝试使用jit
,但我不断收到错误消息,我将不胜感激。
解决方案
推荐阅读
- swift - 在 Swift 中链接 Promise 以初始化自定义对象
- java - spring 框架中的@Qualifier 和 javax.inject 的区别?
- image - 如何使用 RGBA 和更多通道独立于其颜色来更改图像的颜色
- powershell - 如何在powershell中转义大括号
- javascript - Javascript Builder 模式没有看到声明的变量
- c++ - OpenGL 翻译错误,C1068 和 C2003
- c++ - 如果我们不涉及真实代码,在 gmock 中模拟是否有意义?
- javascript - 谷歌表格日历
- python - 有没有办法在不使用循环的情况下获取列表的每个元素?
- java - 每次进行更改时都运行 mvn package?