Skip to content

Instantly share code, notes, and snippets.

@gnrfan
Created September 22, 2013 04:14
Show Gist options
  • Save gnrfan/6656628 to your computer and use it in GitHub Desktop.
Save gnrfan/6656628 to your computer and use it in GitHub Desktop.
Square root calculation in Go using Newton's iteration algorithm.
package main
import (
"fmt"
"math"
)
func Average(x, y float64) float64 {
return (x + y) / 2.0
}
func Improve(guess, x float64) float64 {
return Average(guess, x/guess)
}
func GoodEnough(guess, x float64) bool {
d := math.Abs(guess*guess - x)
return d < 0.0000000000001
}
func Sqrt(x float64) (guess float64, iterations int) {
iterations = 0
guess = 1.0
for !GoodEnough(guess, x) {
guess = Improve(guess, x)
iterations += 1
}
return guess, iterations
}
func main() {
//fmt.Println(Average(10, 5))
//fmt.Println(Improve(1.0, 16))
//fmt.Println(GoodEnough(3.5, 16))
result, iterations := Sqrt(9)
fmt.Println(result, iterations)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment