Created
October 17, 2018 14:08
-
-
Save guitarrapc/bdf51e61d50ad3e70b3bb2290797b5fe to your computer and use it in GitHub Desktop.
Exercise: Loops and Functions, https://go-tour-jp.appspot.com/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" | |
) | |
// Newton-Raphson method | |
func Sqrt(x float64) (result float64, count int) { | |
z := 1.0 | |
i := 0 | |
var prev float64 = 1.0 | |
init := false | |
for { | |
i++ | |
prev = z | |
z -= (z * z - x ) / (2 * z) | |
//fmt.Println(z, prev, prev < z + 0.00000000001) | |
if z == prev || (init && prev < z + 0.00000000001) { | |
break | |
} | |
init = true | |
} | |
return z, i | |
} | |
func main() { | |
input := float64(67000000000) | |
result, count := Sqrt(input) | |
fmt.Println("try", result, ", count", count) | |
fmt.Println("math", math.Sqrt(input)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment