如何计算负数的平方根?
我正在尝试使用以下代码从负数的平方根创建一个复数:
include Math z = Complex(sqrt(-9))
但它产生了这个错误:
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 `'
如何从负数的平方根构建复数?
Math.sqrt
函数无法计算负数的平方根:
irb> Math.sqrt(-1) Math::DomainError: Numerical argument is out of domain - "sqrt" ...
您必须使用根据需要返回复数的CMath
模块:
irb> require 'cmath' irb> CMath.sqrt(-1) # => (0+1.0i) irb> CMath.sqrt(-1).class # => Complex irb> CMath.sqrt(1).class # => Float