Estimating SQRT of a non-negative number the long way
조회 수: 3 (최근 30일)
이전 댓글 표시
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.")
댓글 수: 0
답변 (1개)
John D'Errico
2024년 4월 12일
편집: John D'Errico
2024년 4월 12일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!