package main
import("fmt"; "math")
func Sqrt(x float64) (z float64) {
z, delta := 1.0, 1.0
for delta > 1e-4 {
z0 := z
z = z0 - ((z0*z0 - x) / 2*z0)
delta = math.Abs(z - z0)
}
return
}
func main() {
fmt.Println(Sqrt(2))
}
def sqrt x
z = 1.0
delta = 1
while delta > 0.0001
z0 = z
z = z0 - ((z0*z0 - x) / 2*z0)
delta = (z - z0).abs
end
z
end
puts sqrt 2
# Go
./tour 0.46s user 0.00s system 99% cpu 0.468 total
# Ruby 1.8.7
ruby newton.rb 54.44s user 0.07s system 99% cpu 54.672 total
# Ruby 1.9.3
ruby newton.rb 26.24s user 0.08s system 98% cpu 26.761 total
oooo.... speedy.
Weird that you use a for loop to represent a while in go.