Created
August 30, 2015 16:32
-
-
Save colelawrence/f33a6e9deb6128046dcf to your computer and use it in GitHub Desktop.
Newtons Sqrt
This file contains hidden or 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" | |
| ) | |
| 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