Why is this Square Root approximation not working?

  • A+
Category:Languages

This Program basically finds an approximation to the square root of a given number. I can't see the problem why its not working. The program is compiling but never running. It'd computing something indefinitely.

    public static void Main(string[] args)     {         Console.WriteLine("Enter number to find Square Root");         var num = Convert.ToInt32(Console.ReadLine());          var ans = SqaureRoot(num);         Console.WriteLine("Square root of {0} : {1}",num,ans);      } 

The problem must obviously be in this method, in my opinion, the code is not exiting from the while true loop, and i just can't see why. This problem has to be tackled using the Newton Raphson method only to approximate the square root. Could it be maybe since the newton raphson equation doesn't have brackets?

    public static double SqaureRoot(double a)     {         if (a < 0)             throw new Exception("Can not sqrt a negative number");         double error = 0.00001;         double x = 1;         while (true)         {             double val = x * x;             if (Math.Abs(a) <= error)                 return x;             x = x / 2 + a / (2 * x);         }      } 


I can't see the problem why its not working. ... the code is not exiting from the while true loop, and i just can't see why.

It's true, you can't see it. All the time I'm looking in the refrigerator at the milk and I can't see the milk. You have Refrigerator Blindness but for coding. You are looking directly at an obvious defect and you cannot see it.

This problem is very, very common amongst both beginners and experienced programmers.

The program you are analyzing in your head is the one that works, but that program only exists in your head. You have to analyze the program that you actually wrote and is actually running!

There are many techniques that experienced developers use every day to break out of code blindness and find the defect.

The technique you're using is ask people with fresh eyes to look at the problem. This technique works; I just had to glance at your code to see the obvious problem because I'm reading the code that you wrote, and you're reading the code that doesn't exist that you thought you wrote.

But that's a bad technique because it wastes other people's time on trivial problems that you could learn to solve yourself. Today would be a great day to learn how to solve those problems yourself.

The first technique is to learn how to use a debugger.

What you want to do is step through the code in the debugger, one statement at a time, and on every statement make a prediction about what that statement will do. You have to make the prediction before you step the statement. Then step the statement and see if your prediction came true. Eventually you'll make a prediction that is false, and that's the point where your understanding of your program is wrong.

The next technique is called rubber duck debugging. Get a rubber duck or a grad student or some other object you can talk to, and out loud explain every line of your program -- preferably while debugging -- and give an excessively detailed explanation of why that line is correct. When you get to a line you cannot justify, either you don't understand your own program, or the line is wrong. You will feel like an idiot talking out loud to a rubber duck, but part of what makes it work is engaging the part of your brain responsible for speaking.

In particular, explain the purpose and usage of every variable very carefully. In your case that alone would quickly find the problem, as you have a variable which is declared and written but never read. A variable which is written but never read from is a huge red flag; it means that you've either got a useless part in your machine, or, more likely, you've got a crucial part that is not being used by mistake. As is the case here.

In your particular case there are some special techniques.

  • Your intuition gave you two big hints: the problem is an infinite loop, and "Could it be maybe since the newton raphson equation doesn't have brackets?" The first intuition was spot on. The second intuition makes zero sense to me and I have no idea what you're talking about. But regardless, run down those hunches.

  • You have correctly diagnosed your problem as an infinite loop, so focus your attention while debugging particularly on the loop condition. Does it make sense? (Hint: No.) Again, read it out loud. It helps.

  • You are writing a code version of a standard algorithm. Go back to your description of the algorithm, and verify that every step in the algorithm is found somewhere in your code. There's an operation in the original algorithm that is not in your program, and that's where the bug is.

  • Rename your variables so that their names more clearly represent their concepts. error is wrong; that's not the error. That's the errorTolerance. x should be approximation. The error is computed by currentError = approximation * approximation - a; If you look at your program and ask yourself "where is errorTolerance compared to currentError? you'd easily find your bug. And if you do that, you'll write fewer silly bugs.

Any of these techniques would find your bug quickly. Learn all of them today.

Further reading: https://ericlippert.com/2014/03/05/how-to-debug-small-programs

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: