The original post was on stackoverflow : I transfert it here.
I have to solve numerically the advection equation with periodic boundaries conditions : u(t,0) = u(t,L) with L the length of system to solve.
I start also
with u(0,x) = uexacte(0,x) = sin(2*pi*x/L)
Here the main part of the code with loop time (we use here
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
I don't understand the solution given by teacher who uses the python function
roll in this way :
# Using roll u = u - cfl/2*(roll(u,-1)- roll(u,1))
One says that with the using of
roll, we are sure to respect the periodic boundary conditions but I don't understand why ?
Indeed, my first approach was to do :
u = u[nx-1] u[1:nx-1] = u[1:nx-1] - cfl/2*(u[2:nx] - u[0:nx-2])
but this doesn't work and I don't know how to implement this periodic conditions in this way (without using
If someone could explain this matter and the trick with
roll function, this would be nice to tell it.
UPDATE 1 :
I tried with classical approach (simple recurrence formula ) like this :
# 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 = u - cfl/2*(u - u[nx-1]) # Update time t = t+dt
Indeed, the result is bad (values for each side are not the same). I could impose the theorical values at each step but in practise, we don't know always the analytical solution.
What is the trick to impose this periodic boundary condition on the numerical solution at each step of time ?
The problem with periodic boundary conditions is formulated as :
UPDATE 2 :
The solution given by LonelyProf below works fine. Thanks