Created
June 30, 2015 20:14
-
-
Save danilogr/2ded2b6d4c7d87ab9824 to your computer and use it in GitHub Desktop.
A Tour of Go: Square root using Netwon'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
// https://tour.golang.org/flowcontrol/8 | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) (z float64) { | |
const delta float64 = 1e-10 | |
z = x | |
var z_old float64 | |
for math.Abs(z_old-z) > delta { | |
z_old = z | |
z = z - (z*z-x)/(2*z) | |
} | |
return | |
} | |
func main() { | |
fmt.Println(Sqrt(2), math.Sqrt(2)) | |
fmt.Println(Sqrt(2) - math.Sqrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment