Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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