1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Issue with Mathematica

  1. Apr 27, 2010 #1
    1. The problem statement, all variables and given/known data
    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.

    2. Relevant equations



    3. The attempt at a solution
    Here is my code that I put into Mathematica
    Code (Text):
    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 (Text):
    {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: May 4, 2017
  2. jcsd
  3. Apr 27, 2010 #2

    Mapes

    User Avatar
    Science Advisor
    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 (Text):
    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}]
     
  4. Apr 27, 2010 #3
    Thank you very much :)
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook