#---------------------------------------------------------------------- # Lecture September 15, 2017 (C) Dr. William T. Verts #---------------------------------------------------------------------- def SQRT1(N): if (N < 0.0): # Check to make sure that you... N = -1.0 * N # ...aren't taking the square root of a negative. Guess = N / 2.0 # First approximation to the square root (really bad guess) Error = 1.0 # Make sure the while loop runs at least once while (Error > 1.0E-14): # Keep going if Guess^2 is too far from N New = N / Guess # Guess = (New + Guess) / 2.0 # Get a new (closer) approximation Error = N - (Guess * Guess) # Compute the error difference between Guess^2 and N if (Error < 0.0): # Make sure the error estimate... Error = -1.0 * Error # ...is positive print Guess # Print the current guess to show the process return Guess # Return the answer #---------------------------------------------------------------------- def SQRT2(N): if (N < 0.0): N = -N # An if followed by one statement can be combined # Use negation instead of multiply by -1.0 Guess = N / 2.0 Error = 1.0 while (Error > 1.0E-14): New = N / Guess Guess = (New + Guess) / 2.0 Error = N - (Guess * Guess) if (Error < 0.0): Error = -Error # An if followed by one statement can be combined print Guess return Guess #---------------------------------------------------------------------- def SQRT3(N): N = abs(N) # Use absolute value function Guess = N / 2.0 Error = 1.0 while (Error > 1.0E-14): New = N / Guess Guess = (New + Guess) / 2.0 Error = abs(N - (Guess * Guess)) # Use absolute value function # print Guess # Comment out the print (but leave it in for later debugging) return Guess #---------------------------------------------------------------------- # Where to from here? # 1: Picking a better initial guess # 2: Putting in a counter to stop, even if Error doesn't converge # 3: Use the built-in function math.sqrt