Skip to content

Instantly share code, notes, and snippets.

@spcbfr
Created February 24, 2024 20:16
Show Gist options
  • Save spcbfr/62a78790735f09efa019dc7b5aaa1b2b to your computer and use it in GitHub Desktop.
Save spcbfr/62a78790735f09efa019dc7b5aaa1b2b to your computer and use it in GitHub Desktop.
Square root approximation algorithm in Go
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