summaryrefslogtreecommitdiff
path: root/numeric.c
diff options
context:
space:
mode:
authornaruse <naruse@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2011-11-29 17:29:41 +0000
committernaruse <naruse@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2011-11-29 17:29:41 +0000
commitee490943c14e214cf9bee3d488d1ec6ba9b886fa (patch)
treece0ed3c92454165f52d4ada90c1d0c8657863447 /numeric.c
parent08cd580fa6c756a9ed53bc01a4a7de543829d7dd (diff)
merge revision(s) 33183,33185:
* numeric.c (int_round): Integer#round always returns an Integer [Bug #5271] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_9_3@33897 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'numeric.c')
-rw-r--r--numeric.c64
1 files changed, 41 insertions, 23 deletions
diff --git a/numeric.c b/numeric.c
index 4a94a95608..962d3f3883 100644
--- a/numeric.c
+++ b/numeric.c
@@ -1456,6 +1456,45 @@ flo_ceil(VALUE num)
}
/*
+ * Assumes num is an Integer, ndigits <= 0
+ */
+static VALUE
+int_round_0(VALUE num, int ndigits)
+{
+ VALUE n, f, h, r;
+ long bytes;
+ ID op;
+ /* If 10**N / 2 > num, then return 0 */
+ /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
+ bytes = FIXNUM_P(num) ? sizeof(long) : rb_funcall(num, rb_intern("size"), 0);
+ if (-0.415241 * ndigits - 0.125 > bytes ) {
+ return INT2FIX(0);
+ }
+
+ f = int_pow(10, -ndigits);
+ if (FIXNUM_P(num) && FIXNUM_P(f)) {
+ SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
+ int neg = x < 0;
+ if (neg) x = -x;
+ x = (x + y / 2) / y * y;
+ if (neg) x = -x;
+ return LONG2NUM(x);
+ }
+ if (TYPE(f) == T_FLOAT) {
+ /* then int_pow overflow */
+ return INT2FIX(0);
+ }
+ h = rb_funcall(f, '/', 1, INT2FIX(2));
+ r = rb_funcall(num, '%', 1, f);
+ n = rb_funcall(num, '-', 1, r);
+ op = RTEST(rb_funcall(num, '<', 1, INT2FIX(0))) ? rb_intern("<=") : '<';
+ if (!RTEST(rb_funcall(r, op, 1, h))) {
+ n = rb_funcall(n, '+', 1, f);
+ }
+ return n;
+}
+
+/*
* call-seq:
* flt.round([ndigits]) -> integer or float
*
@@ -3318,9 +3357,8 @@ int_dotimes(VALUE num)
static VALUE
int_round(int argc, VALUE* argv, VALUE num)
{
- VALUE n, f, h, r;
+ VALUE n;
int ndigits;
- ID op;
if (argc == 0) return num;
rb_scan_args(argc, argv, "1", &n);
@@ -3331,27 +3369,7 @@ int_round(int argc, VALUE* argv, VALUE num)
if (ndigits == 0) {
return num;
}
- ndigits = -ndigits;
- if (ndigits < 0) {
- rb_raise(rb_eArgError, "ndigits out of range");
- }
- f = int_pow(10, ndigits);
- if (FIXNUM_P(num) && FIXNUM_P(f)) {
- SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
- int neg = x < 0;
- if (neg) x = -x;
- x = (x + y / 2) / y * y;
- if (neg) x = -x;
- return LONG2NUM(x);
- }
- h = rb_funcall(f, '/', 1, INT2FIX(2));
- r = rb_funcall(num, '%', 1, f);
- n = rb_funcall(num, '-', 1, r);
- op = RTEST(rb_funcall(num, '<', 1, INT2FIX(0))) ? rb_intern("<=") : '<';
- if (!RTEST(rb_funcall(r, op, 1, h))) {
- n = rb_funcall(n, '+', 1, f);
- }
- return n;
+ return int_round_0(num, ndigits);
}
/*