Created
March 15, 2012 09:40
-
-
Save janlay/2043291 to your computer and use it in GitHub Desktop.
Tour of Go #43: implement the square root function using Newton's method.
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 { | |
z := 1.0 | |
for i := 1; i <= 100; i++ { | |
if value := z - (z * z - x) / (2 * z); math.Abs(value - z) < 0.0000001 { | |
return value | |
} else { | |
z = value | |
} | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(10)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment