Skip to content

Instantly share code, notes, and snippets.

@hodlbirb
Last active January 31, 2017 22:24
Show Gist options
  • Save hodlbirb/a391079d9b2fab7d0b8bd6b76c994565 to your computer and use it in GitHub Desktop.
Save hodlbirb/a391079d9b2fab7d0b8bd6b76c994565 to your computer and use it in GitHub Desktop.
Hand-coded sqrt func with tail recursion
package main
import (
"fmt"
"math"
"math/big"
)
func Sqrt(x float64) float64 {
if x == 0 {
return x
}
return auxSqrt(x, 1, 1.0)
}
func auxSqrt(x float64, i int, z float64) float64 {
if i == 10 {
return z
}
return auxSqrt(x, i + 1, z - (math.Pow(z, 2) - x) / (2 * z))
}
func main() {
i := 1.0
for tranc8(Sqrt(i)) == tranc8(math.Sqrt(i)) {i++}
fmt.Println(i)
}
func tranc8(x float64) string {
return big.NewFloat(x).Text('f', 8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment