Skip to content

Instantly share code, notes, and snippets.

@scottdelly
Created July 14, 2017 19:08
Show Gist options
  • Save scottdelly/35889b9c3e5b1b9b4f2a2bed9dc0a35c to your computer and use it in GitHub Desktop.
Save scottdelly/35889b9c3e5b1b9b4f2a2bed9dc0a35c to your computer and use it in GitHub Desktop.
Efficient Implementation of Newtons Formula for Square Roots
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
digits := math.Floor( math.Log10( x ) ) + 1
guess := x/math.Pow(10,digits/2)
fmt.Println("Start Guess: ",guess)
y := 0.0
i := 0
for math.Abs(guess-y) > math.Pow(10,-3) {
i++
y = guess
guess = guess - (math.Pow(guess,2) - x) / (2.0*guess)
}
fmt.Println(i)
return guess
}
func main() {
x := 1252460.0
guess := Sqrt(x)
fmt.Println(guess)
real := math.Sqrt(x)
fmt.Println(real)
diff := real - guess
fmt.Println(diff)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment