Skip to content

Instantly share code, notes, and snippets.

@andresvia
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andresvia/64feef8f4277c419e6db to your computer and use it in GitHub Desktop.
Save andresvia/64feef8f4277c419e6db to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (z float64) {
s := 1.0
min_change := 0.01
z = 1
for i := 0 ; true ; i++ {
s = z - (z*z-x)/2*z
change := math.Abs(z - s)
fmt.Println(i, "->", z)
z = s
if change < min_change {
break
}
}
return
}
func main() {
newton := Sqrt(2)
mathlib := math.Sqrt(2)
fmt.Println("newton", newton)
fmt.Println("mathlib", mathlib)
fmt.Println("diff", math.Abs(mathlib-newton))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment