Trying to create a function to approx the sqrt of a number using this approximation

2 visualizzazioni (ultimi 30 giorni)
I have been trying to figure out this problem for a few hours and I cant seem to progress any further. I would greatly appreciate any help that could be provided in fixing my code.
My code wont post correctly so i will screenshot what i had.

Risposta accettata

Walter Roberson
Walter Roberson il 25 Feb 2016
You have to define n before you use it.
  3 Commenti
Stephen23
Stephen23 il 25 Feb 2016
Modificato: Stephen23 il 25 Feb 2016
Nope. Follow your code steps:
  1. define a
  2. define x
  3. define tol
  4. evaluate abs(n-x)<=tol
Nope, n has not been defined when you first try to use it. To fix this put n = x; before your loop. You also need to rethink your line
n = x;
at the end of the loop. The very next thing that happens is that these two variables get compared (in the while operation), yet you just defined them to be exactly the same, so this comparison will always be true. Your loop will never stop.
You also need to reconsider your while loop comparison:
while abs(n-x)<=tol
This does the exact opposite of what you want it to do: when n and x have very different values this comparison will be false and the loop will stop. You want it to stop when the difference is small.
Basically you need to rethink your code, and think about every step, and test your code as your write it. Most beginners think that writing lots of code means that they have done some work. But working code is better than lots of code. Test every line as a write it, and make sure that it does exactly what you need it to do.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by