Created
July 12, 2013 16:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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