all methods
all methods
% Inside loop
while ea > accepted_error
x_n = xr - (f(xr) / g(xr));
ea = abs((x_n - xr) / x_n);
xr = x_n;
no_iterations = no_iterations + 1;
end
% Initial step
x_n = xr - (f(xr) / g(xr));
iterations(end + 1) = xr; % Store initial guess
xr = x_n;
% Plotting
x_vals = linspace(0, 1.5, 1000); % Limit x range for clearer view
y_vals = f(x_vals); % Function values for f(x)
figure
plot(x_vals, y_vals, 'b', 'LineWidth', 2) % Plot f(x) in blue
hold on
plot(iterations, f(iterations), 'ro', 'MarkerSize', 8) % Plot iteration
points in red
yline(0, 'r--', 'Final Root', 'LineWidth', 1.5) % Add horizontal line at y=0
hold off
Fixed_point iteration
i=1;
imax=10;
xo=0;
tolerance=0.1;
ea=zeros(1,imax);
val=zeros(1,imax);
f=@(x)exp(-x);
while i<imax
xnew=f(xo);
xold=xo;
val(i)=xnew;
ea(i)=abs((xnew-xold)/xnew)*100;
if ea(i)<tolerance
break
end
xo=xnew;
i=i+1;
end
xo
Secant method
clc
clear all
close all
f=inline(input("Enter the function",'s'))
a=input("Enter the upper limit")
b=input("Enter the lower limit")
maxerr=input("enter max err in %")
c=(a*f(b)-b*f(a))/(f(b)-f(a));
while abs(a-b)>maxerr
a=b;
b=c;
c=b-(f(b)*(a-b)/(f(a)-f(b)));
end
x=0:0.5:10
disp(['Root: ' num2str(c)])
plot(x,f(x));grid
title('Entered function ')
hold on
plot([c,c],[5,-5],'g','linewidth',2)
clc
clear all
syms x
format long
f(x) =0.95*x^3-5.9*x^2+10.9*x-6
disp("Initial Guesses")
Initial Guesses
x1=2.5
x0=3.5
accepted_error=0.000001;
ea=1;
i=0;
while ea>accepted_error
dx=eval(f(x1)-f(x0))/(x1-x0);
xp=x1;
x1=x1-eval(f(x1))/dx;
x0=xp;
ea=abs(x1-x0)/x1;
i=i+1;
end
root=x1
no_of_iteration=i
Bisection method:
clc
clear all
format long
%function input
f=inline(input("Enter function = ",'s'))
%acceptable error percentage input
ae=input("Enter the accepted error percentage value = ");
xl=input("Enter lower limit:")
xu=input("Enter upper limit:")
ea=100;
%first iteration outside loop
i=1;
xr= (xl+xu)/2;
x_prev=xr;
xr
i
ea=100;
%first iteration outside loop
i=1;xr= (xu*f(xl)-xl*f(xu))/(f(xl)-f(xu));xr= (xl+xu)/2;
x_prev=xr;
xr
i
clc;
clear all;
format long;
% Initialize variables
ea = 100; % Initial error (100% to
enter loop)
i = 1; % Iteration counter
xr = (xl + xu) / 2; % First midpoint
estimate
x_prev = xr; % Store previous root
estimate
iterations = [xr]; % Store root estimates
for plotting
figure;
plot(x_vals, y_vals, 'b', 'LineWidth', 2); % Plot function in blue
hold on;
plot(iterations, arrayfun(f, iterations), 'ro', 'MarkerSize', 8); % Plot
iteration points in red
yline(0, 'r--', 'Final Root', 'LineWidth', 1.5); % Horizontal line at y=0
for root
hold off;
% Set plot limits and labels
xlabel('x');
ylabel('f(x)');
title('Root-Finding Method Convergence');
legend('f(x)', 'Iterations', 'Final Root');
grid on;