Matlav Code Assignment
Matlav Code Assignment
BSCE 3C
ASSIGNMENT CE 101-C3-2
Determining the square root of a number p, , is the same as finding a solution to the equation
. Write a MATLAB user-defined function that determines the square root of a positive number
by solving the equation using Name the function . The output argument
Xs is the answer, and the input p argument is the number whose square root is determined. The program should
include the following features:
• It should check if the number is positive. If not, the program should stop and display an error message.
• The iterations should stop when the estimated relative error is smaller than .
• The number of iterations should be limited to 20. If a solution is not obtained in 20 iterations, the program
should stop and display an error message.
Function Xs=SquareRoot(p)
% check whether the given value is positive
if p<=0
error('Input must be a positive number');
end
% set the starting value of x for the iteration
x=p;
% set the allowed maximum number of iterations
maxIterations=20;
% set the allowed relative error
tolerance=1e-6;
% use newton's method for the iteration
for iteration=1:maxIterations
x_new = 0.5*(x+p/x);
% Check for the proximity using relative error
if abs(x_new-x)/x<tolerance
Xs=x_new;
return;
end
% Update the current value
x=x_new;
end
1
% For (a) 729
% Check if the number is positive
p = input('Enter the number to be squared:');
if (p < 0)
disp('Error! The number is negative.');
else
disp('Hooray! The number is positive.');
end
Xs = 27
x1 = 365.000000
x2 = 183.498630
x3 = 93.735706
x4 = 50.756446
x5 = 32.559577
x6 = 27.474651
x7 = 27.004100
x8 = 27.000000
x9 = 27.000000
2
% For (b) 1500
% Check if the number is positive
p = input('Enter the number to be squared:');
if (p < 0)
disp('Error! The number is negative.');
else
disp('Hooray! The number is positive.');
end
Xs = 38.7298
x1 = 750.500000
x2 = 376.249334
x3 = 190.118026
x4 = 99.003931
x5 = 57.077422
x6 = 41.678758
x7 = 38.834157
x8 = 38.729974
x9 = 38.729833
x10 = 38.729833
3
clear, clc, close all
% For (c) -72
% Check if the number is positive
p = input('Enter the number to be squared:');
if (p < 0)
disp('Error! The number is negative.');
else
disp('Hooray! The number is positive.');
end