You are on page 1of 1

0001 // Define the function and its derivative

0001 function y=equation(x)


0002 y = 3*x - cos(x) - 1;
0003 endfunction
0005
0001 function y=derivative(x)
0002 y = 3 + sin(x);
0003 endfunction
0009
0010 // Newton-Raphson method
0001 function [root, iterations]=newton_raphson(f, df, x0, tol, max_iter)
0002 iterations = 0;
0003 while iterations < max_iter
0004 iterations = iterations + 1;
0005 x1 = x0 - f(x0) / df(x0);
0006 if abs(x1 - x0) < tol
0007 root = x1;
0008 return;
0009 end
0010 x0 = x1;
0011 end
0012 root = NaN; // Return NaN if max iterations reached without convergence
0013 endfunction
0024
0025 // Initial guess
0026 x0 = 0;
0027
0028 // Tolerance and maximum iterations
0029 tolerance = 1e-6;
0030 max_iterations = 100;
0031
0032 // Call Newton-Raphson method
0033 [root, iterations] = newton_raphson(equation, derivative, x0, tolerance, max_iterations);
0034
0035 if isnan(root)
0036 disp('Did not converge within maximum iterations');
0037 else
0038 disp(['Root found: ', string(root)]);
0039 disp(['Iterations: ', string(iterations)]);
0040 end
0041
0042 // Plot the function and root
0043 x = linspace(-2, 2, 1000);
0044 y = equation(x);
0045
0046 plot(x, y);
0047 xtitle('Graph of 3x = cos(x) + 1', 'x', 'y');
0048 xlabel('x');
0049 ylabel('f(x)');
0050 grid on;
0051
0052 // Highlight the root
0053 if ~isnan(root)
0054 plot(root, equation(root), 'ro', 'MarkerSize', 10, 'MarkerFaceColor', 'r');
0055 end

You might also like