Skip to content

Instantly share code, notes, and snippets.

@peterc
Created December 10, 2011 03:07
Show Gist options
  • Save peterc/1454432 to your computer and use it in GitHub Desktop.
Save peterc/1454432 to your computer and use it in GitHub Desktop.
Square root calculation using Newton-Raphson
# Square root calculation using Newton-Raphson
# from Practical Programming (1968)
a = 256
x = (1 + a) / 2.0
loop do
ox = x
x = (x + a.to_f / x) / 2.0
break if x >= ox
end
puts "The square root of #{a} is #{x}"
@peterc
Copy link
Author

peterc commented Dec 12, 2011

I gave it a go. No significant performance gain, as far as I could tell. On the few runs I tried, it was a few percent.

All in the interests of science though since, of course, the iterative solution is quicker anyway ;-)

src = <<-RUBY
  def improve(guess, x)
    (guess + (x / guess.to_f)) / 2.0
  end

  def sqrt_iter(guess, x)
    return guess if good_enough?(guess, x)
    sqrt_iter improve(guess, x), x
  end

  def good_enough?(guess, x)
    (guess ** 2 - x).abs < 0.001
  end

  def sqrt(x)
    sqrt_iter(1.0, x)
  end

  y = nil
  500000.times { y = sqrt(2401) } 
  puts y
RUBY

RubyVM::InstructionSequence.compile_option = {
  :tailcall_optimization => false
}

puts "Tail call optimization is #{RubyVM::InstructionSequence.compile_option[:tailcall_optimization] ? "ON" : "OFF"}"
p RubyVM::InstructionSequence.compile(src, nil, nil, 1).eval

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