Created
August 13, 2015 08:18
-
-
Save adkdev/b29f0b7bb5284538e544 to your computer and use it in GitHub Desktop.
Go Tour: Exercise: Loops and Functions (http://tour.golang.org/flowcontrol/8)
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 := 1.0 | |
// var a,b,c,d,e float64 | |
for i := 1; i <= 50; i++ { | |
tmp := z | |
// a = math.Pow(z,2) | |
// b = math.Pow(z,2) - x | |
// c = 2*z | |
// d = ((math.Pow(z,2) - x) / (2*z)) | |
// e = z - ((math.Pow(z,2) - x) / (2*z)) | |
// fmt.Println(a,b,c,d,e) | |
z = z - ((math.Pow(z,2) - x) / (2*z)) | |
fmt.Println(i,"-->",z) | |
delta := math.Abs(math.Abs(z) - math.Abs(tmp)) | |
if delta < 0.000001 { | |
break | |
} | |
} | |
return z | |
} | |
func guessSqrt(x float64) { | |
fmt.Println("Guess:", Sqrt(x), " Actual: ", math.Sqrt(x), "\n") | |
} | |
func main() { | |
guessSqrt(2) | |
guessSqrt(9) | |
guessSqrt(612) | |
guessSqrt(90000000000) | |
guessSqrt(160000000000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment