Numerical Methods NA Lab Assignment
Numerical Methods NA Lab Assignment
Function file:
F= @(x) (x.^3)-(x.^2)+x-7
x_lower=0;
x_upper=5;
x_mid=(x_lower+x_upper)/2;
while abs(F(x_mid))>0.01
if (F(x_mid)*F(x_upper))<0
x_lower=x_mid
else
x_upper=x_mid
end
x_mid=(x_lower+x_upper)/2;
end
fprintf('the root is %g\n',x_mid)
F=
@(x)(x.^3)-(x.^2)+x-7
Command Window:
x_upper =
2.5000
x_lower =
1.2500
x_lower =
1.8750
x_upper =
2.1875
x_lower =
2.0313
x_upper =
2.1094
x_lower =
2.0703
x_lower =
2.0898
x_lower =
2.0996
Function file:
% I=h/3[f(xo)+4{f(x1)+f(x3)+....+f(x(n-1))}
% +2{f(x2)+f(x4)+...+f(x(n-2))}+f(xn)]; (n always even)
clear,clc
f=@(x) 1/(1+x^2);
xo=input('Enter the lower limit:');
xn=input('Enter the upper limit:');
n=input('Enter the Number of intervals:');
h=(xn-xo)/n;
s=f(xo)+f(xn);
for i=1:2:n-1;
s=s+4*f(xo+i*h);
end
for j=2:2:n-2
s=s+2*f(xo+j*h);
end
I=h/3*s;
fprintf('\nFinal Result by Simpson Method: %i\n',I)
command window:
Function file:
display('Equation is 1/(1+x^2)')
xl=input('Enter lower limit:');
xu=input('Enter upper upper limit: ');
n=input('Enter number of subintervals: ');
h=(xu-xl)/n;
x=xl+h;
integ=equan(xl)+equan(xu);
i=1;
while (x<xu)
if (i<=2)
integ=integ+3*equan(x);
i=i+1;
else
integ=integ+2*equan(x);
i=1;
end
x=x+h;
end
integ=integ*3*h/8
% Equation to be solved
function[eqn]=equan(x);
eqn=1/(1+x^2);
end
command window
Equation is 1/(1+x^2)
Enter lower limit:0
Enter upper upper limit: 10
Enter number of subintervals: 10
integ =
1.4199
Trapezoidal Rule
Function file:
%I=h/2[f(x0)+2{f(x1)+f(x2)....+f(x(n-1))}+f(xn)]
f= @(x) 1/(1+(x^2))
x0=input('Enter the lower limit:')
xn=input('Enter the upper limit:')
n=input('Enter the number of intervals:')
h=(xn-x0)/n;
s=f(x0)+f(xn);
for i=1 : n-1
s=s+2*f(x0+i*h);
end
I=(h/2)*s
fprintf('final resultby trapezoidal rule is:%i',I)
Command Window:
f=
@(x)1/(1+(x^2))
x0 =
xn =
n=
I=
0.7842
Function file:
x1=input('enter value of x1=')
x2=input('enter value of x2=')
n=input('number of iteration=')
f=inline('x^3-4*x-9')
y1=f(x1);
y2=f(x2);
while y1*y2>0
x1=input('enter value of x1 again=')
x2=input('enter value of x2 again=')
y1=f(x1)
y2=f(x2);
end
for i=1:n
x3=(x2*y1-x1*y2)/(y1-y2);
y3=f(x3)
if y1*y3<0
x2=x3;
y2=f(x2);
else
x1=x3;
y1=y3;
end
end
x3
Command Window:
x1 =
x2 =
number of iteration=3
n=
f=
Inline function:
f(x) = x^3-4*x-9
enter value of x1 again=1
x1 =
x2 =
y1 =
-12
x1 =
x2 =
y1 =
-12
>>
Euler's Method
Function file:
Command Window:
>> clear
enter step size:0.2
enter the starting value of x:2
enter the ending value of x:4
enter the starting value of y:1
f=
13
f=
18.1200
f=
24.5040
f=
32.4048
f=
42.1258
f=
54.0309
f=
68.5571
f=
86.2285
f=
107.6742
f=
133.6491