Can't figure out what I am doing wrong. Looking to find square root using the equation given x=(x+x/a)/2. I also feel like I am not making use of the approximation errors ea and es.

조회 수: 21(최근 30일)
William Donovan
William Donovan 2020년 1월 28일
댓글: James Tursa 2020년 1월 28일
Having trouble determining what I am doing wrong. I don't feel like I am initiallizing x incorrectly, because that is what I am trying to solve for. Not sure if I am making use of ea and es error approximations as well.
code is as follows:
a=input('Enter Number'); %User input number
ea=100; %approximate relative error 100 percent
es=0.01; %stopping point for error must be less than
count=1; %iteration beginning
countmax=1000; %max number of iterations allowed
if 0<a %must be positive number
while (count<countmax) && (es<ea) %How is es/ea even a factor???
x=(x+(a/x))/2; %equation to solve for square root
disp(x); %show answer
msgbox("Enter Positive Number") %number entered not positive

채택된 답변

Matt J
Matt J 2020년 1월 28일
You need to take absolute values,

추가 답변(2개)

James Tursa
James Tursa 2020년 1월 28일
편집: James Tursa 2020년 1월 28일
You can't do these assignments in this order:
The first one will cause the second one to always be exactly 0. You need to reverse the order of these equations (with the abs( ) that Matt J points out):
Because of that, you will need to initialize x_old prior to the start of the loop:
x_old = x;
And, it is quite unfair to start your iteration process at exactly the answer. So this line needs to be replaced:
x = sqrt(a);
Pick something else. For simplicity, maybe just
x = a;

Stijn Haenen
Stijn Haenen 2020년 1월 28일
just use this to solve x=(x+x/a)/2
syms x
  댓글 수: 2
James Tursa
James Tursa 2020년 1월 28일
@Stijn: The original question is not asking how to solve an algebraic equation for x, but how to fix the iterative code for calculating the sqrt of a number. Two completely different things.

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

Community Treasure Hunt

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

Start Hunting!

Translated by