Simpsons' Method
Simpsons' Method
f = @(x) x.^3 - 6*x.^2 + 11*x - 6.1; g = @(x) exp(-x); f = @(x) x.^4 - 6*x.^2 + 11*x - 6.1; intervalBegin = 0;
df = @(x) 3*x.^2 - 12*x + 11; x0 = 2.5; intervalEnd = 0.8;
x0 = 1.5; exact_val = 1.640533; %
% Initial guess for the root tol = 1e-6; x1 = 3.0; Given exact value
x0 = 3.5; max_iter = 30; n = 15;
% Tolerance and maximum number of iterations tol = 1e-6; n = 4; % Number of intervals
tol = 1e-6; x_vals = zeros(1, max_iter); (must be even for Simpson's
max_iter = 20; errors = zeros(1, max_iter); x_value = zeros(1, n); 1/3 rule)
f_value = zeros(1, n); if mod(n,2) ~= 0
% Arrays to store the iterations % Fixed-point iteration iteration_time = zeros(1, n); error('n must be even for
x_vals = zeros(1, max_iter); x = x0; Simpson''s 1/3 rule.');
y_vals = zeros(1, max_iter); for i = 1:max_iter for i = 1:n end
errors = zeros(1, max_iter); x_new = g(x); tic;
x_vals(i) = x; x_new = x1 - f(x1) * (x1 - x0) / (f(x1) - dx = (intervalEnd -
% Newton-Raphson iteration f(x0)); intervalBegin) / n; % Step size
x = x0; % Calculate relative approximate error x_value(i) = x_new;
for i = 1:max_iter if i > 1 f_value(i) = f(x_new); % Generate x values
x_new = x - f(x) / df(x); errors(i) = abs((x_new - x) / x_new) * 100 iteration_time(i) = toc; x = linspace(intervalBegin,
x_vals(i) = x; end intervalEnd, n+1);
y_vals(i) = f(x); fprintf('Iteration %d: x_new = %.6f, fx = y(x); % Compute function
% Check for convergence f(x) = %.6f, Time = %.6f seconds\n', ... values
% Calculate relative approximate error if abs(x_new - x) < tol i, x_new, f_value(i), iteration_time(i));
if i > 1 x_vals = x_vals(1:i); % Apply Simpson's 1/3 Rule
errors(i) = abs((x_new - x) / x_new) * 100; errors = errors(2:i); if abs(x_new - x1) < tol integral = fx(1) + fx(end); %
end fprintf('Converged to root: x_value = x_value(1:i); First and last terms
%.6f after %d iterations\n', x_new, i); f_value = f_value(1:i);
% Check for convergence break; iteration_time = iteration_time(1:i); % Summing up intermediate
if abs(x_new - x) < tol end break; terms
x_vals = x_vals(1:i); x = x_new; end for i = 2:n
y_vals = y_vals(1:i); if mod(i,2) == 0
errors = errors(2:i); if i == max_iter x0 = x1; integral = integral + 4 *
fprintf('Converged to root: %.6f after fprintf('Max iterations reached x1 = x_new; fx(i); % Coefficient 4 for odd
%d iterations\n', x_new, i); without convergence\n'); end index
break; errors = errors(2:end); else
end end x_range = linspace(0, 3.5, 400); integral = integral + 2 *
x = x_new; end figure; fx(i); % Coefficient 2 for even
hold on; index
if i == max_iter % Plot the function g(x) and the iterations plot(x_range, f(x_range), 'b-', end
fprintf('Max iterations reached without x_range = linspace(0, 3.5, 400); 'LineWidth', 2); end
convergence\n'); figure; xlabel('x');
errors = errors(2:end); hold on; ylabel('f(x)'); result = (dx/3) * integral; %
end title('Secant Method Convergence'); Final integral result
end % Plot the function g(x) grid on; error = abs((exact_val - result)
plot(x_range, g(x_range), 'b-', 'LineWidth', 2); / exact_val) * 100; %
% Plot the function and the iterations xlabel('x'); for i = 1:length(x_value) Percentage error
x_range = linspace(0, 5, 400); ylabel('g(x)'); plot(x_value(i), f_value(i), 'ro');
figure; title('Fixed-Point Iteration Convergence'); plot([x_value(i) x_value(i)], % Display results
hold on; grid on; [0 f_value(i)], 'r--'); fprintf('Number of intervals
end (n): %d\n', n);
% Plot the function % Plot the iterations fprintf('Step size (h): %.5f\n',
plot(x_range, f(x_range), 'b-', 'LineWidth', 2); for i = 1:length(x_vals) plot(x_value(end), f_value(end), dx);
xlabel('x'); plot(x_vals(i), g(x_vals(i)), 'ro'); 'go', 'MarkerSize', 8, 'MarkerFaceColor', fprintf('Numerical Integral
ylabel('f(x)'); plot([x_vals(i) x_vals(i)], [0 g(x_vals(i))], 'r--'); 'g'); Result (I): %.5f\n', result);
title('Newton-Raphson Method Convergence'); end legend('f(x)', 'Iterations', 'Final Root'); fprintf('Error: %.2f%%\n',
grid on; hold off; error);
% Highlight the final root
% Plot the iterations plot(x_vals(end), g(x_vals(end)), figure; % Plot Function & Simpson’s
for i = 1:length(x_vals) 'go', 'MarkerSize', 8, 'MarkerFaceColor', 'g'); plot(1:length(iteration_time), Approximation
plot(x_vals(i), y_vals(i), 'ro'); % Plot the current legend('g(x)', 'Iterations', 'Final Root'); iteration_time, figure;
guess hold off; 'r-o', 'LineWidth', 2, 'MarkerFaceColor', fplot(y, [intervalBegin
plot([x_vals(i) x_vals(i)], [0 y_vals(i)], 'r--'); % 'r'); intervalEnd], 'b', 'LineWidth',
Vertical line to the curve % Display final result and relative approximate xlabel('Iteration'); 1.5);
end fprintf('Final root found: x = %.6f\n', x_vals(end)); ylabel('Time (seconds)'); hold on;
fprintf('Function value title('Iteration Times plot(x, fx, 'ro-',
% Highlight the final root at root: g(x) = %.6f\n', g(x_vals(end))); in Secant Method'); 'MarkerFaceColor', 'r',
plot(x_vals(end), y_vals(end), 'go', 'MarkerSize', 8, for i = 2:length(errors)+1 grid on; 'LineWidth', 1.2);
'MarkerFaceColor', 'g'); fprintf('Iteration %d: Relative title('Function and Simpson’s
legend('f(x)', 'Iterations', 'Final Root'); Approximate Error = %.6f%%\n', i, errors(i-1)); 1/3 Rule Approximation');
hold off; end xlabel('x');
% Plot the relative approximate error graph
Simpsons’ Method: ylabel('y(x)');
% Display final result and relative approximate errors figure; clc; legend('f(x)', 'Simpson’s
fprintf('Final root found: x = %.6f\n', x_vals(end)); plot(2:length(errors)+1, errors, clear; Approximation', 'Location',
fprintf('Function value at root: f(x) = %.6f\n', 'r-o', 'LineWidth', 2, 'MarkerFaceColor', 'r'); % Given function 'best');
y_vals(end)); xlabel('Iteration'); y = @(x) 0.2 + 25*x - 200*x.^2 + 675*x.^3 grid on;
for i = 2:length(errors)+1 % Start from the second ylabel('Relative Approximate Error (%)'); - 900*x.^4 + 400*x.^5; hold off;
iteration since first error is undefined title('Relative Approximate
fprintf('Iteration %d: Relative Approximate Error = Error in Fixed-Point Iteration');
%.6f%%\n', i, errors(i-1)); grid on;
end
% Reference lines for O(h) and O(h^2) Trapezoidal method manual Input: Trapezoidal method Advanta
Forward, Backward and Central difference loglog(xCentral, 10*h*ones(size(xCentral)), 'k--', clc; Simple and easy to
approximation of first derivative: 'LineWidth', 1.2); % O(h) clear; implement.
clc loglog(xCentral, 10*h.^2*ones(size(xCentral)), 'm-- More accurate than
clear all ', 'LineWidth', 1.2); % O(h^2) % Get user input for function, limits, and rectangular methods.
close all iterations Works for a wide range of
Fun = @(x) exp(-x).*sin(3*x); title('Error Analysis of Numerical Differentiation func_str = input('Enter the function in functions.
dFun = @(x) -exp(-x).*sin(3*x)+ 3*exp(-x).*cos(3*x); Methods'); terms of x: ', 's'); Can be improved using the
xlabel('Step size h'); y = str2func(['@(x) ' func_str]); % Convert composite trapezoidal rule
%Generating x-values and Function Values ylabel('Absolute Error'); string to function handle
x=linspace(0,4,101); legend('Central O(h^2)', 'Forward O(h)', 'Backward
Simpsons’ Method Advantag
F=Fun(x); O(h)', 'O(h)', 'O(h^2)', 'Location', 'northwest'); intervalBegin = input('Enter the lower
1.Higher accuracy than the
h=x(2)-x(1);%Step Size grid on; limit of integration: ');
trapezoidal
hold off; intervalEnd = input('Enter the upper limit
2.Efficient for smooth
%Central Difference Method of integration: ');
functions.
xCentral=x(2:end-1); Trapezoidal method: max_iterations = input('Enter the number
3.Requires fewer subintervals
dFCenteral=(F(3:end)-F(1:end-2))/(2*h); clc; of iterations: ');
for precision.
clear; exact_val = input('Enter the exact integral
4.Can be improved using the
%Forward Difference Method value (if known, otherwise use 0): ');
composite Simpson’s rule.
xForward=x(1:end-1); n = 20;
dFForward=(F(2:end)-F(1:end-1))/h; intervalBegin = 0; % Display table header
intervalEnd = 0.8; %Integration range [0, 0.8] fprintf('\n%-10s %-10s %-15s %-10s\n', Differentiation of Continuous
%backward Difference Method exact_val = 1.640533; 'n', 'h', 'I (Integral)', 'Error (%)'); Function FD,BD,CD:
xBackward=x(2:end); fprintf('%s\n', repmat('-', 50, 1)); Applicable to complex
dFBackward=(F(2:end)-F(1:end-1))/h; % Function functions.
y = @(x) 0.2 + 25*x - 200*x.^2 + 675*x.^3 - % Loop through increasing n values Useful for discrete data.
% Plot numerical differentiation comparison 900*x.^4 + 400*x.^5; for n = 1:max_iterations Efficient for computational
figure dx = (intervalEnd - intervalBegin) / n; % methods.
plot(x, dFun(x), 'b', 'LineWidth', 1.5); % Analytical Step Size Calculation Adaptable for various
derivative dx = (intervalEnd - intervalBegin) / n; %Step Size accuracy levels.
hold on Calculation % Applying the Trapezoidal Rule
plot(xCentral,dFCenteral, 'r', 'LineWidth', 1.2) % integral = 0.5 * y(intervalBegin) + 0.5 *
Central difference %Applying the Trapezoidal Rule y(intervalEnd); Central Differentiation is
plot(xForward, dFForward, 'k', 'LineWidth', 1.2); % integral = 0.5 * y(intervalBegin) + 0.5 * better:
Forward difference y(intervalEnd); for i = 1:(n-1)
plot(xBackward, dFBackward, 'g', 'LineWidth', 1.2); % integral = integral + y(intervalBegin + Higher accuracy
Backward difference %First and last terms are weighted by 0.5 in the i*dx); (O(h2)O(h^2)O(h2)).
title('Comparison of Numerical Differentiation trapezoidal rule formula. end More balanced
Methods') for i = 1:(n-1) approximation.
xlabel('x') integral = integral + y(intervalBegin + i*dx); result = integral * dx; % Final integral Better stability.
ylabel('f''(x)') end result Improved precision with
legend('Analytical', 'Central', 'Forward', 'Backward') small step size.
grid on %Summing up function values at intermediate % Calculate error if exact value is given
hold off points. if exact_val ~= 0 Advantage of Newton R
result = integral * dx; error = (exact_val - result) / exact_val Faster convergence
% Plot function and its exact derivative * 100; (quadratic).
figure error = (exact_val - result) / exact_val; else Requires fewer iterations.
subplot(2,1,1) % First subplot for function error = NaN; % If no exact value is Efficient for smooth
plot(x, F, 'b', 'LineWidth', 1.5) %output Showing given functions.
title('Function: f(x) = e^{-x} sin(3x)') fprintf('Value of h is : %.3f\n', dx); end Less computational
xlabel('x') fprintf('The final result is: %.4f\n', result); overhead.
ylabel('f(x)') fprintf('Error: %.2f%%\n', error * 100); % Print values in table format
grid on fprintf('%-10d %-10.5f %-15.5f %-
% Generate x values for plotting 10.2f\n', n, dx, result, error);
% Plot function's exact derivative x_values = linspace(intervalBegin, intervalEnd, end
subplot(2,1,2) % Second subplot for derivative n+1);
plot(x, dFun(x), 'm', 'LineWidth', 1.5) y_values = y(x_values); % Generate x values for plotting
title('Analytical Derivative: f''(x)') x_values = linspace(intervalBegin,
xlabel('x') % Plot Function & Trapezoidal Approximation intervalEnd, n+1);
ylabel('f''(x)') figure y_values = y(x_values);
grid on fplot(y, [intervalBegin intervalEnd], 'b',
'LineWidth', 1.5); % Plot Function & Trapezoidal
hold on; Approximation
plot(x_values, y_values, 'ro-', 'MarkerFaceColor', figure;
'r', 'LineWidth', 1.2); fplot(y, [intervalBegin intervalEnd], 'b',
% Compute errors for different methods title('Function and Trapezoidal Approximation'); 'LineWidth', 1.5);
errorCentral = abs(dFCentral - dFun(xCentral)); xlabel('x'); hold on;
errorForward = abs(dFForward - dFun(xForward)); ylabel('y(x)'); plot(x_values, y_values, 'ro-',
errorBackward = abs(dFBackward - dFun(xBackward)); legend('f(x)', 'Trapezoidal Approximation', 'MarkerFaceColor', 'r', 'LineWidth', 1.2);
'Location', 'best'); title('Function and Trapezoidal
% Plot error comparison grid on; Approximation');
figure; hold off; xlabel('x');
loglog(xCentral, errorCentral, 'r', 'LineWidth', 1.5); %
ylabel('y(x)');
Central difference O(h^2)
legend('f(x)', 'Trapezoidal Approximation',
hold on;
'Location', 'best');
loglog(xForward, errorForward, 'k', 'LineWidth', 1.5); %
grid on;
Forward difference O(h)
hold off;
loglog(xBackward, errorBackward, 'g', 'LineWidth',
1.5); % Backward difference O(h)