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.
1 view (last 30 days)
Show older comments
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
disp(x); %show answer
x_old=x;
ea=((x-x_old)/x)*100;
count=count+1;
end
else
msgbox("Enter Positive Number") %number entered not positive
end
0 Comments
Accepted Answer
More Answers (2)
James Tursa
on 28 Jan 2020
Edited: James Tursa
on 28 Jan 2020
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 Comments
Stijn Haenen
on 28 Jan 2020
just use this to solve x=(x+x/a)/2
a=input('')
syms x
xsol=vpasolve(x==(x+x/a)/2,x)
2 Comments
James Tursa
on 28 Jan 2020
@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.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!