在ruby-doc中,它指出<Fixnum> ** <Numeric>可能是小数,并给出了示例:
2 ** -1 #=> 0.5
2 ** 0.5 #=> 1.4142135623731但在我的irb上,它有时会像下面的指数-1一样给出一个Rational答案:
2 ** -1 #=> (1/2)
2 ** 0.5 #=> 1.4142135623731看起来ruby-doc并不准确,并且ruby尽可能尝试将类型转换为Rational,但我不能完全确定。当基数和指数都为Fixnum时,这里确切的类型转换规则是什么?我对Ruby 1.9.3特别感兴趣,但是不同版本的结果不同吗?
发布于 2012-01-01 12:44:56
DGM是正确的;答案在您链接的文档中是正确的,尽管它是用C编写的。这里是相关的部分;我添加了一些注释:
static VALUE
fix_pow(VALUE x, VALUE y)
{
long a = FIX2LONG(x);
if (FIXNUM_P(y)) { // checks to see if Y is a Fixnum
long b = FIX2LONG(y);
if (b < 0)
// if b is less than zero, convert x into a Rational
// and call ** on it and 1 over y
// (this is how you raise to a negative power).
return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);现在,我们可以转到docs for Rational,看看它是如何描述the ** operator的
rat **数字→数字
执行幂运算。
例如:
Rational(2) ** Rational(3) #=> (8/1) Rational(10) ** -2 #=> (1/100) Rational(10) ** -2.0 #=> 0.01 Rational(-4) ** Rational(1,2) #=> (1.2246063538223773e-16+2.0i) Rational(1,2) ** 0 #=> (1/1) Rational(1,2) ** 0.0 #=> 1.0
https://stackoverflow.com/questions/8691804
复制相似问题