Created
February 17, 2017 22:19
-
-
Save drguildo/52d570a4df1c3a509c96a917d7ecd609 to your computer and use it in GitHub Desktop.
A Go implementation of Newton's method for finding the square root of a number.
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" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
return SqrtNewton(x, x) | |
} | |
func SqrtNewton(x float64, z float64) float64 { | |
nextz := z - (z*z-x)/(2*z) | |
if math.Abs(z-nextz) < 0.001 { | |
return nextz | |
} | |
return SqrtNewton(x, nextz) | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment