Created
April 26, 2014 09:29
-
-
Save jsmits/11315681 to your computer and use it in GitHub Desktop.
Tour of Golang #25
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 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