Skip to content

Instantly share code, notes, and snippets.

@pixyj
Last active April 19, 2017 14:28
Show Gist options
  • Save pixyj/6560613 to your computer and use it in GitHub Desktop.
Save pixyj/6560613 to your computer and use it in GitHub Desktop.
Solution to http://tour.golang.org/#24. Find the square root a number using Newton Raphson method
package main
import (
"fmt"
)
func approx(z, x float64) float64 {
z = z - (z*z - x)/2/z
return z
}
func mod(x float64) float64 {
if x < 0.0 {
x = -x
}
return x
}
func goodEnough(before, after float64) bool {
change := (after - before)/before
return mod(change) < 0.000000001
}
func Sqrt(x float64) float64 {
before := 1.0
after := 1.0
iterations := 0
for {
iterations += 1
after = approx(before, x)
fmt.Println("Iterations: ", iterations)
if goodEnough(after, before) {
break
}
before = after
}
return after
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(1e6))
fmt.Println(Sqrt(1/1e6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment