没有不值得去解决的问题,也没有不值得去学习的技术!

Three Ways to Implement Sqrt() in Go: Fixed Iteration, Error Control, and the Standard Library

While working through the official Go tutorial A Tour of Go, I encountered a classic exercise: Implement a square root function Sqrt(x)

1. While working through the official Go tutorial A Tour of Go, I encountered a classic exercise:
Implement a square root function Sqrt(x). As shown in Figure 1.

While working through the official Go tutorial A Tour of Go, I encountered a classic exercise: Implement a square root function Sqrt(x)

This exercise covers not only loops and functions in Go, but also introduces a very important numerical computation method:
Newton’s method.

This article will demonstrate, through three progressively optimized examples, how to start from a simple version
and gradually implement a more accurate and robust square root function:

  1. Fixed 10 iterations
  2. Stopping using error control
  3. Comparing results with the standard library math.Sqrt

All code is organized in the following directory structure:

go-tour/
├── sqrt-iterations/
├── sqrt-epsilon/
├── sqrt-iteration-count/

2. ## Introduction to Newton’s Method

The goal of a square root function is:

Given a number x, find a number z such that:

z² ≈ x

Newton’s method continuously adjusts z to gradually approach the true value.

The update formula for each step is as follows:

z = z – (zz – x) / (2z)

Where:

  • z*z – x represents the current error
  • 2*z represents the derivative of the function z²
  • Each update brings the result closer to the true value

This method converges very quickly,
typically requiring only a few iterations to achieve high precision.

3. Example 1: Fixed 10 iterations, corresponding to sqrt-iterations/main.go

Go
package main

import (
	"fmt"
)

func Sqrt(x float64) float64 {
	z := 1.0 // 初始猜测值
	for i := 0; i < 10; i++ {
		z -= (z*z - x) / (2 * z)
		fmt.Println("iteration", i, "z =", z)
	}

	return z
}

func main() {
	fmt.Println("result:", Sqrt(2))
}

4. Example output

It can be observed that:

After each iteration, the value of z quickly approaches √2.

Usually, after the 4th to 5th iteration,
the result is already very close to the true value.

Go
package main

import (
	"fmt"
)

func Sqrt(x float64) float64 {
	z := 1.0 // 初始猜测值
	for i := 0; i < 10; i++ {
		z -= (z*z - x) / (2 * z)
		fmt.Println("iteration", i, "z =", z)
	}

	return z
}

func main() {
	fmt.Println("result:", Sqrt(2))
}

5. Example 2: Using epsilon to control convergence + comparing with math.Sqrt, corresponding to: sqrt-epsilon/main.go

Go
package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0              // 初始猜测值
	const epsilon = 1e-10 // 精度控制

	for {
		prev := z
		z -= (z*z - x) / (2 * z)

		// 判断变化是否足够小
		if math.Abs(z-prev) < epsilon {
			break
		}
	}

	return z
}

func main() {
	fmt.Println("My sqrt:", Sqrt(2))
	fmt.Println("Math sqrt:", math.Sqrt(2))
}

6. Example output

Why is this better?

This approach:

Automatically determines convergence
Avoids meaningless computations
Improves program efficiency

To verify whether our implementation is correct,
we can compare the result with math.Sqrt from the Go standard library.
As we can see, the two are almost completely identical (exactly equal).

Plaintext

/app/go-tour/sqrt-epsilon # go run main.go
My sqrt: 1.4142135623730951
Math sqrt: 1.4142135623730951

7. Example 3: Counting iterations (observing convergence efficiency), corresponding to: sqrt-iteration-count/main.go

Go
package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0              // 初始猜测值
	const epsilon = 1e-10 // 精度控制

	count := 0

	for {
		prev := z
		z -= (z*z - x) / (2 * z)

		count++

		// 判断变化是否足够小
		if math.Abs(z-prev) < epsilon {
			break
		}
	}

	fmt.Println("iterations:", count)

	return z
}

func main() {
	fmt.Println("result:", Sqrt(2))
}

8. Example output

Features:

Counts count
Outputs iterations

Usage:

Observe algorithm efficiency.

Typically:

iterations: 5

It only takes 5 iterations to get a high-precision result.

Plaintext

/app/go-tour/sqrt-iteration-count # go run main.go
iterations: 5
result: 1.4142135623730951

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系