Skip to content

Instantly share code, notes, and snippets.

@ivanacostarubio
Created September 22, 2012 02:23
Show Gist options
  • Select an option

  • Save ivanacostarubio/3764890 to your computer and use it in GitHub Desktop.

Select an option

Save ivanacostarubio/3764890 to your computer and use it in GitHub Desktop.
Newton's Square Root Approximation
def abs(x)
(x < 0) ? -x : x
end
def sqrtIter(guess, x)
isGoodEnough(guess,x) ? guess : sqrtIter( improve(guess,x) ,x)
end
def isGoodEnough(guess,x)
abs(guess * guess - x) < 0.001
end
def improve(guess,x)
(guess + x / guess) / 2
end
def sqrt(x)
sqrtIter(1.0,x)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment