0
$\begingroup$

I am having trouble using mathematica to do Euler integration of the following function. I keep getting nonsense for values. The code I used is as follows. I don't know where my mistakes are.

 a==0
 b==5
 h=(b-a)/steps
 steps==50
 f=f(t,y)=-y+t+1
 y0==1
 euler[f,a,y0,b,steps]
 Module[{t,y,h,i},t[0]=a,y[0]=y0,Do[t[i]=a+h,y[i]=y[i-1]+h f[t[i-1],y[i-1]], 
 {i,1,50}],Table[{t[i],y[i],{i,1,50}]]

Any help would be highly appreciated.

$\endgroup$
2
1
$\begingroup$

Try this

a = 0.;
b = 5.;
y0 = 1;
steps = 50;
f[t_, y_] := -y + t + 1

euler[f_, a_, y0_, b_, steps_] := Module[{t, y, i, path, h = (b - a)/steps},
t = a;
y = y0;
path = {{t, y}};

For[i = 1, i <= steps, i++,
  t = t + h;
  y = y + h f[t, y];
  AppendTo[path, {t, y}]
  ];

Return[path]
];


yt = y[t] /. DSolve[{Derivative[1][y][t] == 1 + t - y[t], y[0] == y0}, y, {t, a, b}][[1]]
Show[Plot[yt, {t, a, b}], ListPlot[euler[f, a, y0, b, steps]]]
$\endgroup$
2
  • $\begingroup$ I tried the code and it did not work. It just shows me that Mathematica is running. I let it run for about an hour and never got an answer. $\endgroup$ Apr 30 '20 at 5:56
  • $\begingroup$ Under version 11.0 runs perfectly. $\endgroup$
    – Cesareo
    Apr 30 '20 at 10:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.