Skip to content

Instantly share code, notes, and snippets.

@jsanders
Created March 30, 2012 03:47
Show Gist options
  • Save jsanders/2246320 to your computer and use it in GitHub Desktop.
Save jsanders/2246320 to your computer and use it in GitHub Desktop.
Newton's method go vs. ruby comparison
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
@lmarlow
Copy link

lmarlow commented Mar 30, 2012

oooo.... speedy.

Weird that you use a for loop to represent a while in go.

@atimin
Copy link

atimin commented Mar 30, 2012

Hmm.. why does variable Z in 29 line equal 1.3 when in Go example it equal 1.0? I suppose that count of iteration is different for both example

@jsanders
Copy link
Author

jsanders commented Apr 2, 2012

@FLIPBack: Shoot, good point, it's completely arbitrary but it probably changes things at least somewhat.

@jsanders
Copy link
Author

jsanders commented Apr 2, 2012

Edits: formatting, remove newton func from Go example, change starting guess in ruby to 1.0, update times. Removing the function call from the Go example chopped off about a third of its run time, but it seems like that sort of thing should be able to be optimized away by the compiler - I'll have to play with the flags.

@atimin
Copy link

atimin commented Apr 2, 2012

Looks good. Now we know that Go in 100-50 times faster Ruby. Sorry, but I not see a many meaning in compare so different languages. But comparison Go with C\C++ is another pair of shoes =)

@jsanders
Copy link
Author

jsanders commented Apr 2, 2012

@FLIPBack - Ha yes, it is indeed a very silly comparison! Purely for my own curiosity. The more interesting comparison is how much the syntax matches up between the two. But for such a simple little program, most languages would look pretty similar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment