Skip to content

Instantly share code, notes, and snippets.

@nZac
Last active August 29, 2015 13:56
Show Gist options
  • Save nZac/8891720 to your computer and use it in GitHub Desktop.
Save nZac/8891720 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) (float64, int) {
z := float64(x)
thres := .0000001
count := 0
var prev float64
for ;; count++{
// Do calculation
top := z*z - x
bot := 2 * z
div := top/bot
z = z - div
// First time behavior
if count == 0 { prev = z; continue }
// Calculate diff
diff := prev - z
// Check against the threshold
if diff < thres {
break
}
// Setup the next
prev = z
}
return z, count
}
func main() {
x := 200000.0
ret, loop := Sqrt(x)
fmt.Println("mine: ",ret, loop )
fmt.Println("yours:", math.Sqrt(x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment