0

I'm trying to calculate the square root of a really big number in Ruby. The problem I have is that the Math.sqrt function looks like this

sqrt(numeric) → float

If I feed it a really big number, it will give me FloatDomainError: Infinity.

What is the best way to get sqrt() to return a BigNum? Is there perhaps a gem for this or will I have to write my own function to calculate the square root?

In that case, what is the easiest way to go about doing this? Taylor series? The square roots of the numbers will always be integers.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
davorb
  • 613
  • 1
  • 9
  • 17
  • Wow, larger than `Float::MAX #=> 1.79769313486232e+308`? How are you getting to something that large? Are there any intermediate points where you might be able to take roots? – Mike Woodhouse Nov 22 '11 at 12:05

1 Answers1

5

There is a simple way to calculate the square root of an integer, which results in an integer:

  1. To find the square root of a number, set M and P to that number.
  2. Then calculate (M+P/M)/2, rounding each division down.
  3. If M equals or is less than the result, use M as the square root; otherwise, set M to the result and repeat this process at step 2.

This approach may be inefficient for big numbers, though, so try it and see.

EDIT:

Here's the Ruby implementation:

def mysqrt(x)
  return 0 if x==0 
  m=x
  p=x
  loop do
    r=(m+p/m)/2
    return m if m<=r
    m=r
  end
end
Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • it would be great how it works out for sm simple number.. say 9 – Baz1nga Nov 22 '11 at 11:48
  • @Baz1nga: No, that formula is completely different from `(m+p/m)/2` and would lead to incorrect results. – Peter O. Nov 22 '11 at 11:53
  • Ah, good thing that you reminded me! Btw for those that don't know, this is called Newton's Method. It can be further optimized by treating it as a binary search. – davorb Nov 22 '11 at 12:32