Skip to content

Instantly share code, notes, and snippets.

@kh0p
Created May 4, 2014 16:14
Show Gist options
  • Save kh0p/be6dc9a197e8268a2cc5 to your computer and use it in GitHub Desktop.
Save kh0p/be6dc9a197e8268a2cc5 to your computer and use it in GitHub Desktop.
Exercise: Loops and Functions - http://tour.golang.org/#25
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
guess := x
for i := 0; i < 10; i++ {
guess -= (math.Pow(guess,2) - 2) / (2.0*guess)
}
return guess
}
func SqrtDiff(x, y float64) float64 {
diff := float64(math.Sqrt(x)) - y
if diff < 0 {
diff = -diff
}
return diff
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
fmt.Println(float64(math.Sqrt(2)) - Sqrt(2))
fmt.Println(SqrtDiff(2, Sqrt(2)))
}
@kh0p
Copy link
Author

kh0p commented May 4, 2014

Output:

1.414213562373095
1.4142135623730951
2.220446049250313e-16
2.220446049250313e-16

Program exited.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment