You are on page 1of 7

[1]Bisection

ff=@(x) (x^3 - 5);


a=1;
b=2;
tol=1e-5;
max=100;
if(ff(a)*ff(b)>0)
disp(' Choose [a,b] such that f(a)*f(b) < 0 !! ')
return
end
iter=0;
x = (a + b)/2.0;
while(abs(ff(x)) >= tol)
x = (a + b)/2.0;
if( ff(x) == 0 )
break;
elseif( ff(a)*ff(x) < 0 )
b = x;
else
a = x;
end
if(iter >=max)
disp(' No convergece !! ')
break
end
fprintf('\n % 5d % 10.5d % 10.5d ',iter, x, abs(ff(x)));
iter = iter + 1;
end
fprintf('\n\n');
disp(['Root of the eqn is: ' num2str(x)])
end

[2]Secant

clear all
clc
format long
f=@(x) cos(x)-x;
tol = 1e-5;
max = 100;
iter = 1;
x0 = 0.5;
x1 = 0.785;
f0 = f(x0);
f1 = f(x1);

if(f(x1)==f(x0)) disp('no convergence')


return
end
fprintf(' %-6s %-8s %-15s %-20s', ' Iter ', ' x0 ', ' x1 ',' x','f(x)');

x = x1-f1*(x1-x0)/(f1-f0);

fabs = abs(f(x));

while(fabs>=tol)

x = x1-f1*(x1-x0)/(f1-f0);
fprintf('\n % 5d % 15d % 10d % 10.5d % 17.5d ',iter, x0, x1, x, f(x));
fx = f(x);
fabs = abs(fx);
x0 = x1;
x1 = x;
f0 = f1;
f1 = fx;

if(iter==max)
disp('not found')
break;
else

iter=iter+1;
end
end
fprintf('\n\n');
disp(['Root of the eqn is: ' num2str(x)])

[3]NR
clear all;
clc;
f=@(x) x^4-2*(x^2)+x - 3;
fdash=@(x) 4*(x^3) - 4*x +1;
x0=1.6;
tol=1e-5;
if(fdash(x0)==0)
disp('error');
else
x1=x0-(f(x0)/fdash(x0));
end
while abs(f(x1)) > tol
x0=x1
x1=x0-f(x0)/fdash(x0)
end
[4]Interpolation
clear all;
t=[0 1 2 3];
v=[1 2 9 28];
A=[1 0 0 0 ; 1 1 1 1 ; 1 2 4 8 ; 1 3 9 27];
B=v';
U = A\B;
a0 = U(1);
a1 = U(2);
a2 = U(3);
a3 = U(4);

vhad=a0 + a1*t + a2*t.^2 + a3*t.^3


plot(t,v,'k-',t,vhad,'r*')
xlabel('Time');
ylabel('Voltage');
title('current');

[5]Simpson

clear all
a=(input('Enter start value'));
b=(input('Enter end value'));
n=4;
while(1)
h=(b-a)/n;
sum1=0;
for i=1:2:n-1
sum1=sum1+f(a+i*h);
end
sum2=0;
for i=2:2:n-2
sum2=sum2+f(a+i*h);
end

val=(h/3)*(f(a)+f(b)+2*sum2+4*sum1);
if(n>4)
error=val-oldval;
if(abs(error)<0.0000001)
break;
end
end
oldval=val;
n=n*2
end
disp(['value of integeration = '
num2str(val)]);

[6]Trapezoidal

clear all;
clc;
a=(input('Enter start value'));
b=(input('Enter end value'));
n=4;
while(1)
h=(b-a)/n;
sum=0;
for i=1:n-1
sum=sum+f(a+i*h);
end
val=(h/2)*(f(a)+2*sum+f(b));
if(n>4)
error=val-oldval;
if(abs(error)<0.0000001)
break;
end
end
oldval=val;
n=n*2
end
disp(['value of integeration = '
num2str(val)]);

You might also like