Skip to content

Instantly share code, notes, and snippets.

@tetsuok
Created April 2, 2012 01:58
Show Gist options
  • Save tetsuok/2279991 to your computer and use it in GitHub Desktop.
Save tetsuok/2279991 to your computer and use it in GitHub Desktop.
An answer of the exercise: Loops and Functions on a tour of Go
package main
import (
"fmt"
"math"
)
const Delta = 0.0001
func isConverged(d float64) bool {
if d < 0.0 {
d = -d
}
if d < Delta {
return true
}
return false
}
func Sqrt(x float64) float64 {
z := 1.0
tmp := 0.0
for {
tmp = z - (z * z - x) / 2 * z
if d := tmp - z; isConverged(d) {
return tmp
}
z = tmp
}
return z
}
func main() {
attempt := Sqrt(2)
expected := math.Sqrt(2)
fmt.Printf("attempt = %g (expected = %g) error = %g\n",
attempt, expected, attempt - expected)
}
@ArturSultanov
Copy link

ArturSultanov commented Sep 15, 2025

package main

import (
	"fmt";
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0
	for math.Abs(z*z-x) > 1e-8 {
		z -= (z*z - x) / (2*z)
	}
	return z
}

func main() {
	x := float64(2)
	fmt.Println(Sqrt(x))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment