Last active
December 28, 2015 06:56
-
-
Save ryanmr/967a7cf8af45289a7242 to your computer and use it in GitHub Desktop.
This file contains 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, int) { | |
z, l, d := 1.0, 1.0, 1.0 | |
i := 0 | |
threshold := math.Pow(10, -15) | |
for d > threshold { | |
i++ | |
l = z | |
z = z - (math.Pow(z, 2)-x)/(2*z) | |
d = math.Abs(l-z) | |
} | |
return z, i | |
} | |
func Test() { | |
numbers := []int{1,2,3,4,5,10,55,100,1000, 1024} | |
for i := 0; i < len(numbers); i++ { | |
var n = float64(numbers[i]) | |
var experimental, e_i = Sqrt(n) | |
var builtin = math.Sqrt(n) | |
var diff = builtin - experimental | |
fmt.Println(experimental, builtin, diff, e_i) | |
} | |
} | |
func main() { | |
Test() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment