Clear Filters
Clear Filters

Estimating SQRT of a non-negative number the long way

31 views (last 30 days)
Dylan
Dylan on 12 Apr 2024 at 16:51
Commented: Dylan on 15 Apr 2024 at 16:04
Estimate the square root of a non-negative number, then displaying the original number, the answer, and the amount of iterations it took to calculate. Cannot accept a negative or a 0. Using the divide and average method. Estimate with a tolerance less than 1e-6.
I don't know how to actually do the math of it. and I can't figure out how to get the input prompt to show up after the error messges.
clear
clc
num = input("Enter any number greater than 0 to calculate it's square root: ");
if num < 0
msg = 'Cannot calculate the square root of a negative number. Try again.';
error (msg); %display error message
else
if num == 0
msg = 'Its not very hard to calculate the square root of 0. Try again.';
error (msg); %display error message
else
n = 0;
k = 1:100; %initialize the counter?
e = 1e-6; %error tolerance <.000001
s = num/2; %the first approximation, n= )
while e > tol
sOld = s;
s = (s + (n/s)) / 2;
e = abs((s - sOld)/s);
end
end
end
%disp ("The square root of" num "is" s "and it took" __ "iterations to calculate.")

Answers (1)

John D'Errico
John D'Errico on 12 Apr 2024 at 17:26
Edited: John D'Errico on 12 Apr 2024 at 19:40
If you generate an error message, MATLAB stops execution. An error is a failure, and nothing gets past that. However, a warning message does not cause termination.
But here is a thought for you: Use a while loop. So you might do this.
num = input("Enter any number greater than 0 to calculate it's square root: ");
while num < 0
warning("Aw come on. I need it to be non-negative. Please try harder.")
num = input("Enter any number greater than 0 to calculate it's square root: ");
end
When the loop finally terminates, num will be at least zero. But until the while loop is willing to let num pass, it will just keep on asking until you make the test in the while statement fail. Actually, I might even make the warning message complain more severely, the more times it gets a negative number. You could be creative in this of course.
Even better code would worry about the user giving you a complex number, or a NaN.
  1 Comment
Dylan
Dylan on 15 Apr 2024 at 16:04
John,
Thanks for helping with that. I'm still in need of assistance with the actual math of the problem. I have to write code to approximate/calculate the squareroot of the number the user input. I'm being advised to use the divide and average method. I have a tolerance of 1e-6. So it has to iterate/calculate until it gets within that tolerance. then I have to display how many iterations/calculations it took.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!