필터 지우기
필터 지우기

Estimating SQRT of a non-negative number the long way

조회 수: 3 (최근 30일)
Dylan
Dylan 2024년 4월 12일
댓글: Dylan 2024년 4월 15일
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.")

답변 (1개)

John D'Errico
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.
  댓글 수: 1
Dylan
Dylan 2024년 4월 15일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by