This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: Applied problem solving

Square root estimator (Step 3)

face Josiah Wang

Step 3: Implement your algorithm!

Now that you hopefully have your algorithm and steps clearly defined in your head, it is time to implement your program in Python!

Here is a reminder of the task: write a square root estimator program that reads in a floating point number n from the user, and prints out an estimate of the square root of n.

You can assume that the user will always enter a number n \ge 0. Of course, you are welcome to write code to check that n is valid if you like (for example no negative numbers)!

Also remember to test that your program is giving the correct output. The easiest way is to use a calculator to manually compare your answer. You can also perform automated testing - by writing a program test your code. You may use math.sqrt here just to check that your code is producing the correct output. Here is an example tester code. We will talk about better ways to automatically test your program’s correctness in the future!

import math

n = float(input("Please enter a number: "))

# Your code...
# ... computes the square root ...
# and stores it in a variable called "estimate" 

gold_reference = math.sqrt(n)
if abs(estimate - gold_reference) < 0.00001:
    print("Correct answer.")
else:
    print(f"Incorrect. Program output is {estimate}, but I am expecting {gold_reference}.")

Sample run #1

Please enter a positive number: 9
2.999984000065427

Sample run #2

Please enter a positive number: 96
9.797953999418729

Sample run #3

Please enter a positive number: 45.6
6.752770000589984