我是这个网站的新手,我正在寻找我的python代码的答案
我的代码只是解决地下水头部扩散(使用2d隐式微分)。换句话说,我正在解决这个功能与时间有关的问题 用拉普拉斯方程:d ^ 2h / dx ^ 2 + d ^ 2h / dy ^ 2 = ds / dt 其中dh是空间中头部流动路径(dx = dy)的变化 ds是一些常数值(存储系数),dt是时间增量
所以我确实解决了在上游5米和下游3米的边界条件和我的网格是7x7单元的条件下的例子
我使用C#和matlab解决了这个问题,转换后两个答案都很接近(达到了一些精确解析解的平衡点)但是当我使用Python时我的解决方案没有达到平衡
这是我的代码与python
import numpy as np
h = np.zeros((7,7,10))
h0 = 5.
K = 2.
DT = 1.
DX = 100.
S = 0.0005
B = 8.
D = (K*B)/S
r = (D*DT)/(DX*DX)
dummy = h.shape
nrow = dummy[0]
ncol = dummy[1]
ntm = dummy[2]
print 'Groundwater Head matrix is a ', nrow, ' by ', ncol, ' matrix.','with',ntm,'increments'
for i in range(nrow):
for j in range(ncol):
for k in range(1):
h[i,j,k] = h0
continue
h[0:,0,1:] = 5.
h[0:,6,1:] = 3.
ni = 1
conv_crit = 1e-9
converged = False
while (not converged):
max_err = 0
for i in range(1, nrow - 1):
for j in range(1,ncol - 1):
for k in range(1,ntm-1):
h_old = h[i,j,k+1]
h[i,j,k+1] = (r*h[i-1,j,k+1]+r*h[i+1,j,K+1]+r*h[i,j-1,K+1]+
r*h[i,j+1,k+1]+h[i,j,k])/(1+4*r)
h[0,0:6,k+1] = h[2,0:6,k+1]
h[6,0:6,k+1] = h[4,0:6,k+1]
diff = h[i,j,k+1] - h_old
if (diff > max_err):
max_err = diff
if (max_err <= conv_crit):
converged = True
ni = ni + 1
print 'Number of iterations = ', ni - 1
print h[0:,0:,9]
print ' Error =', max_err
这是我使用python的结果
Number of iterations = 132
[[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]
[ 5. 4.40796148 3.88890558 3.5072111 3.24606331 3.0865587 3. ]]
Error = 9.17176556925e-10
这里有matlab
5.0000 4.6599 4.3229 3.9892 3.6583 3.3291 3.0000
5.0000 4.6592 4.3217 3.9879 3.6573 3.3285 3.0000
5.0000 4.6599 4.3229 3.9892 3.6583 3.3291 3.0000
5.0000 4.6606 4.3240 3.9904 3.6593 3.3296 3.0000
5.0000 4.6613 4.3250 3.9915 3.6602 3.3301 3.0000
5.0000 4.6619 4.3259 3.9925 3.6610 3.3305 3.0000
5.0000 4.6613 4.3250 3.9915 3.6602 3.3301 3.0000
matlab仅使用41次迭代
请注意,我使用了Gauss Seidel Iteration
答案 0 :(得分:0)
我想我弄清楚我的python代码有什么问题
我应该让
for k in range(ntm-1):
而不是
for k in range(1, ntm-1):
因为矩阵中的python第一个元素从零开始,并且在那里我的初始条件头值发生。也就是说,在瞬态时,地下水头将开始扩散以达到平衡,并且头部将采用直线(线性)线的形状 (我跟matlab的python索引混在一起,从一开始) 这是我的最终结果
5. 4.67229917 4.34411362 4.01349084 3.67944236 3.34142973 3. ]
[ 5. 4.67207003 4.34374374 4.01309249 3.6791206 3.3412565 3. ]
[ 5. 4.67229917 4.34411362 4.01349084 3.67944236 3.34142973 3. ]
[ 5. 4.67251271 4.34445832 4.01386208 3.67974223 3.34159116 3. ]
[ 5. 4.67271172 4.34477956 4.01420805 3.68002168 3.34174161 3. ]
[ 5. 4.67289718 4.34507894 4.01453048 3.68028211 3.34188181 3. ]
[ 5. 4.67271172 4.34477956 4.01420805 3.68002168 3.34174161 3. ]]
Error = 0.00088610885882
即使迭代次数有所改善,也只有49次迭代
感谢每个人
***注意我在上一段代码中将容差值从1e-9更改为1e-3