Skip to content

Instantly share code, notes, and snippets.

@Ovid
Last active December 21, 2016 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ovid/897965be87038f71a1c48fe0cd086fad to your computer and use it in GitHub Desktop.
Save Ovid/897965be87038f71a1c48fe0cd086fad to your computer and use it in GitHub Desktop.
Newton's methods for calculating the square root in golang
package main
// newton's method for calculating square roots
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
if x == 0 {
return 0
}
z := float64(1)
var prev float64
for math.Abs(z-prev) > .000000001 {
prev = z
z = z - (z*z-x)/(2*z)
}
return z
}
func main() {
for i := float64(0); i <= 9; i++ {
fmt.Println("sqrt of", i, "is", Sqrt(i), "versus", math.Sqrt(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment