astaxie / build-web-application-with-golang

A golang ebook intro how to build a web with golang

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sqrt Algorithm in Chapter 1.2

be1be1 opened this issue · comments

In Chapter 1.2 $GOPATH and workspace, there is an algorithm describing a squre root math method writing in Golang.

// Source code of $GOPATH/src/mymath/sqrt.go
package mymath

func Sqrt(x float64) float64 {
	z := 0.0
	for i := 0; i < 1000; i++ {
		z -= (z*z - x) / (2 * x)
	}
	return z
}

In my point of view, this function intends to use newton method to get the approximate value of a squre root. However, if this is indeed using newton method, the method should be changed to:

// Source code of $GOPATH/src/mymath/sqrt.go
package mymath

func Sqrt(x float64) float64 {
	z := 100.0
	for i := 0; i < 1000; i++ {
		z -= (z*z - x) / (2 * z)
	}
	return z
}

Correct me if I am wrong. For reference: https://gist.github.com/abesto/3476594