Skip to content

Instantly share code, notes, and snippets.

@k0uki
Last active August 28, 2016 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0uki/fdfd77b06b9cfeb3983b2f00c6700ea3 to your computer and use it in GitHub Desktop.
Save k0uki/fdfd77b06b9cfeb3983b2f00c6700ea3 to your computer and use it in GitHub Desktop.
tour of goの例題
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