Skip to content

Instantly share code, notes, and snippets.

@tortillaj
Last active August 29, 2015 14:18
Show Gist options
  • Save tortillaj/80dfd6a7030bf50b4855 to your computer and use it in GitHub Desktop.
Save tortillaj/80dfd6a7030bf50b4855 to your computer and use it in GitHub Desktop.
Gotour Loops and Functions
package main
import (
"fmt"
"math"
)
func NewtonSqrt(x float64, z float64) float64 {
return z - ((math.Pow(z, 2.0) - x) / (2 * z))
}
func Sqrt(x float64, diff float64) float64 {
k := 1.0
guess := NewtonSqrt(x, k)
for {
next := NewtonSqrt(x, guess)
if math.Abs(next - guess) <= diff {
break
} else {
guess = next
}
}
return guess
}
func main() {
fmt.Println("Newton's Method:", Sqrt(9, 0.00001), "GO Method:", math.Sqrt(9))
fmt.Println("Newton's Method:", Sqrt(144, 0.00001), "GO Method:", math.Sqrt(144))
fmt.Println("Newton's Method:", Sqrt(12, 0.00001), "GO Method:", math.Sqrt(12))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment