Skip to content

Instantly share code, notes, and snippets.

@danilogr
Created June 30, 2015 20:14
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 danilogr/2ded2b6d4c7d87ab9824 to your computer and use it in GitHub Desktop.
Save danilogr/2ded2b6d4c7d87ab9824 to your computer and use it in GitHub Desktop.
A Tour of Go: Square root using Netwon's method
// https://tour.golang.org/flowcontrol/8
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (z float64) {
const delta float64 = 1e-10
z = x
var z_old float64
for math.Abs(z_old-z) > delta {
z_old = z
z = z - (z*z-x)/(2*z)
}
return
}
func main() {
fmt.Println(Sqrt(2), math.Sqrt(2))
fmt.Println(Sqrt(2) - math.Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment