For the Crank-Nicolson method we shall need:
A sample program structure for the Crank-Nicolson method may look something like:
First we must carry out the initial setup phase where we assign values to parameters such as
,
and resize any vectors that depend on the choice of grid size
and
. Also we can now assign values to vectors such as stock values (that remain constant throughout) and the final payoff condition to the option values.
Now create a time loop (check that it runs for the appropriate amount of loops) and finishes at the correct time. Try to avoid using while loops that evaluate a condition on a double, use integers instead. Inside the loop the code will be broken into two sections, matrix setup and matrix solver, both of which may be written into functions later. See the example linked below for how to setup and solve the matrix equations.