Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Last active August 29, 2015 14:17
Show Gist options
  • Save ara-ta3/5c30a5da1cafe565b4d0 to your computer and use it in GitHub Desktop.
Save ara-ta3/5c30a5da1cafe565b4d0 to your computer and use it in GitHub Desktop.
golang Sqrt
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := float64(1)
const count = 10
for i := 0; i < count ; i++ {
z = z - (math.Pow(z,2) - x) / (2 * z)
}
return z
}
func Sqrt2(x float64) float64 {
z := float64(1)
y := sqrtiter(x,z)
const diff = 0.000000000000001
for math.Abs(z-y) > diff {
z = y
y = sqrtiter(x,z)
}
return y
}
func sqrtiter(x,z float64) float64 {
z = z - (math.Pow(z,2) - x) / (2 * z)
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt2(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment