Python Iterative Loop Plot值

时间:2013-05-30 13:37:59

标签: python for-loop pde iteration

我正在尝试使用有限差分方法在python中执行迭代计算。我从中找到了有限差分法:

http://depa.fquim.unam.mx/amyd/archivero/DiferenciasFinitas3_25332.pdf

代码计算的值是正确的。问题是它只显示最终值。我想要的是提取x方向上任何点的值,以便我可以绘制它们,以及在任何时间点提取值,例如计算中途的点的值。这是进行迭代计算的正确方法吗?代码如下所示:

import numpy as np
import scipy as sp
import time
import matplotlib as p
L=0.005
Nx=3
T=5
N1=5
k=0.5
rho=1200
c=1000
a=(k/(rho*c))
x = np.linspace(0, L, Nx+1)   # mesh points in space
dx = x[1] - x[0]
t = np.linspace(0, T, N1)    # time
dt = t[1] - t[0]
toutside=5
Coefficient = a*dt/dx**2
bi=0.5
ui = sp.zeros(Nx+1)
u = sp.zeros(Nx+1)
for i in range(Nx+1):
  ui[i] = 50 # initial values

for n in range(0, N1):

   for i in range(0,1):
      u[i] = 2*Coefficient*(ui[i+1]+bi*toutside)+(1-2*Coefficient-2*bi*Coefficient)*ui[i]
   for i in range(1,Nx):
      u[i] = Coefficient*(ui[i+1]+ui[i-1])+(1-2*Coefficient)*ui[i]
   for i in range(Nx,Nx+1):
      u[i] = 2*Coefficient*(ui[i-1])+(1-2*Coefficient)*ui[i]
      ui[:]= u #updates matrix for next loop
 print ui

我已将我的代码修改为基于danodonovan回答:

for n in range(0, N1):

for i in range(0,1):
    u[i] = 2*Coefficient*(ui[i+1]+bi*toutside)+(1-2*Coefficient-2*bi*Coefficient)*ui[i]
for i in range(1,Nx):
    u[i] = Coefficient*(ui[i+1]+ui[i-1])+(1-2*Coefficient)*ui[i]
for i in range(Nx,Nx+1):
    u[i] = 2*Coefficient*(ui[i-1])+(1-2*Coefficient)*ui[i]
    ui=u
    a=list(ui)

print a

当我尝试将整个列表从循环中取出时,只生成最终值。如何提取整个列表?这是使用前一行的值进行迭代计算以计算新行值的正确方法吗?

2 个答案:

答案 0 :(得分:0)

(如果我理解你的问题)使用matplotlib你可以做

 import matplotlib as p

 # and after your loop has completed

 p.pyplot.plot(range(0, N1), ui, 'o-')
 p.pyplot.show()

获取针对u的数据range(0, N1)的简单图表。

我不知道你期望ui成为ui[:]= u是多么奇怪的事情 - 它会将ui的副本设置为u但你不要不保留ui正在生成的ui[:]副本。

提示:将ui[:]视为与list(ui)相同

答案 1 :(得分:0)

对于初学者缩进print ui,以查看所有ui的{​​{1}}值。然后将结果附加到列表中:

N1

产生这个结果:

res = []
for n in range(0, N1):

   for i in range(0,1):
      u[i] = 2*Coefficient*(ui[i+1]+bi*toutside)+(1-2*Coefficient-2*bi*Coefficient)*ui[i]
   for i in range(1,Nx):
      u[i] = Coefficient*(ui[i+1]+ui[i-1])+(1-2*Coefficient)*ui[i]
   for i in range(Nx,Nx+1):
      u[i] = 2*Coefficient*(ui[i-1])+(1-2*Coefficient)*ui[i]
      ui[:]= u #updates matrix for next loop
   print ui
   res.append(ui.copy())

print res