Skip to content

Instantly share code, notes, and snippets.

@Babatunde13
Last active June 24, 2024 16:14
Show Gist options
  • Save Babatunde13/cd6b48d3669ac7e60a331d3c92c9ff32 to your computer and use it in GitHub Desktop.
Save Babatunde13/cd6b48d3669ac7e60a331d3c92c9ff32 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
guess := 1.0
var lastGuess float64
var lastTwoGuess float64
const MaxIterCount = 10
for i := 0; i < MaxIterCount; i++ {
fmt.Printf("Iteration %d: z = %v\n", i, guess)
lastTwoGuess = lastGuess
lastGuess = guess
guess -= (guess * guess - x)/(2 * guess)
if guess == lastGuess && lastGuess == lastTwoGuess {
// we are already at the square root
fmt.Println("definitive sqrt found")
break
}
}
return guess
}
func main() {
fmt.Println(Sqrt(5))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment