Last active
August 29, 2015 14:17
-
-
Save ara-ta3/5c30a5da1cafe565b4d0 to your computer and use it in GitHub Desktop.
golang Sqrt
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 { | |
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