原来的帖子在 stackoverflow 上:我把它转移到这里。
我必须在数值上求解具有周期性边界条件的平流方程:u(t,0) = u(t,L),其中 L 是要求解的系统长度。
我也开始with u(0,x) = uexacte(0,x) = sin(2*pi*x/L)
这是带有循环时间的代码的主要部分(我们在这里使用FTCS scheme
):
V=1
L=1
# analytical solution --------------------------
def uexacte(t,x):
return sin(2*pi*(x-V*t)/L)
# 1. Centre FTCS (Forward Time Centered Space)
cfl = 0.25
nx = 10
tend = 1
#
dx = L/(nx-1.)
dt = cfl*dx/V
nt = int(tend/dt)+1
print "CFL=%5.2f tend=%4.1f --> %i iterations en temps"%(cfl,tend,nt)
# Arrays
x = linspace(0,L,nx)
# Bounadry condition
u0 = uexacte(0,x)
# Starting solution
t=0.0 ; u=copy(u0)
# Time loop
for i in range(1,nt):
# FTCS
#u[1:nx-1] = u[1:nx-1] - cfl/2*(u[2:nx] - u[0:nx-2])
# Using roll
u = u + - cfl/2*(roll(u,-1)- roll(u,1))
# Update time
t = t+dt
不明白用roll
这种方式使用python函数的老师给出的解决方案:
# Using roll
u = u - cfl/2*(roll(u,-1)- roll(u,1))
有人说使用roll
,我们肯定会尊重周期性边界条件,但我不明白为什么?
事实上,我的第一种方法是:
u[0] = u[nx-1]
u[1:nx-1] = u[1:nx-1] - cfl/2*(u[2:nx] - u[0:nx-2])
但这不起作用,我不知道如何以这种方式实现这个周期性条件(不使用roll
函数)。
如果有人可以用 来解释这件事和诀窍roll function
,那就太好了。
更新 1:
我尝试了这样的经典方法(简单的递归公式):
# Time loop
for i in range(1,nt):
# FTCS
u[1:nx-1] = u[1:nx-1] - cfl/2*(u[2:nx] - u[0:nx-2])
# Try to impose periodic boundary conditions but without success
u[0] = u[0] - cfl/2*(u[0] - u[nx-1])
# Update time
t = t+dt
事实上,结果很糟糕(每一边的值都不一样)。我可以在每一步都强加理论值,但在实践中,我们并不总是知道解析解。
在每一步的数值解上施加这种周期性边界条件的技巧是什么?
周期性边界条件的问题被表述为:
更新 2:
LonelyProf 下面给出的解决方案工作正常。谢谢