How to compute the square root of negative numbers?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 11:21:25

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