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 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Matt J
Matt J le 28 Jan 2020
You need to take absolute values,
ea=abs((x-x_old)/x)*100;

Plus de réponses (2)

James Tursa
James Tursa le 28 Jan 2020
Modifié(e) : James Tursa le 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;

Stijn Haenen
Stijn Haenen le 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 commentaires
N/A
N/A le 28 Jan 2020
Thank you for the help, but this just returns x not a value for x. Even using the initial equation I had an using syms x I get the equation with x left in place versus an inputted a and returns an x value that should be the square root of a.
James Tursa
James Tursa le 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by