0
$\begingroup$

So this is my code for Euler's method to approximate ode's. f_ being the ode, t0_ the start of the interval, tf_ the end, y0_ initial condition, h_ the step size, and y_ is a given exact solution.

euler[f_, t0_, y0_, tf_, h_, y_] := Module[{},  
 t[0] = t0;  
 w[0] = y0;  
 n = Rationalize[(tf - t0)/h];  
Do[  
  w[i] = w[i - 1] + h*f[t[i - 1], w[i - 1]];  
  t[i] = t[i - 1] + h,  
  {i, 1, n}];  
Print["Euler's Method Results:"];  
TableForm[  
Table[{i, t[i], w[i], y[t[i]], Abs[w[i] - y[t[i]]]}, {i, 0, n}],   
TableHeadings -> {None, {"i", "ti",  
   "Euler's \nMethod \nwi","Exact \nSolution\ny(ti)",  
   "Absolute \nError \n|wi-y(ti)|\n"}},  
TableAlignments -> Center, TableSpacing -> {2, 5}  
]  
]  

The code works fine so I'm not worried about that, but I can't figure out how to plot the Euler's method solution. I expect it to be something like

Plot[w[i], {i, 0, n}, PlotLabel -> "Exact solution",AxesLabel -> {"t", "y"}]

but I can't seem to make it work.

$\endgroup$
11
  • $\begingroup$ Have you seen this? $\endgroup$ Apr 9, 2018 at 13:28
  • $\begingroup$ Yeah I was just looking at that and I will admit I do not understand it. I'm not really a cs person, just a math student who got pulled into a mathematica class. My professor walked us through the code that I have, but we ran out of time before she showed us how to plot it. $\endgroup$
    – JakeRyan34
    Apr 9, 2018 at 13:31
  • $\begingroup$ Well, I'm not a "CS person" either. ;) Anyway: so you wrote this implementation of Euler's method yourself, or is this adapted from your prof's implementation? $\endgroup$ Apr 9, 2018 at 13:33
  • $\begingroup$ Yeah it's adapted from hers. She pretty much gives everyone the code for an example and then changes the question a little bit on the homework. I guess so everyone does it in a similar way $\endgroup$
    – JakeRyan34
    Apr 9, 2018 at 13:36
  • 1
    $\begingroup$ I had asked because the programming style really isn't something I can endorse, but this isn't a good time to give your prof surprises. Anyway, try this: euler[f_, t0_, y0_, tf_, h_] := Module[{n, t, w}, t[0] = t0; w[0] = y0; n = Rationalize[(tf - t0)/h]; Do[w[i] = w[i - 1] + h f[t[i - 1], w[i - 1]]; t[i] = t[i - 1] + h, {i, 1, n}]; ListLinePlot[Table[t[i], w[i], {i, 0, n}]]]. $\endgroup$ Apr 9, 2018 at 13:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.