Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created October 17, 2018 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/bdf51e61d50ad3e70b3bb2290797b5fe to your computer and use it in GitHub Desktop.
Save guitarrapc/bdf51e61d50ad3e70b3bb2290797b5fe to your computer and use it in GitHub Desktop.
Exercise: Loops and Functions, https://go-tour-jp.appspot.com/flowcontrol/8
package main
import (
"fmt"
"math"
)
// Newton-Raphson method
func Sqrt(x float64) (result float64, count int) {
z := 1.0
i := 0
var prev float64 = 1.0
init := false
for {
i++
prev = z
z -= (z * z - x ) / (2 * z)
//fmt.Println(z, prev, prev < z + 0.00000000001)
if z == prev || (init && prev < z + 0.00000000001) {
break
}
init = true
}
return z, i
}
func main() {
input := float64(67000000000)
result, count := Sqrt(input)
fmt.Println("try", result, ", count", count)
fmt.Println("math", math.Sqrt(input))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment