How to compute the square root of negative numbers?

牧云@^-^@ 提交于 2019-12-01 07:26:39

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18569027/how-to-compute-the-square-root-of-negative-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!