Skip to content

Instantly share code, notes, and snippets.

@faizanakram99
Created January 1, 2025 15:58
Show Gist options
  • Save faizanakram99/dd3618fb08f94ee6b315aeae44a9dcb3 to your computer and use it in GitHub Desktop.
Save faizanakram99/dd3618fb08f94ee6b315aeae44a9dcb3 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
guess := 1.0
previousGuess := 1.0
maxVariance := 1e-8
fmt.Println("Finding square root of ", x)
for i := 1; i <= 10; i++ {
previousGuess = guess
guess -= (guess*guess - x) / (2 * guess)
fmt.Println("iteration ", i, " result:", guess)
if math.Abs(guess-previousGuess) < maxVariance {
fmt.Println("Square root found at iteration ", i)
return guess
}
}
return guess
}
func main() {
for i := 1; i <= 10; i++ {
fmt.Println("Square root of ", i, ": ", Sqrt(float64(i)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment