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

3 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2016-2-25
You have to define n before you use it.
  3 个评论
Stephen23
Stephen23 2016-2-25
编辑:Stephen23 2016-2-25
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by