From b93d9cf2d03c2491e1bdaa0465b2de45cd119f65 Mon Sep 17 00:00:00 2001 From: matz Date: Sat, 14 Jul 2007 14:31:21 +0000 Subject: * numeric.c (fix_pow): integer power calculation: 0**n => 0, 1**n => 1, -1**n => 1 (n: even) / -1 (n: odd). * test/ruby/test_fixnum.rb (TestFixnum::test_pow): update test suite. pow(-3, 2^64) gives NaN when pow(3, 2^64) gives Inf. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@12789 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- numeric.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'numeric.c') diff --git a/numeric.c b/numeric.c index a50199dce..9f986a763 100644 --- a/numeric.c +++ b/numeric.c @@ -2326,14 +2326,21 @@ int_pow(long x, unsigned long y) static VALUE fix_pow(VALUE x, VALUE y) { + long a = FIX2LONG(x); + if (FIXNUM_P(y)) { - long a, b; + long b = FIX2LONG(y); - b = FIX2LONG(y); if (b == 0) return INT2FIX(1); if (b == 1) return x; - a = FIX2LONG(x); if (a == 0) return INT2FIX(0); + if (a == 1) return INT2FIX(1); + if (a == -1) { + if (b % 2 == 0) + return INT2FIX(1); + else + return INT2FIX(-1); + } if (b > 0) { return int_pow(a, b); } @@ -2341,10 +2348,18 @@ fix_pow(VALUE x, VALUE y) } switch (TYPE(y)) { case T_BIGNUM: + if (a == 0) return INT2FIX(0); + if (a == 1) return INT2FIX(1); + if (a == -1) { + if (int_even_p(y)) return INT2FIX(1); + else return INT2FIX(-1); + } x = rb_int2big(FIX2LONG(x)); return rb_big_pow(x, y); case T_FLOAT: - return rb_float_new(pow((double)FIX2LONG(x), RFLOAT(y)->value)); + if (a == 0) return rb_float_new(0.0); + if (a == 1) return rb_float_new(1.0); + return rb_float_new(pow((double)a, RFLOAT(y)->value)); default: return rb_num_coerce_bin(x, y); } -- cgit