Skip to content

Instantly share code, notes, and snippets.

@avkosme
Forked from tetsuok/answer_exercise_gotour.go
Created January 5, 2020 03:13
Show Gist options
  • Save avkosme/1ab0eafb18fd7bbf5aec334b5fec4a78 to your computer and use it in GitHub Desktop.
Save avkosme/1ab0eafb18fd7bbf5aec334b5fec4a78 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment