From a5ba7c63b1b96c3df89f07a80f6ec91300377b7a Mon Sep 17 00:00:00 2001 From: "Stephen M. McQuay" Date: Thu, 2 Aug 2012 14:39:21 -0600 Subject: [PATCH] solution to exercise 1 --- loopfuncs/go.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 loopfuncs/go.go diff --git a/loopfuncs/go.go b/loopfuncs/go.go new file mode 100644 index 0000000..4aa0bd2 --- /dev/null +++ b/loopfuncs/go.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "math" +) + +const min_threshold = 1e-200 + +func Sqrt(x float64, threshold float64) (z float64, iterations int) { + z = x + old_z := z + for { + z = z - (z*z-x)/(2*x) + if math.Abs(z-old_z) < threshold { + break + } + old_z = z + iterations++ + } + return +} + +func main() { + threshold := 1.0 + right_answer := math.Sqrt(2) + for threshold > min_threshold { + answer, iterations := Sqrt(2, threshold) + fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n", + threshold, right_answer-answer, right_answer, answer, + iterations) + threshold = threshold / 10.0 + } +}