Created
September 22, 2013 04:14
-
-
Save gnrfan/6656628 to your computer and use it in GitHub Desktop.
Square root calculation in Go using Newton's iteration algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Average(x, y float64) float64 { | |
return (x + y) / 2.0 | |
} | |
func Improve(guess, x float64) float64 { | |
return Average(guess, x/guess) | |
} | |
func GoodEnough(guess, x float64) bool { | |
d := math.Abs(guess*guess - x) | |
return d < 0.0000000000001 | |
} | |
func Sqrt(x float64) (guess float64, iterations int) { | |
iterations = 0 | |
guess = 1.0 | |
for !GoodEnough(guess, x) { | |
guess = Improve(guess, x) | |
iterations += 1 | |
} | |
return guess, iterations | |
} | |
func main() { | |
//fmt.Println(Average(10, 5)) | |
//fmt.Println(Improve(1.0, 16)) | |
//fmt.Println(GoodEnough(3.5, 16)) | |
result, iterations := Sqrt(9) | |
fmt.Println(result, iterations) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment