CENG 202-Tutorial1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

UNIVERSITY OF BAHRAIN

Civil Engineering Department

CENG 202 NUMERICAL ANALYSIS

APPROXIMATING FUNCTIONS BY TAYLOR EXPANSION

TUTORIAL 1

Q.1 Expand the following functions about a=0 using Taylor’s series. Then write a Matlab
code to calculate approximate values, true values and the relative true errors of the
function for given specific values. Do the calculations for number of terms ranging from
1-5.


a) f(x) = cos(x) calculate the function value at x 
4


b) g(x) = sin(x) calculate the function value at x 
4

Q.2 Expand the following function to Taylor series around a=0 until fifth terms
1
f ( x) 
x 1
Then write a Matlab program to calculate the approximate values of the function and
relative true errors at x=0.5 for each terms ranging from 1-5.
f(x)=Cos(x) 

n=input('enter the number of terms=');


x=input('enter the value of x=');
csx=0;
cx=cos(x);
disp(['# of terms cos(x) error'])
for i=1:n;
p=2*i-2;
csx=csx+(-1)^(i-1)*x^p/factorial(p);
error=abs((cx-csx)/cx);
disp([i,csx,error])
end
Result
enter the number of terms=5
enter the value of x=pi/4
# of terms cos(x) error
1.0000 1.0000 0.4142

2.0000 0.6916 0.0220

3.0000 0.7074 0.0005

4.0000 0.7071 0.0000

5.0000 0.7071 0.0000

g(x)=Sin(x) 

n=input('enter the number of terms=');


x=input('enter the value of x=');
snx=0;
sx=sin(x);
disp(['# of terms cos(x) error'])
for i=1:n;
j=2*i-1;
snx=snx+(-1)^(i-1)*x^j/factorial(j);
error=abs((sx-snx)/sx);
disp([i,snx,error])
end

enter the number of terms=5


enter the value of x=pi/4
# of terms cos(x) error
1.0000 0.7854 0.1107

2.0000 0.7047 0.0035

3.0000 0.7071 0.0001

4.0000 0.7071 0.0000

5.0000 0.7071 0.0000

h(x)=

n=input('enter the number of terms=');


x=input('enter the value of x=');
fapx=0;
ftrue=sqrt(x+1);
p=1;
disp(['# of terms fapx error'])
for i=1:n;
k=3/2-i;
j=i-1;
fapx=fapx+x^j*p/factorial(j);
p=p*k;
error=abs((ftrue-fapx)/ftrue);
disp([i,fapx,error])
end

enter the number of terms=5


enter the value of x=1
# of terms fapx error
1.0000 1.0000 0.2929

2.0000 1.5000 0.0607

3.0000 1.3750 0.0277

4.0000 1.4375 0.0165

5.0000 1.3984 0.0112


Taylor expansion code for f(x)=ex at a=0

n=input('enter n');
x=input('enter x');
expx=0;
ex=exp(x);
disp(['n expx error'])
for i=1:n;
k=i-1;
expx=expx+ (x^k)/factorial(k);
error=abs((ex-expx)/ex);
disp([i expx error])
end

You might also like