What is wrong with my function?
Mostra commenti meno recenti
Hi! I'm doing this homework problem: "Edmond Halley invented a fast algorithm approximates A^0.5 as follows: Start with an initial guess x1. The new approximation is then given by Yn=(1/A)*xn^2 xn+1=(xn/8)(15-yn(10-3yn)). These calculations are repeated until some convergence criterion, e is met. xn+1-xn<=e. Write a MATLAB function that approximates the square root of a number."
I tried with this code to calculate the square root if 4 but it doesn't work:
function m=my_sqrt(g,c)
A=4;
b=g;
for abs(g-b)<=c
Yn=(1/A)*g^2;
g=(g/8)*((15-Yn)*(10-3*Yn));
end
m=g
end
Can someone please help me to find what I've done wrong?
Risposte (1)
You need to use a while loop, not a for loop. And you need to learn to indent your code consistently and use code comments to describe what you are doing. I know beginners often think that these things are not important, but we get plenty of questions here from people whose bugs could be fixed by simply writing neater code. For example:
((15-Yn)*(10-3*Yn))
is not what the algorithm you were given states. Check it. Anyway, try this on for size:
function xn = my_sqrt(A,xn,e)
xp = Inf;
while abs(xn-xp)>e
xp = xn;
yn = (1/A)*xn^2;
xn = (xn/8)*(15-yn*(10-3*yn));
end
and tested:
>> my_sqrt(4,1.5,0.1)
ans =
1.9998
>> my_sqrt(9,1.5,0.1)
ans =
3
Learn to use the debugging tools: you really really really need to learn how to use these. Also learn to write code one line at-a-time: beginners often come here after writing lots of code and they don't actually know what their own code is doing. Did they check it? Did they read the documentation for the functions that they are using? Write one line: check it: does it do what you need it to do. Understand what it does. Don't guess.
Read this:
Categorie
Scopri di più su Physics in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!