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

2 views (last 30 days)
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.
  1 Comment
Stephen23
Stephen23 on 25 Feb 2016
It is much easier for us to help you if you paste text rather then screenshots of links to other webpages. Simply paste it, and add formatting using the buttons above the textbox:

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 25 Feb 2016
You have to define n before you use it.
  3 Comments
Stephen23
Stephen23 on 25 Feb 2016
Edited: Stephen23 on 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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!