Integration af 2. ordens differentialligning.
Simpel metode, Afsnit 20.3, opgave 3 og 9. 
Samt opgave 12 (Runge-Kutta-Nystrom).

Opgave 3

Clear[x,y,f,Y];

DSolve[{y''[x]==-y[x],y[0]==0,y'[0]==1},y[x],x]

Y[x_] = Sin[x];

f[x_,y_,y1_] = - y;

h = 0.1; n = 5; x[0] = 0; Do[x[i] = x[i-1]+h,{i,n}];

y[0]=0;  y1[0]=1; y2[0]=f[x[0],y[0],y1[0]];

Do[{
y[i] = y[i-1]+h y1[i-1]+ 0.5 h^2 y2[i-1],
y1[i] = y1[i-1] +h y2[i-1], 
y2[i] = f[x[i],y[i],y1[i]]
},{i,n}]

z=Table[{x[i-1],y[i-1]},{i,n+1}];
w=Table[{x[i-1],y[i-1],Y[x[i-1]],Y[x[i-1]]-y[i-1]},{i,n+1}];

\(TableForm[w, \ 
      TableHeadings -> 

        		{None, {\*""\!\(x\_n\)"", \*""\!\(y\_n\)"", 
            \*""y(\!\(x\_n\))"", \*""\!\(ϵ\_n\)""}}]\)

g1=ListPlot[z,PlotStyle->{PointSize[0.015],RGBColor[1,0,0]}]

g2=Plot[Y[x],{x,0,0.5}]

Show[g1,g2]

Opgave 9

Clear[x,y,f,Y,w];

Y[x_] = x^4  -  6  x^2  +  3;

f[x_,y_,y1_] = x y1 - 4 y;

h = 0.1; n = 5; x[0] = 0; Do[x[i] = x[i-1]+h,{i,n}];

y[0]=3;  y1[0]=0; y2[0]=f[x[0],y[0],y1[0]];

Do[{
y[i] = y[i-1]+h y1[i-1]+ 0.5 h^2 y2[i-1],
y1[i] = y1[i-1] +h y2[i-1], 
y2[i] = f[x[i],y[i],y1[i]]
},{i,n}]

z=Table[{x[i-1],y[i-1]},{i,n+1}];
w=Table[{x[i-1],y[i-1],Y[x[i-1]],Y[x[i-1]]-y[i-1]},{i,n+1}];

\(TableForm[w, \ 
      TableHeadings -> 

        		{None, {\*""\!\(x\_n\)"", \*""\!\(y\_n\)"", 
            \*""y(\!\(x\_n\))"", \*""\!\(ϵ\_n\)""}}]\)

g3=ListPlot[z,PlotStyle->{PointSize[0.015],RGBColor[1,0,0]}]

g4=Plot[Y[x],{x,0,0.5}]

Show[g3,g4]

Integration af 2. ordens differentialligning.
Runge-Kutta-Nystrom metoden, Afsnit 20.3, opgave 12:

Clear[x,y,f,Y];

Y[x_] = BesselJ[0,x];

f[x_,y_,y1_] = - y1/x - y;

h = 0.5; n = 5; x[0] = 1;Do[x[i] = x[i-1]+h,{i,n}];

y[0]=0.765197687;  y1[0]=-0.44005059; 
y2[0]=f[x[0],y[0],y1[0]];

Do[{
k1=0.5h f[x[i-1],y[i-1],y1[i-1]],
K=0.5h(y1[i-1]+0.5k1),
k2=0.5h f[x[i-1]+0.5h,y[i-1]+K,y1[i-1]+k1],
k3=0.5h f[x[i-1]+0.5h,y[i-1]+K,y1[i-1]+k2],
L=h(y1[i-1]+k3),
k4=0.5h f[x[i-1]+h,y[i-1]+L,y1[i-1]+2k3],
y[i] = y[i-1]+h (y1[i-1]+ (k1+k2+k3)/3),
y1[i] = y1[i-1] + (k1+2k2+2k3+k4)/3 
},{i,n}]

z=Table[{x[i-1],y[i-1]},{i,n+1}];
w=Table[{x[i-1],y[i-1],N[Y[x[i-1]]],N[Y[x[i-1]]]-y[i-1]},{i,n+1}];

\(TableForm[w, \ 
      TableHeadings -> 

        		{None, {\*""\!\(x\_n\)"", \*""\!\(y\_n\)"", 
            \*""y(\!\(x\_n\))"", \*""\!\(ϵ\_n\)""}}]\)

g1=ListPlot[z,PlotStyle->{PointSize[0.015],RGBColor[1,0,0]}]

g2=Plot[Y[x],{x,1,4}]

Show[g1,g2]

Mathematica's numeriske løsning af opgave 12:

Clear[x,y,f,z,w]

solution = NDSolve[{x y''[x] + y'[x] + x y[x]==0,
y[1]==0.765197687, y'[1]==-0.44005059},y[x],{x,1,4},
AccuracyGoal -> 10];

x=0.5; h=0.5;
Table[{x=x+h,w=y[x] /.Flatten[solution],
z=N[BesselJ[0,x]],z-w},{i,6}];

\(TableForm[%, \ 
      TableHeadings -> 

        		{None, {\*""\!\(x\_n\)"", \*""\!\(y\_n\)"", 
            \*""y(\!\(x\_n\))"", \*""\!\(ϵ\_n\)""}}]\)