1

ruby​​-doc中,它说<Fixnum> ** <Numeric>可能是分数,并给出了示例:

2 ** -1 #=> 0.5
2 ** 0.5 #=> 1.4142135623731

但在我的 irb 上,它有时会给出如下Rational指数的答案-1

2 ** -1 #=> (1/2)
2 ** 0.5 #=> 1.4142135623731

看起来 ruby​​-doc 不准确,并且 ruby​​ 尝试Rational在可能的情况下进行类型转换,但我不完全确定。当基数和指数都是 时,这里的确切类型转换规则是Fixnum什么?我对 Ruby 1.9.3 特别感兴趣,但是不同版本的结果是否不同?

4

1 回答 1

1

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);

现在我们可以继续阅读 Rational 的文档**检查它对操作符的描述:

rat ** numeric → numeric

执行幂运算。

例如:

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
于 2012-01-01T04:44:56.487 回答