Created
February 24, 2024 20:16
-
-
Save spcbfr/62a78790735f09efa019dc7b5aaa1b2b to your computer and use it in GitHub Desktop.
Square root approximation algorithm in Go
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 Sqrt(x float64) (float64, int) { | |
z := x/2 | |
prev := 0.0 | |
i := 0 | |
for math.Abs(z-prev) > math.Pow(10, -5) { | |
i++ | |
prev = z | |
z -= (z*z - x) / (2*z); | |
} | |
return z,i | |
} | |
func main() { | |
result, nOfIterations := Sqrt(56) | |
fmt.Printf("the result is %f and that was done in %d iterations\n", result, nOfIterations) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment