Issue with Mathematica

Homework Statement

When I put the this code into Mathematica, it fails to plot all of the points... there are some missing points, so i decided to also tell it to display the table so I can look at the values, but some are not defined, and it puts something like y[0.95], y[0.35] or y[0.] instead. Also, I am having another problem with the scaling... it is labeling 0.05 as 1, 0.10 as 2, and so on, on the graph.

And if it helps, this Code is supposed to approximate the solution of y'=-ty+4t/y when 0<= t <= 1, where y(0)=1 and the step size h=0.05 using Runge-Kutta method of order 4. And then I need it to plot the graph using the data that I obtained.

The Attempt at a Solution

Here is my code that I put into Mathematica
Code:
w = 1; h = 0.05; t = 0; y[0] := 0;
While[t < 1, k1 = h ((-t) (w) + (4 t)/w);
k2 = h (-(t + h/2) (w + k1/2) + (4 (t + h/2))/(w + k1/2));
k3 = h (-(t + h/2) (w + k2/2) + (4 (t + h/2))/(w + k2/2));
k4 = h (-(t + h) (w + k3) + (4 (t + h))/(w + k3));
w = w + (1/6) (k1 + 2 k2 + 2 k3 + k4); t = t + h; y[t] = w];
datapts = Table[y[t], {t, 0, 1, 0.05}];
Print[datapts];
ListPlot[datapts]
And I realize now that it would have been easier to define f(x,t)... but that should affect it... lol

The output for the table is:
Code:
{y[0.],1.00374,1.01482,1.03283,1.05718,1.08709,1.1217,y[0.35],1.20149,y[0.45],1.28981,1.33533,1.38093,1.42611,1.47042,y[0.75],y[0.8],y[0.85],y[0.9],y[0.95],y[1.]}

And this is what the graph looks like:
http://img695.imageshack.us/img695/941/problem5.gif [Broken]

Last edited by a moderator:

Mapes
Homework Helper
Gold Member
I just learned about Sow and Reap. Try it out (and note the use of DataRange for setting the x-axis values):

Code:
w = 1; h = 0.05; t = 0;
datapts = Reap[While[t < 1, k1 = h ((-t) (w) + (4 t)/w);
k2 = h (-(t + h/2) (w + k1/2) + (4 (t + h/2))/(w + k1/2));
k3 = h (-(t + h/2) (w + k2/2) + (4 (t + h/2))/(w + k2/2));
k4 = h (-(t + h) (w + k3) + (4 (t + h))/(w + k3));
w = w + (1/6) (k1 + 2 k2 + 2 k3 + k4); t = t + h; Sow[y[t] = w]]];
ListPlot[Flatten[datapts[[2 ;;]]], DataRange -> {0, 1 - h}]

I just learned about Sow and Reap. Try it out (and note the use of DataRange for setting the x-axis values):

Code:
w = 1; h = 0.05; t = 0;
datapts = Reap[While[t < 1, k1 = h ((-t) (w) + (4 t)/w);
k2 = h (-(t + h/2) (w + k1/2) + (4 (t + h/2))/(w + k1/2));
k3 = h (-(t + h/2) (w + k2/2) + (4 (t + h/2))/(w + k2/2));
k4 = h (-(t + h) (w + k3) + (4 (t + h))/(w + k3));
w = w + (1/6) (k1 + 2 k2 + 2 k3 + k4); t = t + h; Sow[y[t] = w]]];
ListPlot[Flatten[datapts[[2 ;;]]], DataRange -> {0, 1 - h}]

Thank you very much :)