Approximating square root function using loops

Please help me solve this:
the "divide and average" method, an old-time method for approximating the square root of any positive number a, can be formulated as x=(x+a/x)/2. write a well-structured function to implement this alogrithm.
here is my first line:
function estSqrt= ApproxSqrt(a,tol)
a is the number whos square root i want to find
tol is the tolerance that must be greater than abs(xOld-xNew)/abs(xOld)

5 件のコメント

Matt J
Matt J 2019 年 2 月 6 日
I think you mean
x=(x+a/x)/2
Char Jacobus
Char Jacobus 2019 年 2 月 6 日
yeah sorry
Matt J
Matt J 2019 年 2 月 6 日
Well, you have to write more than the first line of code in order to call it "help".
Char Jacobus
Char Jacobus 2019 年 2 月 6 日
I can't seem to make this work for negative inputs of a
function estSqrt= ApproxSqrt(a,tol)
% function estSqrt= ApproxSqrt(a,tol)
e = 1;
x = a/2;
estSqrt = 1;
if a == 0
estSqrt = 0;
end
while e > tol
xOld = x;
x = (x+a/x)/2;
e=abs((x - xOld)/x);
estSqrt = x;
if a < 0
a = abs(a);
estSqrt = x*1i;
end
end
end
Matt J
Matt J 2019 年 2 月 6 日
I can't seem to make this work for negative inputs of a
Why would you need to?

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

回答 (1 件)

AKARSH KUMAR
AKARSH KUMAR 2020 年 6 月 24 日

0 投票

function estSqrt= ApproxSqrt(a,tol)
if a<0
msg='Can't calculate square root of negative number';
error(msg);
else if a==0
estSqrt=0;
else
e = 1;
x = a/2;
estSqrt = 1;
while e > tol
xOld = x;
x = (x+a/x)/2;
e=abs((x - xOld)/x);
estSqrt = x;
if a < 0
a = abs(a);
estSqrt = x*1i;
end
end
end
end

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

リリース

R2018b

質問済み:

2019 年 2 月 6 日

回答済み:

2020 年 6 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by