Exercise: Loops and Functions
Let’s put loops and functions to work: implement a square root function without using math.Sqrt. Given a number x, find z such that z² is as close to x as possible.
The trick is Newton’s method. Start with a guess for z, then refine it with:
z -= (z*z - x) / (2*z)
Each iteration, the guess gets closer. A starting value of z = 1 works fine for any input.
Give it a shot:
- Implement
Sqrtin the provided function. Run the loop 10 times and printzon each step. - Watch how fast it converges for
x = 2,x = 3, etc. - Then change the loop to stop when
zbarely changes between iterations — you’ll likely need fewer than 10 steps.
To initialize a float, use either:
z := 1.0
z := float64(1)
Compare your final result to math.Sqrt — they should match closely.
For the curious: z² − x measures how far off your guess is, and dividing by 2z (the derivative of z²) scales the correction. This is Newton’s method — it converges remarkably fast for square roots.