go-tour/exercise-loops-and-functions.go

22 lines
506 B
Go
Raw Permalink Normal View History

2020-02-05 03:44:36 +00:00
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
var p float64
2020-02-09 16:44:04 +00:00
for z := 1.0; z != p && math.Abs(z - p) > 0.000000000000001; z -= (z * z - x) / (2 * z) {
2020-02-05 03:44:36 +00:00
p = z
}
return p
}
func main() {
fmt.Printf("Stdlib: %g, Mine: %g\n", math.Sqrt(333), Sqrt(333))
fmt.Printf("Stdlib: %g, Mine: %g\n", math.Sqrt(33), Sqrt(33))
fmt.Printf("Stdlib: %g, Mine: %g\n", math.Sqrt(17), Sqrt(17))
fmt.Printf("Stdlib: %g, Mine: %g\n", math.Sqrt(4), Sqrt(4))
}