Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Created July 12, 2013 16:16
Show Gist options
  • Save MattSurabian/5985674 to your computer and use it in GitHub Desktop.
Save MattSurabian/5985674 to your computer and use it in GitHub Desktop.
My implementation of the Newtonian Square Root Approximation in Go. Part of the Go tour: http://tour.golang.org/#23
package main
import (
"fmt"
"math"
)
const(
ACCURACY_DELTA = 0.00000000000001 // Experiment with this value to see accuracy impact!
)
func Sqrt(x float64) float64{
ourGuess := float64(1) // any initial guess will do!
for newtonGuess := newtonIteration(x, ourGuess); math.Abs(newtonGuess-ourGuess) > ACCURACY_DELTA
{
ourGuess = newtonGuess;
newtonGuess = newtonIteration(x, ourGuess)
}
return ourGuess
}
func newtonIteration(x, z float64) float64{
return z-(math.Pow(z,2)-x)/(2*z)
}
func main() {
numToSqrt := float64(125030)
fmt.Println("Newtonian Method:",Sqrt(numToSqrt))
fmt.Println("Control Group:", math.Sqrt(numToSqrt))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment