0% found this document useful (0 votes)
3 views2 pages

Q2 New

The function 'Squareone' implements Newton's method to find the square root of a non-negative number up to 20 iterations. It checks for exact or approximate solutions within a specified tolerance and handles negative inputs with an error message. The function outputs the true or approximate solution based on the iterations performed.

Uploaded by

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

Q2 New

The function 'Squareone' implements Newton's method to find the square root of a non-negative number up to 20 iterations. It checks for exact or approximate solutions within a specified tolerance and handles negative inputs with an error message. The function outputs the true or approximate solution based on the iterations performed.

Uploaded by

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

function [Xs] = Squareone(p)

%SquareRoot Finds square root of a function


% Uses Newton's method to find the quare root of a number for upto 20
% iterations
% Returns the root

format long;

F = @(x) x^2 - p;

syms Fd(x) x;
Fd(x) = @(x) 2*x;

Tolerance = 1e-6;
xEST = p;
i = 0;

if p >= 0
if F(xEST) == 0
fprintf('True solution: %0.6f\n', xEST);
Xs = xEST;
else
if F(xEST) <= Tolerance
fprintf('Approximate solution: %0.6f\n', xEST);
Xs = xEST;
else
while i <= 20

xEST = xEST - (F(xEST) / Fd(xEST));

if F(xEST) == 0
fprintf('True solution: %0.6f\n', xEST);
Xs = xEST;
break;
else
if F(xEST) <= Tolerance
fprintf('Approximate solution: %0.6f', xEST);
Xs = xEST;
break;
else
i = i + 1;
end
end
end
if i > 20
fprintf('Max iteration reached(20)');
end
end
end
else
fprintf('Error: Input is negative!\n');
end
end

You might also like