Вы находитесь на странице: 1из 3

str = input('Enter in the function in x: ','s');

f = str2func(['@(x)' str]);
maxErr = input('Enter maximum allowed relative error(in%): ');
maxItr = input('Enter maximum number of iterations: ');
method = menu ('Choose the method to solve the equation: ','Bisection','False
Position','Fixed Point','Newton Raphson','Secant');
e=ones(1,maxItr);

switch method
case 1
% Bisection Method
l = input('Give first guess: ');
u = input('Give second guess: ');
figure
fplot(f,[(l-10) (u+10)]);
title('f(x)vs x')
itr = 0;
if f(u)*f(l)>0
disp('wrong choice of a and b')
else
m = (u+l)/2;
itr = itr + 1;
err = 100;
while ((err > maxErr) && (itr < maxItr))
if f(u)*f(m)<0
l = m;
else
u = m;
end
% n is the new approximation, m is the older approximation
n = (u+l)/2;
err = abs((n-m)/n)*100;
e(1,itr)= err;
m = n; %making the old approximation new
itr = itr + 1;
end
end
disp (m);
figure
subplot(2,1,2)
plot (1:itr-1,e(1:itr-1))
title('Error vs Iteration')

case 2
% False Position Method
l = input('Enter smaller guess: ');
u = input('Enter bigger guess: ');
figure
fplot(f,[(l-10) (u+10)]);
title('f(x)vs x')
itr = 0;
m = l - f(l)*((u-l)/(f(u)-f(l)));
itr = itr + 1;
err = 100;
while ((err > maxErr) && (itr < maxItr))
if f(u)*f(m)<0
l = m;
else
u = m;
end
n = l - f(l)*((u-l)/(f(u)-f(l)));
err = abs((n-m)/n)*100;
e(1,itr)= err;
m = n;
itr = itr +1;
end
disp (m);
figure
subplot(2,1,2)
plot (1:itr-1,e(1:itr-1))
title('Error vs Iteration')

case 3
% Fixed Point Method
str2 = input('Enter phi(x): ','s');
phi = str2func(['@(x)' str2]);
a = input('Enter initial guess: ');
figure
fplot(f,[(a-10) (a+10)]);
title('f(x)vs x')
itr = 0;
err = 100;
while ((err > maxErr) && (itr < maxItr))
b = phi(a);
itr = itr + 1;
err = abs((b-a)/b)*100;
e(1,itr)= err;
a = b;
end
disp (b);
figure
subplot(2,1,2)
plot (1:itr,e(1:itr))
title('Error vs Iteration')

case 4
% Newton Raphson Method
% g(x) = f'(x)
str3 = input('Enter f`(x): ','s');
g = str2func(['@(x)' str3]);
a = input('Enter initial guess: ');
figure
fplot(f,[(a-10) (a+10)]);
title('f(x)vs x')
itr = 0;
err = 100;
while ((err > maxErr) && (itr < maxItr))
b = a - (f(a)/g(a));
itr = itr + 1;
err = abs((b-a)/b)*100;
e(1,itr)= err;
a = b;
end
disp (b)
figure
subplot(2,1,2)
plot (1:itr,e(1:itr))
title('Error vs Iteration')

case 5
% Secant Method
a = input('Enter first(smaller) guess: ');
b = input('Enter second(larger) guess: ');
figure
fplot(f,[(a-10) (b+10)]);
title('f(x)vs x')
itr = 0;
err = 100;
while ((err > maxErr) && (itr < maxItr))
c = b - f(b)*((b-a)/(f(b)-f(a)));
itr = itr + 1;
err = abs((c-b)/c)*100;
e(1,itr)= err;
a = b;
b = c;
end
disp (b);
figure
subplot(2,1,2)
plot (1:itr,e(1:itr));
title('Error vs Iteration')
end