문제

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?

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top