Skip to content

Instantly share code, notes, and snippets.

@jsmits
Created April 26, 2014 09:29
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 jsmits/11315681 to your computer and use it in GitHub Desktop.
Save jsmits/11315681 to your computer and use it in GitHub Desktop.
Tour of Golang #25
package main
import (
"fmt"
"math"
)
func newtonSqrtFormula(z float64, x float64) float64 {
return (z - (((z * z) - x) / (2 * z)))
}
func Sqrt(x float64) float64 {
var z float64 = 1
var i int = 1
var prev_z float64 = -1
for ; ; i++ {
z = newtonSqrtFormula(z, x)
if math.Abs(z - prev_z) < 0.000000000000001 {
break
}
prev_z = z
}
fmt.Println("Iterations:", i)
return z
}
func main() {
var x int = 7
fmt.Println(math.Sqrt(float64(x)))
fmt.Println(Sqrt(float64(x)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment