Runge-Kutta Method - Mathematica Implementation Part 2

Numerical Methods for Solving Differential Equations

The Runge-Kutta Method

Mathematica Implementation

 

(continued from last page...)

For reference, I'll repeat the program on this page too:

euler[f_,{x_,x0_,xn_},{y_,y0_},steps_]:=

Block[{ xold=x0,
    yold=y0,
    sollist={{x0,y0}},
    x,y,h
  },

  h=N[(xn-x0)/steps];

  Do[ xnew=xold+h;
    ynew=yold+h*(f/.{x->xold,y->yold});
    sollist=Append[sollist,{xnew,ynew}];
    xold=xnew;
    yold=ynew,
    steps
  ];

  Return[sollist]
]

The red-highlighted parts of the code are the only locations in the program that actually require any modification. If you sift through the rest of the code carefully you should be able to see that it has nothing to do with the algorithm being used, and is merely concerned with the nitty-gritty of constructing our list of solution points, etc., as discussed in great detail in the previous lab.

Obviously the name of the program should no longer be "euler," since we're now planning on using the Heun algorithm. A more appropriate name would be "RK4," of course, so we'll make that modification.

More importantly, the method we're using to predict the next y-value is now much more sophisticated, namely:

yn+1 = yn + (1/6)(k1 + 2k2 + 2k3 + k4)

where

k1 = h f(xnyn)

k2 = h f(xn + h/2, yn + k1/2)

k3 = h f(xn + h/2, yn + k2/2)

k4 = h f(xn + hyn + k3)

We need to modify the line:

ynew=yold+h*(f/.{x->xold,y->yold});

accordingly, making appropriate changes to put the above formula into the language of Mathematica. This is something I'm going to leave you to do by yourself, however, I will point out that it will be necessary to insert multiple new lines of code into the program in order to calculate the ki before attempting to find ynew. There is actually more than one way to modify the code and get the correct results from the program, so feel free to use your own initiative here.

Switch back to Mathematica now, and make the two necessary changes to the Euler program, then save your notebook and come back here to your web browser.

Welcome back. In order to see whether or not your program is working properly, we will now move on and give it a work out.


Compass If you're lost, impatient, want an overview of this laboratory assignment, or maybe even all three, you can click on the compass button on the left to go to the table of contents for this laboratory assignment.