Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created August 30, 2015 16:32
Show Gist options
  • Select an option

  • Save colelawrence/f33a6e9deb6128046dcf to your computer and use it in GitHub Desktop.

Select an option

Save colelawrence/f33a6e9deb6128046dcf to your computer and use it in GitHub Desktop.
Newtons Sqrt
package main
import (
"fmt"
)
func abs(x float64) float64 {
if x > 0 {
return x
} else {
return -x
}
}
func newtonsSqrt(x, z float64) float64 {
ans := z - ((z * z - x) / (2 * z))
delta := abs(ans - z)
if delta < .000001 {
return ans
} else {
return newtonsSqrt(x, ans)
}
}
func Sqrt(x float64) float64 {
return newtonsSqrt(x, x / 2)
}
func main() {
fmt.Println(Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment