You are on page 1of 3

5. Solution.

b)
clear; close;
format long
N=2;err=1;
x0=0;x1=2/pi;s1=100;
f=@(x) x.^2.*sin(1./x);
disp('Step approximation')
while err>=10^(-3)/2
h=(x1-x0)/N;
s=0*h/2;
for i=1:N-1
s=s+h*f(x0+h*i);
end
s=s+f(x1)*h/2;
err=abs(s1-s);
s1=s;
disp([N, s])
N=N*2;
end

Result:

Step approximation

2.000000000000000 0.064503068866399

4.000000000000000 0.063673513579651

8.000000000000000 0.059387564754992

16.000000000000000 0.058902335031313

c)
clear; close;
format long
N=2;err=1;
x0=0;x1=1; s1=111;
f=@(x) 3*cos(x.^3);
disp('Step approximation')
while err>=10^(-8)/2
h=(x1-x0)/N;
s=f(x0)*h/2;
for i=1:N-1
s=s+h*f(x0+h*i);
end
s=s+f(x1)*h/2;
err=abs(s1-s)/3;
s1=s;
disp([N, s])
N=N*2;
end

Step approximation

2.000000000000000 2.643523230245098

4.000000000000000 2.755912152904892

8.000000000000000 2.785264907428469

16.000000000000000 2.792648819817276

32.000000000000000 2.794497055948642

64.000000000000000 2.794959246696237

1.0e+002 *

1.280000000000000 0.027950748024685

1.0e+002 *

2.560000000000000 0.027951036919146

1.0e+002 *

5.120000000000000 0.027951109143075

1.0e+003 *

1.024000000000000 0.002795112719908

1.0e+003 *

2.048000000000000 0.002795113171308

1.0e+003 *

4.096000000000000 0.002795113284158
1.0e+003 *

8.192000000000000 0.002795113312370

1.0e+004 *

1.638400000000000 0.000279511331942

6. Solution.
First we plot the graph of f, p_1(x), p_3(x) and p_5(x).

close;clear;
x0=-1;x1=1; x=x0:0.001:x1;
f=@(x) sin(pi/2*x);
p5= @(x) pi* x/2 - (pi^3* x.^3)/48 + (pi^5 *x.^5)/3840;
p3=@(x) pi* x/2 - (pi^3* x.^3)/48;
p1=@(x) pi* x/2;
plot(x,p5(x),'--')
hold on
plot(x,p3(x),'-.')
hold on
plot(x,p1(x),':')
hold on
plot(x,f(x))
legend('n=5','n=3','n=1','analytic')

The result is shown on the first graph.

And also we plot the error of p_1(x), p_3(x) and p_5(x) with respect to f.

close;clear;
x0=-1;x1=1; x=x0:0.001:x1;
f=@(x) sin(pi/2*x);
p5= @(x) pi* x/2 - (pi^3* x.^3)/48 + (pi^5 *x.^5)/3840;
p3=@(x) pi* x/2 - (pi^3* x.^3)/48;
p1=@(x) pi* x/2;
plot(x,abs(f(x)-p5(x)),'--')
hold on
plot(x,abs(f(x)-p3(x)),'-.')
hold on
plot(x,abs(f(x)-p1(x)))
legend('n=5','n=3','n=1');

The result is shown on the second graph.

You might also like