# 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 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:
clear
a=input('Enter Number'); %User input number
x=sqrt(a);
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
x_old=x;
ea=((x-x_old)/x)*100;
count=count+1;
end
else
msgbox("Enter Positive Number") %number entered not positive
end

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

### 채택된 답변

Matt J 2020년 1월 28일
You need to take absolute values,
ea=abs((x-x_old)/x)*100;

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

### 추가 답변(2개)

James Tursa 2020년 1월 28일
편집: James Tursa 2020년 1월 28일
You can't do these assignments in this order:
x_old=x;
ea=((x-x_old)/x)*100;
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):
ea=abs((x-x_old)/x)*100;
x_old=x;
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;
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Stijn Haenen 2020년 1월 28일
just use this to solve x=(x+x/a)/2
a=input('')
syms x
xsol=vpasolve(x==(x+x/a)/2,x)
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
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!