Skip to content

Instantly share code, notes, and snippets.

@blakesmith
Created July 4, 2012 19:55
Show Gist options
  • Save blakesmith/3049248 to your computer and use it in GitHub Desktop.
Save blakesmith/3049248 to your computer and use it in GitHub Desktop.
Go Tour: Exercise: Loops and Functions - My solution
package main
import (
"fmt"
"math"
)
func newtAppx(x float64, appx float64) float64 {
return appx - ((math.Pow(appx, 2.0) - x) / (2 * appx))
}
func Sqrt(x float64) float64 {
guess := 1.0
appx := newtAppx(x, guess)
for {
nextAppx := newtAppx(x, appx)
delta := math.Abs(math.Abs(nextAppx) - math.Abs(appx))
if delta <= 0.0001 {
break
} else {
appx = nextAppx
}
}
return appx
}
func guessSqrt(x float64) {
fmt.Println("Guess:", Sqrt(x), " Actual: ", math.Sqrt(x))
}
func main() {
guessSqrt(2)
guessSqrt(54)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment