如何计算负数的平方根? [英] 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))
但是它会产生此错误: / p>
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?
推荐答案
数学。 sqrt
函数无法计算负数的平方根:
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"
...
您必须使用 CMath
模块,可根据需要返回复数:
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
这篇关于如何计算负数的平方根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文