Skip to content

Instantly share code, notes, and snippets.

@ciaranarcher
Created January 31, 2014 20:46
Show Gist options
  • Save ciaranarcher/8742792 to your computer and use it in GitHub Desktop.
Save ciaranarcher/8742792 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (z float64) {
z = 1.0
for i := 0; i < 100000000; i++ {
prev:= z
z = z - ((z * z - x) / 2 * z)
if diff := math.Abs(prev - z); diff < 0.0001 {
fmt.Println("good enough!", i, diff)
break;
}
}
return
}
func main() {
fmt.Println("per Newton:", Sqrt(2))
fmt.Println("per math lib:", math.Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment