Last active
August 28, 2016 08:20
-
-
Save k0uki/fdfd77b06b9cfeb3983b2f00c6700ea3 to your computer and use it in GitHub Desktop.
tour of goの例題
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 { | |
var z float64 = 1 | |
for i := 0; i < 10; i++ { | |
z = z - ((z*z - x) / (2 * z)) | |
} | |
return z | |
} | |
func Sqrt2(x float64) float64 { | |
var z float64 = 1 | |
var loop_count = 1 | |
var threshold = 0.000000000000001 | |
for { | |
result := z - ((z*z - x) / (2 * z)) | |
if math.Abs(z-result) < threshold { | |
break | |
} | |
z = result | |
loop_count++ | |
} | |
fmt.Println("loop_count is", loop_count) | |
return z | |
} | |
func MathSqrt(x float64) float64 { | |
return math.Sqrt(x) | |
} | |
func main() { | |
fmt.Println(Sqrt(15125432)) | |
fmt.Println(Sqrt2(15125432)) | |
fmt.Println(MathSqrt(15125432)) | |
/* | |
15110.695509529038 | |
loop_count is 18 | |
3889.1428361529743 | |
3889.1428361529743 | |
*/ | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment