From 5edefe38d2dc632f61ba31a1c001f9c90fefb58b Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 25 Aug 2012 21:48:12 -0400 Subject: [PATCH] A crappy implementation of Newton's method for finding square root --- gotime/src/exercise-sqrt.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 gotime/src/exercise-sqrt.go diff --git a/gotime/src/exercise-sqrt.go b/gotime/src/exercise-sqrt.go new file mode 100644 index 0000000..806c350 --- /dev/null +++ b/gotime/src/exercise-sqrt.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "math" +) + +// using Newton's method +func Sqrt(x float64) float64 { + z := x - (x * 0.1) + for i := 0 ; i < 1000 ; i++ { + newZ := z - (((z * z) - x) / 2 * z) + diff := math.Abs(newZ) - math.Abs(z) + if math.Abs(diff) < 0.01 { + return newZ + } + z = newZ + } + return z +} + +func main() { + fmt.Printf("stdlib -> %f\n", math.Sqrt(2)) + fmt.Printf("newton -> %f\n", Sqrt(2)) +}