0 Replies - 1363 Views - Last Post: 24 November 2009 - 05:00 PM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Finding Square Root Using Newton-Rhapson Method

Posted 24 November 2009 - 05:00 PM

Description: A fast-converging algorithm for finding the square root of a number
def newtonSqrt(num, prec)
  guess = 10.0 #this is the initial guess to check, it's 10 for no particular reason
  ctr = 0 #this keeps the loop from infinitely running on some roots
  while(((guess**2) - num > prec) and ctr <= 1000)
    #uncomment this next line if you want to watch the guesses become more and more accurate
    #puts guess
    guess = guess - ((guess**2) - num) / (2*guess)
    ctr += 1
  end
  return guess
end

#Example usage
sqrt = newtonSqrt(16, 0.0000000001)

puts sqrt #=>4


Is This A Good Question/Topic? 0
  • +

Page 1 of 1