module Numeric::IntRoots

Public Instance Methods

iroot(n)
Alias for: irootn
iroot2() click to toggle source
# File lib/roots.rb, line 210
def iroot2       # Newton's method version used in Ruby for Integer#sqrt
  return nil if (n = self) < 0
  return n if n < 2
  b = n.bit_length
  x = 1 << (b-1)/2 | n >> (b/2 + 1)    # optimum initial root estimat
  while (t = n / x) < x; x = ((x + t) >> 1) end
  x
end
irootn(n) click to toggle source
# File lib/roots.rb, line 196
def irootn(n)   # Newton's method for nth root
  return nil if self < 0 && n.even?
  raise "root n is < 2 or not an Integer" unless n.is_a?(Integer) && n > 1
  return self if self == 0 || (self == -1 && n.odd?)
  num = self.abs
  e, x = n-1, 1 << (num.bit_length-1)/n + 1
  while (t = (e * x + num / x ** e)/n) < x
    x = t
  end
  x *= self < 0 ? -1 : 1
end
Also aliased as: iroot