Created
August 2, 2014 20:17
-
-
Save MattJermyWright/3832ba383075a786a543 to your computer and use it in GitHub Desktop.
Go Patterns: Common patterns for the Go language.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
const deltaCorrectionThreshold = .000000000000000005 | |
var NewtonSquareRootRecursive func(float64, float64) float64 | |
NewtonSquareRootRecursive = func(x, z0 float64) float64 { | |
z1 := 0.5 * (z0 + x / z0) | |
if math.Abs(z1-z0)< deltaCorrectionThreshold { | |
return z1 | |
} | |
return NewtonSquareRootRecursive(x, z1) | |
} | |
return NewtonSquareRootRecursive(x, 1.5) | |
} | |
func main() { | |
fmt.Println("Square-root (Newton's Method):",Sqrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment