0% found this document useful (0 votes)
23 views4 pages

Matlab Code

The document describes using the secant method to find the root of the function f(x) = x^3 - 2x - 5. It initializes starting values for x, sets a tolerance level, and uses a while loop to iteratively calculate a new x value until the change is within tolerance or the maximum number of iterations is reached. It then plots the function and estimated root.

Uploaded by

Morney
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

Matlab Code

The document describes using the secant method to find the root of the function f(x) = x^3 - 2x - 5. It initializes starting values for x, sets a tolerance level, and uses a while loop to iteratively calculate a new x value until the change is within tolerance or the maximum number of iterations is reached. It then plots the function and estimated root.

Uploaded by

Morney
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

% Function whose root we want to find: f(x) = x^3 - 2x - 5

f = @(x) x^3 - 2*x - 5;

% Initial guesses

x0 = 2;

x1 = 3;

% Tolerance level for convergence

tolerance = 1e-6;

% Maximum number of iterations (to avoid infinite loops)

maxIterations = 100;

% Initialize relative error and iteration counter

relativeError = inf;

iterations = 0;

while relativeError > tolerance && iterations < maxIterations

% Calculate the new iteration

x_new = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));

% Calculate relative error

relativeError = abs(x_new - x1) / abs(x_new);

% Update x0 and x1 for the next iteration


x0 = x1;

x1 = x_new;

iterations = iterations + 1;

end

% After convergence, x_new should contain the root estimate

root_estimate = x_new;
Code 2

% Generate x values for plotting

x_values = linspace(0, 5, 100);

% Evaluate the function at each x value

y_values = f(x_values);

% Plot the function

plot(x_values, y_values);

hold on;

% Plot the estimated root

plot(root_estimate, f(root_estimate), 'ro', 'MarkerSize', 10);

% Add labels and title

xlabel('x');

ylabel('f(x)');

title('Graph of f(x) = x^3 - 2x - 5');

% Add a legend

legend('f(x)', 'Estimated root');


% Display the plot

hold off;

You might also like