Search code examples
rubycomplex-numberssqrt

How to compute the square root of negative numbers?


I'm trying to create a complex number from the square root of a negative number using the following code:

 include Math
 z = Complex(sqrt(-9))

But it produces this error:

Math::DomainError: Numerical argument is out of domain - "sqrt"
    from kata2.rb:20:in `sqrt'
    from kata2.rb:20:in `polinomio'
    from kata2.rb:34
    from /home/howarto/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `<main>'

How can I build a complex number from the square root of a negative number?


Solution

  • The Math.sqrt function can't compute the square root of negative numbers:

    irb> Math.sqrt(-1)
    Math::DomainError: Numerical argument is out of domain - "sqrt"
    ...
    

    You have to use the CMath module that return complex numbers as needed:

    irb> require 'cmath'
    irb> CMath.sqrt(-1)
    # => (0+1.0i) 
    irb> CMath.sqrt(-1).class
    # => Complex
    irb> CMath.sqrt(1).class
    # => Float