Go Patterns: Common patterns for the Go language.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
const deltaCorrectionThreshold = .000000000000000005
var NewtonSquareRootRecursive func(float64, float64) float64
NewtonSquareRootRecursive = func(x, z0 float64) float64 {
z1 := 0.5 * (z0 + x / z0)
if math.Abs(z1-z0)< deltaCorrectionThreshold {
return z1
}
return NewtonSquareRootRecursive(x, z1)
}
return NewtonSquareRootRecursive(x, 1.5)
}
func main() {
fmt.Println("Square-root (Newton's Method):",Sqrt(2))
}