3
$\begingroup$

I would like to solve $y'(x)=x^2-y^2,y(0)=4$ with two ways, NDSolve and Euler method, and with Runge-Kutta maybe. Then, I 'll try to plot all of them in one graph. I had with NDSolve:

s = NDSolve[{y'[x] == x^2-y[x]^2, y[0] == 4}, y, {x, 0, 30}]
Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All]

For Euler method, I tried:

f[x_, y_] := x^2 - y^2
P[q_, h_, N_] := (u[0] = 1; 
Do[u[n + 1] = 
u[n] + h f[n h + (h q/2), u[n] + (h q/2) f[n h, u[n]]], {n, 0, N}])
P[1, 0.01, 30]

but I didn't get anything. I also tried:

y = 4; t = 0.0;
n = 20; h = 6/n;
f[y_, t_] := t^2-y^2;
ξ = {y};
Do[(y = y + f[y, t] h;
t = t + h;
ξ = Join[ξ, {y}]), n]

p = Transpose[{Range[0, n]/n, ξ}];

Clear[y, t];
y = 4; t = 0.0;
n = 20; h = 6/n;
f[y_, t_] := t^2- y^2;
ξ = {y};
Do[(y = y + f[t + h/2, y + h f [y, t]/2] h;
t = t + h;
ξ = Join[ξ, {y}]), n]

s = Transpose[{Range[0, n]/n, ξ}];

Clear[y, t];
DSolve[{y'[t] == t^2- y[t]^2, y[0] == 4}, y[t], t]

q = Plot[Evaluate[y[t] /. %], {t, 0, 6}, PlotStyle -> Gray];

Show[q, ListPlot[p, PlotStyle -> Blue], ListPlot[s, PlotStyle -> Red]]

Any help?

$\endgroup$
1
  • 2
    $\begingroup$ Try Block[{nn=30, q=0.01}, Graphics[{ Line[Table[{n h + (h q/2), u[n]},{n, 0, nn+1}]]. Notes: Do[] has no output. N is a protected, highly-used, system symbol. You should not use it for your own purposes. $\endgroup$
    – Michael E2
    Jan 19, 2020 at 0:46

2 Answers 2

5
$\begingroup$
x[0] = 0;(*Supplementary conditions*)
y[0] = 4.;
h = 0.1;
f[x_, y_] := x^2 - y^2
x[n_] := n h + x[0]
y[n_] := y[n] = y[n - 1] + h f[x[n - 1], y[n - 1]]
data = Table[{x[i], y[i]}, {i, 0, 10}];
Show[Plot[
  Evaluate[yy[x] /. 
    First[NDSolve[{yy'[x] == x^2 - yy[x]^2, yy[0] == 4}, 
      yy[x], {x, 0, 1}]]], {x, 0, 1}, PlotStyle -> {Red, Dashed}], 
 ListLinePlot[data, AxesOrigin -> {0, 0}, Mesh -> Full], 
 PlotRange -> {0, 4}]
$\endgroup$
2
$\begingroup$

You can always supply the statement as an argument for NDSolve, Method -> {"TimeIntegration" -> "ExplicitEuler"}, or Method -> {"TimeIntegration" -> {"ExplicitRungeKutta", "DifferenceOrder" -> d}} where d is the chosen order you want.

$\endgroup$

Your Answer

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

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