Skip to content

Instantly share code, notes, and snippets.

@plasticbrain
Last active March 7, 2016 06:28
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 plasticbrain/ef4e1951449359e3b1bc to your computer and use it in GitHub Desktop.
Save plasticbrain/ef4e1951449359e3b1bc to your computer and use it in GitHub Desktop.
Go: Newton's method of approximating square roots
package main
import (
"fmt"
"math"
)
const DELTA = 0.00000001
func Sqrt(x float64) float64 {
guess := float64(1)
for {
guess = guess - (guess*guess - x)/(2*guess)
if math.Abs(x-guess*guess) <= DELTA {
break
}
}
return guess
}
// Alternative method
// I like this one better, and I feel like it's more effecient since it removes the superflous if statement.
func SqrtAlt(x float64) float64 {
guess, d := float64(1), float64(1)
for d > DELTA {
guess = guess - (guess*guess - x)/(2*guess)
d = math.Abs(x-guess*guess)
}
return guess
}
func main() {
fmt.Println(Sqrt(500))
fmt.Println(SqrtAlt(500))
fmt.Println(math.Sqrt(500))
}
/*
Output:
22.360679774997898
22.360679774997898
22.360679774997898
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment