How to implement Crank-Nicolson method: update f^n, f^(n+1)

I tried to implement the Crank-Nicolson method for a transport equation.

The Crank-Nicolson method

[tex]M\frac{C^{k+1}-C^k}{\Delta t}+\frac{1}{2}A[ C^{k+1}+C^k]=\frac{1}{2}(f^{k+1}+f^k)[/tex]
or in an incremental form:
[tex]M^(C^{k+1}-C^k)=-\Delta tAC^k+0.5\Delta t(f^{k+1}+f^k)[/tex]
where [tex]M^
=M+0.5\Delta t A[/tex]

I don’t know how to represent (f^{k+1}+f^k) in the time loop. I searched on the tutorial, but I didn’t find an example. Please see the attached file.

[code]while t_intermediate < Tend-0.5*dt:
#Update time parameter

#RHS: 1/2*dt*(f^(n+1)+f^(n))-dt*A*C^(k)?? = 0.5*dt * (f.vec+f.vec) - dt * a.mat * gfu.vec #wrong += invmstar * res
t_intermediate += dt
#print("\r", time + t_intermediate,   end="")

time += t_intermediate[/code]

Could you please tell me how to handle this in NGSolve? Thank you so much.

Attachment: Crank_Nicolson.ipynb

Hi dong,

if you need the right hand side from the last time-step, you can simply store this in a vector

f_last = gfu.vec.CreateVector()

and update this at the end of every time-step:

f.Assemble() = f.vec 
while t_intermediate < Tend-0.5*dt:
    f.Assemble() = 0.5*dt * (f.vec+f_last) - dt * a.mat * gfu.vec += invmstar * res
    = f.vec
    t_intermediate += dt

Best wishes,

Thank you so much, Henry. I got it.