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.

5 ビュー (過去 30 日間)
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

採用された回答

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

その他の回答 (2 件)

James Tursa
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;

Stijn Haenen
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 件のコメント
N/A
N/A 2020 年 1 月 28 日
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 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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by