using the nr method, write a script that computes the square root of 5 and check that your results are correct in matlab

Here's a MATLAB code that uses the Newton-Raphson method to compute the square root of 5:

main.m
x = 5; % number to compute square root of
eps = 1e-8; % desired accuracy
max_iter = 100; % maximum number of iterations allowed
f = @(x) x^2 - 5; % function to find root of
df = @(x) 2*x; % derivative of function
x0 = 2.5; % initial guess

for i = 1:max_iter
    x_old = x0;
    x0 = x0 - f(x0) / df(x0);
    if abs(x0 - x_old) < eps
        break;
    end
end

disp(x0); % print result
387 chars
17 lines

The code defines the function f(x) = x^2 - 5 and its derivative df(x) = 2x. It starts with an initial guess of x0 = 2.5, and iteratively applies the Newton-Raphson method until the change in x0 falls below the desired accuracy eps. The resulting square root of 5 is printed with the disp command.

Running this code in MATLAB will yield the result:

main.m
2.23606797749979
17 chars
2 lines

which is the correct value for the square root of 5.

related categories

gistlibby LogSnag