Determining the squareroot of a number p, squareroot p, is the same as finding a
ID: 3786176 • Letter: D
Question
Determining the squareroot of a number p, squareroot p, is the same as finding a solution to the equation f(x) = x^2 - p = 0. Write a MATLAB user-defined function that determines the squareroot of a positive number by solving the equation using bisection method. Name the function Xs = SquareRoot(p). The output argument Xs is the answer, and the input argument p is the number whose squareroot 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 1 times 10^-6. 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. Use the function SquareRoot to determine the squareroot of (a) 729, (b) 1500, and (c) -72.Explanation / Answer
Matlab code:
function root = SquareRoot(p)
if(p< 0)
fprintf('Negative number entered ');
else
actual = p^(1/2);
format long;
a = 25;
b = 40;
c = a;
iter = 1;
EPSILON = 0.000001;
while (abs(actual-c) >= EPSILON & iter <= 20)
iter
c = (a+b)/2;
if (3*(c^2) - 30 == 0.0)
break;
elseif (((c^2) - p)*((a^2) - p) < 0)
b = (a+b)/2;
else
a = (a+b)/2;
end
a
b
iter = iter + 1;
end
if(iter > 20)
fprintf('More than 20 Iterations completed');
root=c
else
root=c;
end
end
end
Sample Output:
1)
>> SquareRoot(-72)
Negative number entered
2)
>> SquareRoot(729)
More than 20 Iterations completed
root =27.000012397766113
Please note that the values of a and b in bisection methode in the code need to be changed depending upon input value of p.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.