1 /**********************************************************************
2 
3   numeric.c -
4 
5   $Author: usa $
6   created at: Fri Aug 13 18:33:09 JST 1993
7 
8   Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 #include "ruby/encoding.h"
13 #include "ruby/util.h"
14 #include "internal.h"
15 #include "id.h"
16 #include <assert.h>
17 #include <ctype.h>
18 #include <math.h>
19 #include <stdio.h>
20 
21 #ifdef HAVE_FLOAT_H
22 #include <float.h>
23 #endif
24 
25 #ifdef HAVE_IEEEFP_H
26 #include <ieeefp.h>
27 #endif
28 
29 /* use IEEE 64bit values if not defined */
30 #ifndef FLT_RADIX
31 #define FLT_RADIX 2
32 #endif
33 #ifndef FLT_ROUNDS
34 #define FLT_ROUNDS 1
35 #endif
36 #ifndef DBL_MIN
37 #define DBL_MIN 2.2250738585072014e-308
38 #endif
39 #ifndef DBL_MAX
40 #define DBL_MAX 1.7976931348623157e+308
41 #endif
42 #ifndef DBL_MIN_EXP
43 #define DBL_MIN_EXP (-1021)
44 #endif
45 #ifndef DBL_MAX_EXP
46 #define DBL_MAX_EXP 1024
47 #endif
48 #ifndef DBL_MIN_10_EXP
49 #define DBL_MIN_10_EXP (-307)
50 #endif
51 #ifndef DBL_MAX_10_EXP
52 #define DBL_MAX_10_EXP 308
53 #endif
54 #ifndef DBL_DIG
55 #define DBL_DIG 15
56 #endif
57 #ifndef DBL_MANT_DIG
58 #define DBL_MANT_DIG 53
59 #endif
60 #ifndef DBL_EPSILON
61 #define DBL_EPSILON 2.2204460492503131e-16
62 #endif
63 
64 #ifndef USE_RB_INFINITY
65 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
66 const union bytesequence4_or_float rb_infinity = {{0x00, 0x00, 0x80, 0x7f}};
67 #else
68 const union bytesequence4_or_float rb_infinity = {{0x7f, 0x80, 0x00, 0x00}};
69 #endif
70 
71 #ifndef USE_RB_NAN
72 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
73 const union bytesequence4_or_float rb_nan = {{0x00, 0x00, 0xc0, 0x7f}};
74 #else
75 const union bytesequence4_or_float rb_nan = {{0x7f, 0xc0, 0x00, 0x00}};
76 #endif
77 
78 #ifndef HAVE_ROUND
79 double
round(double x)80 round(double x)
81 {
82     double f;
83 
84     if (x > 0.0) {
85 	f = floor(x);
86 	x = f + (x - f >= 0.5);
87     }
88     else if (x < 0.0) {
89 	f = ceil(x);
90 	x = f - (f - x >= 0.5);
91     }
92     return x;
93 }
94 #endif
95 
96 static double
round_half_up(double x,double s)97 round_half_up(double x, double s)
98 {
99     double f, xs = x * s;
100 
101     f = round(xs);
102     if (s == 1.0) return f;
103     if (x > 0) {
104 	if ((double)((f + 0.5) / s) <= x) f += 1;
105 	x = f;
106     }
107     else {
108 	if ((double)((f - 0.5) / s) >= x) f -= 1;
109 	x = f;
110     }
111     return x;
112 }
113 
114 static double
round_half_down(double x,double s)115 round_half_down(double x, double s)
116 {
117     double f, xs = x * s;
118 
119     f = round(xs);
120     if (x > 0) {
121 	if ((double)((f - 0.5) / s) >= x) f -= 1;
122 	x = f;
123     }
124     else {
125 	if ((double)((f + 0.5) / s) <= x) f += 1;
126 	x = f;
127     }
128     return x;
129 }
130 
131 static double
round_half_even(double x,double s)132 round_half_even(double x, double s)
133 {
134     double f, d, xs = x * s;
135 
136     if (x > 0.0) {
137 	f = floor(xs);
138 	d = xs - f;
139 	if (d > 0.5)
140 	    d = 1.0;
141 	else if (d == 0.5 || ((double)((f + 0.5) / s) <= x))
142 	    d = fmod(f, 2.0);
143 	else
144 	    d = 0.0;
145 	x = f + d;
146     }
147     else if (x < 0.0) {
148 	f = ceil(xs);
149 	d = f - xs;
150 	if (d > 0.5)
151 	    d = 1.0;
152 	else if (d == 0.5 || ((double)((f - 0.5) / s) >= x))
153 	    d = fmod(-f, 2.0);
154 	else
155 	    d = 0.0;
156 	x = f - d;
157     }
158     return x;
159 }
160 
161 static VALUE fix_uminus(VALUE num);
162 static VALUE fix_mul(VALUE x, VALUE y);
163 static VALUE fix_lshift(long, unsigned long);
164 static VALUE fix_rshift(long, unsigned long);
165 static VALUE int_pow(long x, unsigned long y);
166 static VALUE int_even_p(VALUE x);
167 static int int_round_zero_p(VALUE num, int ndigits);
168 VALUE rb_int_floor(VALUE num, int ndigits);
169 VALUE rb_int_ceil(VALUE num, int ndigits);
170 static VALUE flo_to_i(VALUE num);
171 static int float_round_overflow(int ndigits, int binexp);
172 static int float_round_underflow(int ndigits, int binexp);
173 
174 static ID id_coerce, id_div, id_divmod;
175 #define id_to_i idTo_i
176 #define id_eq  idEq
177 #define id_cmp idCmp
178 
179 VALUE rb_cNumeric;
180 VALUE rb_cFloat;
181 VALUE rb_cInteger;
182 #ifndef RUBY_INTEGER_UNIFICATION
183 VALUE rb_cFixnum;
184 #endif
185 
186 VALUE rb_eZeroDivError;
187 VALUE rb_eFloatDomainError;
188 
189 static ID id_to, id_by;
190 
191 void
rb_num_zerodiv(void)192 rb_num_zerodiv(void)
193 {
194     rb_raise(rb_eZeroDivError, "divided by 0");
195 }
196 
197 enum ruby_num_rounding_mode
rb_num_get_rounding_option(VALUE opts)198 rb_num_get_rounding_option(VALUE opts)
199 {
200     static ID round_kwds[1];
201     VALUE rounding;
202     VALUE str;
203     const char *s;
204 
205     if (!NIL_P(opts)) {
206 	if (!round_kwds[0]) {
207 	    round_kwds[0] = rb_intern_const("half");
208 	}
209 	if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
210 	if (SYMBOL_P(rounding)) {
211 	    str = rb_sym2str(rounding);
212 	}
213 	else if (NIL_P(rounding)) {
214 	    goto noopt;
215 	}
216 	else if (!RB_TYPE_P(str = rounding, T_STRING)) {
217 	    str = rb_check_string_type(rounding);
218 	    if (NIL_P(str)) goto invalid;
219 	}
220 	s = RSTRING_PTR(str);
221 	switch (RSTRING_LEN(str)) {
222 	  case 2:
223 	    if (rb_memcicmp(s, "up", 2) == 0)
224 		return RUBY_NUM_ROUND_HALF_UP;
225 	    break;
226 	  case 4:
227 	    if (rb_memcicmp(s, "even", 4) == 0)
228 		return RUBY_NUM_ROUND_HALF_EVEN;
229 	    if (strncasecmp(s, "down", 4) == 0)
230 		return RUBY_NUM_ROUND_HALF_DOWN;
231 	    break;
232 	}
233       invalid:
234 	rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
235     }
236   noopt:
237     return RUBY_NUM_ROUND_DEFAULT;
238 }
239 
240 /* experimental API */
241 int
rb_num_to_uint(VALUE val,unsigned int * ret)242 rb_num_to_uint(VALUE val, unsigned int *ret)
243 {
244 #define NUMERR_TYPE     1
245 #define NUMERR_NEGATIVE 2
246 #define NUMERR_TOOLARGE 3
247     if (FIXNUM_P(val)) {
248 	long v = FIX2LONG(val);
249 #if SIZEOF_INT < SIZEOF_LONG
250 	if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
251 #endif
252 	if (v < 0) return NUMERR_NEGATIVE;
253 	*ret = (unsigned int)v;
254 	return 0;
255     }
256 
257     if (RB_TYPE_P(val, T_BIGNUM)) {
258 	if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
259 #if SIZEOF_INT < SIZEOF_LONG
260 	/* long is 64bit */
261 	return NUMERR_TOOLARGE;
262 #else
263 	/* long is 32bit */
264 	if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
265 	*ret = (unsigned int)rb_big2ulong((VALUE)val);
266 	return 0;
267 #endif
268     }
269     return NUMERR_TYPE;
270 }
271 
272 #define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
273 
274 static inline int
int_pos_p(VALUE num)275 int_pos_p(VALUE num)
276 {
277     if (FIXNUM_P(num)) {
278 	return FIXNUM_POSITIVE_P(num);
279     }
280     else if (RB_TYPE_P(num, T_BIGNUM)) {
281 	return BIGNUM_POSITIVE_P(num);
282     }
283     rb_raise(rb_eTypeError, "not an Integer");
284 }
285 
286 static inline int
int_neg_p(VALUE num)287 int_neg_p(VALUE num)
288 {
289     if (FIXNUM_P(num)) {
290 	return FIXNUM_NEGATIVE_P(num);
291     }
292     else if (RB_TYPE_P(num, T_BIGNUM)) {
293 	return BIGNUM_NEGATIVE_P(num);
294     }
295     rb_raise(rb_eTypeError, "not an Integer");
296 }
297 
298 int
rb_int_positive_p(VALUE num)299 rb_int_positive_p(VALUE num)
300 {
301     return int_pos_p(num);
302 }
303 
304 int
rb_int_negative_p(VALUE num)305 rb_int_negative_p(VALUE num)
306 {
307     return int_neg_p(num);
308 }
309 
310 int
rb_num_negative_p(VALUE num)311 rb_num_negative_p(VALUE num)
312 {
313     return rb_num_negative_int_p(num);
314 }
315 
316 static VALUE
num_funcall_op_0(VALUE x,VALUE arg,int recursive)317 num_funcall_op_0(VALUE x, VALUE arg, int recursive)
318 {
319     ID func = (ID)arg;
320     if (recursive) {
321 	const char *name = rb_id2name(func);
322 	if (ISALNUM(name[0])) {
323 	    rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
324 			  x, ID2SYM(func));
325 	}
326 	else if (name[0] && name[1] == '@' && !name[2]) {
327 	    rb_name_error(func, "%c%"PRIsVALUE,
328 			  name[0], x);
329 	}
330 	else {
331 	    rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
332 			  ID2SYM(func), x);
333 	}
334     }
335     return rb_funcallv(x, func, 0, 0);
336 }
337 
338 static VALUE
num_funcall0(VALUE x,ID func)339 num_funcall0(VALUE x, ID func)
340 {
341     return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
342 }
343 
344 NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
345 
346 static void
num_funcall_op_1_recursion(VALUE x,ID func,VALUE y)347 num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
348 {
349     const char *name = rb_id2name(func);
350     if (ISALNUM(name[0])) {
351 	rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
352 		      x, ID2SYM(func), y);
353     }
354     else {
355 	rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
356 		      x, ID2SYM(func), y);
357     }
358 }
359 
360 static VALUE
num_funcall_op_1(VALUE y,VALUE arg,int recursive)361 num_funcall_op_1(VALUE y, VALUE arg, int recursive)
362 {
363     ID func = (ID)((VALUE *)arg)[0];
364     VALUE x = ((VALUE *)arg)[1];
365     if (recursive) {
366 	num_funcall_op_1_recursion(x, func, y);
367     }
368     return rb_funcall(x, func, 1, y);
369 }
370 
371 static VALUE
num_funcall1(VALUE x,ID func,VALUE y)372 num_funcall1(VALUE x, ID func, VALUE y)
373 {
374     VALUE args[2];
375     args[0] = (VALUE)func;
376     args[1] = x;
377     return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
378 }
379 
380 /*
381  *  call-seq:
382  *     num.coerce(numeric)  ->  array
383  *
384  *  If +numeric+ is the same type as +num+, returns an array
385  *  <code>[numeric, num]</code>. Otherwise, returns an array with both
386  *  +numeric+ and +num+ represented as Float objects.
387  *
388  *  This coercion mechanism is used by Ruby to handle mixed-type numeric
389  *  operations: it is intended to find a compatible common type between the two
390  *  operands of the operator.
391  *
392  *     1.coerce(2.5)   #=> [2.5, 1.0]
393  *     1.2.coerce(3)   #=> [3.0, 1.2]
394  *     1.coerce(2)     #=> [2, 1]
395  */
396 
397 static VALUE
num_coerce(VALUE x,VALUE y)398 num_coerce(VALUE x, VALUE y)
399 {
400     if (CLASS_OF(x) == CLASS_OF(y))
401 	return rb_assoc_new(y, x);
402     x = rb_Float(x);
403     y = rb_Float(y);
404     return rb_assoc_new(y, x);
405 }
406 
407 NORETURN(static void coerce_failed(VALUE x, VALUE y));
408 static void
coerce_failed(VALUE x,VALUE y)409 coerce_failed(VALUE x, VALUE y)
410 {
411     if (SPECIAL_CONST_P(y) || BUILTIN_TYPE(y) == T_FLOAT) {
412 	y = rb_inspect(y);
413     }
414     else {
415 	y = rb_obj_class(y);
416     }
417     rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
418 	     y, rb_obj_class(x));
419 }
420 
421 static int
do_coerce(VALUE * x,VALUE * y,int err)422 do_coerce(VALUE *x, VALUE *y, int err)
423 {
424     VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
425     if (ary == Qundef) {
426 	if (err) {
427 	    coerce_failed(*x, *y);
428 	}
429 	return FALSE;
430     }
431     if (!err && NIL_P(ary)) {
432 	return FALSE;
433     }
434     if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
435 	rb_raise(rb_eTypeError, "coerce must return [x, y]");
436     }
437 
438     *x = RARRAY_AREF(ary, 0);
439     *y = RARRAY_AREF(ary, 1);
440     return TRUE;
441 }
442 
443 VALUE
rb_num_coerce_bin(VALUE x,VALUE y,ID func)444 rb_num_coerce_bin(VALUE x, VALUE y, ID func)
445 {
446     do_coerce(&x, &y, TRUE);
447     return rb_funcall(x, func, 1, y);
448 }
449 
450 VALUE
rb_num_coerce_cmp(VALUE x,VALUE y,ID func)451 rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
452 {
453     if (do_coerce(&x, &y, FALSE))
454 	return rb_funcall(x, func, 1, y);
455     return Qnil;
456 }
457 
458 VALUE
rb_num_coerce_relop(VALUE x,VALUE y,ID func)459 rb_num_coerce_relop(VALUE x, VALUE y, ID func)
460 {
461     VALUE c, x0 = x, y0 = y;
462 
463     if (!do_coerce(&x, &y, FALSE) ||
464 	NIL_P(c = rb_funcall(x, func, 1, y))) {
465 	rb_cmperr(x0, y0);
466 	return Qnil;		/* not reached */
467     }
468     return c;
469 }
470 
471 /*
472  * :nodoc:
473  *
474  * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
475  *
476  * Numerics should be values; singleton_methods should not be added to them.
477  */
478 
479 static VALUE
num_sadded(VALUE x,VALUE name)480 num_sadded(VALUE x, VALUE name)
481 {
482     ID mid = rb_to_id(name);
483     /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
484     rb_remove_method_id(rb_singleton_class(x), mid);
485     rb_raise(rb_eTypeError,
486 	     "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
487 	     rb_id2str(mid),
488 	     rb_obj_class(x));
489 
490     UNREACHABLE_RETURN(Qnil);
491 }
492 
493 #if 0
494 /*
495  *  call-seq:
496  *     num.clone(freeze: true)  ->  num
497  *
498  *  Returns the receiver.  +freeze+ cannot be +false+.
499  */
500 static VALUE
501 num_clone(int argc, VALUE *argv, VALUE x)
502 {
503     return rb_immutable_obj_clone(argc, argv, x);
504 }
505 #else
506 # define num_clone rb_immutable_obj_clone
507 #endif
508 
509 #if 0
510 /*
511  *  call-seq:
512  *     num.dup  ->  num
513  *
514  *  Returns the receiver.
515  */
516 static VALUE
517 num_dup(VALUE x)
518 {
519     return x;
520 }
521 #else
522 # define num_dup num_uplus
523 #endif
524 
525 /*
526  *  call-seq:
527  *     +num  ->  num
528  *
529  *  Unary Plus---Returns the receiver.
530  */
531 
532 static VALUE
num_uplus(VALUE num)533 num_uplus(VALUE num)
534 {
535     return num;
536 }
537 
538 /*
539  *  call-seq:
540  *     num.i  ->  Complex(0, num)
541  *
542  *  Returns the corresponding imaginary number.
543  *  Not available for complex numbers.
544  *
545  *     -42.i  #=> (0-42i)
546  *     2.0.i  #=> (0+2.0i)
547  */
548 
549 static VALUE
num_imaginary(VALUE num)550 num_imaginary(VALUE num)
551 {
552     return rb_complex_new(INT2FIX(0), num);
553 }
554 
555 /*
556  *  call-seq:
557  *     -num  ->  numeric
558  *
559  *  Unary Minus---Returns the receiver, negated.
560  */
561 
562 static VALUE
num_uminus(VALUE num)563 num_uminus(VALUE num)
564 {
565     VALUE zero;
566 
567     zero = INT2FIX(0);
568     do_coerce(&zero, &num, TRUE);
569 
570     return num_funcall1(zero, '-', num);
571 }
572 
573 /*
574  *  call-seq:
575  *     num.fdiv(numeric)  ->  float
576  *
577  *  Returns float division.
578  */
579 
580 static VALUE
num_fdiv(VALUE x,VALUE y)581 num_fdiv(VALUE x, VALUE y)
582 {
583     return rb_funcall(rb_Float(x), '/', 1, y);
584 }
585 
586 /*
587  *  call-seq:
588  *     num.div(numeric)  ->  integer
589  *
590  *  Uses +/+ to perform division, then converts the result to an integer.
591  *  Numeric does not define the +/+ operator; this is left to subclasses.
592  *
593  *  Equivalent to <code>num.divmod(numeric)[0]</code>.
594  *
595  *  See Numeric#divmod.
596  */
597 
598 static VALUE
num_div(VALUE x,VALUE y)599 num_div(VALUE x, VALUE y)
600 {
601     if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
602     return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
603 }
604 
605 /*
606  *  call-seq:
607  *     num.modulo(numeric)  ->  real
608  *
609  *  <code>x.modulo(y)</code> means <code>x-y*(x/y).floor</code>.
610  *
611  *  Equivalent to <code>num.divmod(numeric)[1]</code>.
612  *
613  *  See Numeric#divmod.
614  */
615 
616 static VALUE
num_modulo(VALUE x,VALUE y)617 num_modulo(VALUE x, VALUE y)
618 {
619     VALUE q = num_funcall1(x, id_div, y);
620     return rb_funcall(x, '-', 1,
621 		      rb_funcall(y, '*', 1, q));
622 }
623 
624 /*
625  *  call-seq:
626  *     num.remainder(numeric)  ->  real
627  *
628  *  <code>x.remainder(y)</code> means <code>x-y*(x/y).truncate</code>.
629  *
630  *  See Numeric#divmod.
631  */
632 
633 static VALUE
num_remainder(VALUE x,VALUE y)634 num_remainder(VALUE x, VALUE y)
635 {
636     VALUE z = num_funcall1(x, '%', y);
637 
638     if ((!rb_equal(z, INT2FIX(0))) &&
639 	((rb_num_negative_int_p(x) &&
640 	  rb_num_positive_int_p(y)) ||
641 	 (rb_num_positive_int_p(x) &&
642 	  rb_num_negative_int_p(y)))) {
643 	return rb_funcall(z, '-', 1, y);
644     }
645     return z;
646 }
647 
648 /*
649  *  call-seq:
650  *     num.divmod(numeric)  ->  array
651  *
652  *  Returns an array containing the quotient and modulus obtained by dividing
653  *  +num+ by +numeric+.
654  *
655  *  If <code>q, r = x.divmod(y)</code>, then
656  *
657  *      q = floor(x/y)
658  *      x = q*y + r
659  *
660  *  The quotient is rounded toward negative infinity, as shown in the
661  *  following table:
662  *
663  *     a    |  b  |  a.divmod(b)  |   a/b   | a.modulo(b) | a.remainder(b)
664  *    ------+-----+---------------+---------+-------------+---------------
665  *     13   |  4  |   3,    1     |   3     |    1        |     1
666  *    ------+-----+---------------+---------+-------------+---------------
667  *     13   | -4  |  -4,   -3     |  -4     |   -3        |     1
668  *    ------+-----+---------------+---------+-------------+---------------
669  *    -13   |  4  |  -4,    3     |  -4     |    3        |    -1
670  *    ------+-----+---------------+---------+-------------+---------------
671  *    -13   | -4  |   3,   -1     |   3     |   -1        |    -1
672  *    ------+-----+---------------+---------+-------------+---------------
673  *     11.5 |  4  |   2,    3.5   |   2.875 |    3.5      |     3.5
674  *    ------+-----+---------------+---------+-------------+---------------
675  *     11.5 | -4  |  -3,   -0.5   |  -2.875 |   -0.5      |     3.5
676  *    ------+-----+---------------+---------+-------------+---------------
677  *    -11.5 |  4  |  -3,    0.5   |  -2.875 |    0.5      |    -3.5
678  *    ------+-----+---------------+---------+-------------+---------------
679  *    -11.5 | -4  |   2,   -3.5   |   2.875 |   -3.5      |    -3.5
680  *
681  *
682  *  Examples
683  *
684  *     11.divmod(3)        #=> [3, 2]
685  *     11.divmod(-3)       #=> [-4, -1]
686  *     11.divmod(3.5)      #=> [3, 0.5]
687  *     (-11).divmod(3.5)   #=> [-4, 3.0]
688  *     11.5.divmod(3.5)    #=> [3, 1.0]
689  */
690 
691 static VALUE
num_divmod(VALUE x,VALUE y)692 num_divmod(VALUE x, VALUE y)
693 {
694     return rb_assoc_new(num_div(x, y), num_modulo(x, y));
695 }
696 
697 /*
698  *  call-seq:
699  *     num.real?  ->  true or false
700  *
701  *  Returns +true+ if +num+ is a real number (i.e. not Complex).
702  */
703 
704 static VALUE
num_real_p(VALUE num)705 num_real_p(VALUE num)
706 {
707     return Qtrue;
708 }
709 
710 /*
711  *  call-seq:
712  *     num.integer?  ->  true or false
713  *
714  *  Returns +true+ if +num+ is an Integer.
715  *
716  *      1.0.integer?   #=> false
717  *      1.integer?     #=> true
718  */
719 
720 static VALUE
num_int_p(VALUE num)721 num_int_p(VALUE num)
722 {
723     return Qfalse;
724 }
725 
726 /*
727  *  call-seq:
728  *     num.abs        ->  numeric
729  *     num.magnitude  ->  numeric
730  *
731  *  Returns the absolute value of +num+.
732  *
733  *     12.abs         #=> 12
734  *     (-34.56).abs   #=> 34.56
735  *     -34.56.abs     #=> 34.56
736  *
737  *  Numeric#magnitude is an alias for Numeric#abs.
738  */
739 
740 static VALUE
num_abs(VALUE num)741 num_abs(VALUE num)
742 {
743     if (rb_num_negative_int_p(num)) {
744 	return num_funcall0(num, idUMinus);
745     }
746     return num;
747 }
748 
749 /*
750  *  call-seq:
751  *     num.zero?  ->  true or false
752  *
753  *  Returns +true+ if +num+ has a zero value.
754  */
755 
756 static VALUE
num_zero_p(VALUE num)757 num_zero_p(VALUE num)
758 {
759     if (FIXNUM_P(num)) {
760 	if (FIXNUM_ZERO_P(num)) {
761 	    return Qtrue;
762 	}
763     }
764     else if (RB_TYPE_P(num, T_BIGNUM)) {
765 	if (rb_bigzero_p(num)) {
766 	    /* this should not happen usually */
767 	    return Qtrue;
768 	}
769     }
770     else if (rb_equal(num, INT2FIX(0))) {
771 	return Qtrue;
772     }
773     return Qfalse;
774 }
775 
776 /*
777  *  call-seq:
778  *     num.nonzero?  ->  self or nil
779  *
780  *  Returns +self+ if +num+ is not zero, +nil+ otherwise.
781  *
782  *  This behavior is useful when chaining comparisons:
783  *
784  *     a = %w( z Bb bB bb BB a aA Aa AA A )
785  *     b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
786  *     b   #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
787  */
788 
789 static VALUE
num_nonzero_p(VALUE num)790 num_nonzero_p(VALUE num)
791 {
792     if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
793 	return Qnil;
794     }
795     return num;
796 }
797 
798 /*
799  *  call-seq:
800  *     num.finite?  ->  true or false
801  *
802  *  Returns +true+ if +num+ is a finite number, otherwise returns +false+.
803  */
804 static VALUE
num_finite_p(VALUE num)805 num_finite_p(VALUE num)
806 {
807     return Qtrue;
808 }
809 
810 /*
811  *  call-seq:
812  *     num.infinite?  ->  -1, 1, or nil
813  *
814  *  Returns +nil+, -1, or 1 depending on whether the value is
815  *  finite, <code>-Infinity</code>, or <code>+Infinity</code>.
816  */
817 static VALUE
num_infinite_p(VALUE num)818 num_infinite_p(VALUE num)
819 {
820     return Qnil;
821 }
822 
823 /*
824  *  call-seq:
825  *     num.to_int  ->  integer
826  *
827  *  Invokes the child class's +to_i+ method to convert +num+ to an integer.
828  *
829  *      1.0.class          #=> Float
830  *      1.0.to_int.class   #=> Integer
831  *      1.0.to_i.class     #=> Integer
832  */
833 
834 static VALUE
num_to_int(VALUE num)835 num_to_int(VALUE num)
836 {
837     return num_funcall0(num, id_to_i);
838 }
839 
840 /*
841  *  call-seq:
842  *     num.positive?  ->  true or false
843  *
844  *  Returns +true+ if +num+ is greater than 0.
845  */
846 
847 static VALUE
num_positive_p(VALUE num)848 num_positive_p(VALUE num)
849 {
850     const ID mid = '>';
851 
852     if (FIXNUM_P(num)) {
853 	if (method_basic_p(rb_cInteger))
854 	    return (SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0) ? Qtrue : Qfalse;
855     }
856     else if (RB_TYPE_P(num, T_BIGNUM)) {
857 	if (method_basic_p(rb_cInteger))
858 	    return BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num) ? Qtrue : Qfalse;
859     }
860     return rb_num_compare_with_zero(num, mid);
861 }
862 
863 /*
864  *  call-seq:
865  *     num.negative?  ->  true or false
866  *
867  *  Returns +true+ if +num+ is less than 0.
868  */
869 
870 static VALUE
num_negative_p(VALUE num)871 num_negative_p(VALUE num)
872 {
873     return rb_num_negative_int_p(num) ? Qtrue : Qfalse;
874 }
875 
876 
877 /********************************************************************
878  *
879  * Document-class: Float
880  *
881  *  Float objects represent inexact real numbers using the native
882  *  architecture's double-precision floating point representation.
883  *
884  *  Floating point has a different arithmetic and is an inexact number.
885  *  So you should know its esoteric system. See following:
886  *
887  *  - http://docs.sun.com/source/806-3568/ncg_goldberg.html
888  *  - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#floats_imprecise
889  *  - http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
890  */
891 
892 VALUE
rb_float_new_in_heap(double d)893 rb_float_new_in_heap(double d)
894 {
895     NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0));
896 
897     flt->float_value = d;
898     OBJ_FREEZE(flt);
899     return (VALUE)flt;
900 }
901 
902 /*
903  *  call-seq:
904  *     float.to_s  ->  string
905  *
906  *  Returns a string containing a representation of +self+.
907  *  As well as a fixed or exponential form of the +float+,
908  *  the call may return +NaN+, +Infinity+, and +-Infinity+.
909  */
910 
911 static VALUE
flo_to_s(VALUE flt)912 flo_to_s(VALUE flt)
913 {
914     enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
915     enum {float_dig = DBL_DIG+1};
916     char buf[float_dig + (decimal_mant + CHAR_BIT - 1) / CHAR_BIT + 10];
917     double value = RFLOAT_VALUE(flt);
918     VALUE s;
919     char *p, *e;
920     int sign, decpt, digs;
921 
922     if (isinf(value)) {
923 	static const char minf[] = "-Infinity";
924 	const int pos = (value > 0); /* skip "-" */
925 	return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
926     }
927     else if (isnan(value))
928 	return rb_usascii_str_new2("NaN");
929 
930     p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
931     s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
932     if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
933     memcpy(buf, p, digs);
934     xfree(p);
935     if (decpt > 0) {
936 	if (decpt < digs) {
937 	    memmove(buf + decpt + 1, buf + decpt, digs - decpt);
938 	    buf[decpt] = '.';
939 	    rb_str_cat(s, buf, digs + 1);
940 	}
941 	else if (decpt <= DBL_DIG) {
942 	    long len;
943 	    char *ptr;
944 	    rb_str_cat(s, buf, digs);
945 	    rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
946 	    ptr = RSTRING_PTR(s) + len;
947 	    if (decpt > digs) {
948 		memset(ptr, '0', decpt - digs);
949 		ptr += decpt - digs;
950 	    }
951 	    memcpy(ptr, ".0", 2);
952 	}
953 	else {
954 	    goto exp;
955 	}
956     }
957     else if (decpt > -4) {
958 	long len;
959 	char *ptr;
960 	rb_str_cat(s, "0.", 2);
961 	rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
962 	ptr = RSTRING_PTR(s);
963 	memset(ptr += len, '0', -decpt);
964 	memcpy(ptr -= decpt, buf, digs);
965     }
966     else {
967       exp:
968 	if (digs > 1) {
969 	    memmove(buf + 2, buf + 1, digs - 1);
970 	}
971 	else {
972 	    buf[2] = '0';
973 	    digs++;
974 	}
975 	buf[1] = '.';
976 	rb_str_cat(s, buf, digs + 1);
977 	rb_str_catf(s, "e%+03d", decpt - 1);
978     }
979     return s;
980 }
981 
982 /*
983  *  call-seq:
984  *     float.coerce(numeric)  ->  array
985  *
986  *  Returns an array with both +numeric+ and +float+ represented as Float
987  *  objects.
988  *
989  *  This is achieved by converting +numeric+ to a Float.
990  *
991  *     1.2.coerce(3)       #=> [3.0, 1.2]
992  *     2.5.coerce(1.1)     #=> [1.1, 2.5]
993  */
994 
995 static VALUE
flo_coerce(VALUE x,VALUE y)996 flo_coerce(VALUE x, VALUE y)
997 {
998     return rb_assoc_new(rb_Float(y), x);
999 }
1000 
1001 /*
1002  * call-seq:
1003  *    -float  ->  float
1004  *
1005  * Returns +float+, negated.
1006  */
1007 
1008 VALUE
rb_float_uminus(VALUE flt)1009 rb_float_uminus(VALUE flt)
1010 {
1011     return DBL2NUM(-RFLOAT_VALUE(flt));
1012 }
1013 
1014 /*
1015  * call-seq:
1016  *   float + other  ->  float
1017  *
1018  * Returns a new Float which is the sum of +float+ and +other+.
1019  */
1020 
1021 VALUE
rb_float_plus(VALUE x,VALUE y)1022 rb_float_plus(VALUE x, VALUE y)
1023 {
1024     if (RB_TYPE_P(y, T_FIXNUM)) {
1025 	return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1026     }
1027     else if (RB_TYPE_P(y, T_BIGNUM)) {
1028 	return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1029     }
1030     else if (RB_TYPE_P(y, T_FLOAT)) {
1031 	return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1032     }
1033     else {
1034 	return rb_num_coerce_bin(x, y, '+');
1035     }
1036 }
1037 
1038 /*
1039  * call-seq:
1040  *   float - other  ->  float
1041  *
1042  * Returns a new Float which is the difference of +float+ and +other+.
1043  */
1044 
1045 VALUE
rb_float_minus(VALUE x,VALUE y)1046 rb_float_minus(VALUE x, VALUE y)
1047 {
1048     if (RB_TYPE_P(y, T_FIXNUM)) {
1049 	return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1050     }
1051     else if (RB_TYPE_P(y, T_BIGNUM)) {
1052 	return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1053     }
1054     else if (RB_TYPE_P(y, T_FLOAT)) {
1055 	return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1056     }
1057     else {
1058 	return rb_num_coerce_bin(x, y, '-');
1059     }
1060 }
1061 
1062 /*
1063  * call-seq:
1064  *   float * other  ->  float
1065  *
1066  * Returns a new Float which is the product of +float+ and +other+.
1067  */
1068 
1069 VALUE
rb_float_mul(VALUE x,VALUE y)1070 rb_float_mul(VALUE x, VALUE y)
1071 {
1072     if (RB_TYPE_P(y, T_FIXNUM)) {
1073 	return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1074     }
1075     else if (RB_TYPE_P(y, T_BIGNUM)) {
1076 	return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1077     }
1078     else if (RB_TYPE_P(y, T_FLOAT)) {
1079 	return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1080     }
1081     else {
1082 	return rb_num_coerce_bin(x, y, '*');
1083     }
1084 }
1085 
1086 static bool
flo_iszero(VALUE f)1087 flo_iszero(VALUE f)
1088 {
1089     return RFLOAT_VALUE(f) == 0.0;
1090 }
1091 
1092 static double
double_div_double(double x,double y)1093 double_div_double(double x, double y)
1094 {
1095     if (LIKELY(y != 0.0)) {
1096         return x / y;
1097     }
1098     else if (x == 0.0) {
1099         return nan("");
1100     }
1101     else {
1102         double z = signbit(y) ? -1.0 : 1.0;
1103         return x * z * HUGE_VAL;
1104     }
1105 }
1106 
1107 MJIT_FUNC_EXPORTED VALUE
rb_flo_div_flo(VALUE x,VALUE y)1108 rb_flo_div_flo(VALUE x, VALUE y)
1109 {
1110     double num = RFLOAT_VALUE(x);
1111     double den = RFLOAT_VALUE(y);
1112     double ret = double_div_double(num, den);
1113     return DBL2NUM(ret);
1114 }
1115 
1116 /*
1117  * call-seq:
1118  *   float / other  ->  float
1119  *
1120  * Returns a new Float which is the result of dividing +float+ by +other+.
1121  */
1122 
1123 VALUE
rb_float_div(VALUE x,VALUE y)1124 rb_float_div(VALUE x, VALUE y)
1125 {
1126     double num = RFLOAT_VALUE(x);
1127     double den;
1128     double ret;
1129 
1130     if (RB_TYPE_P(y, T_FIXNUM)) {
1131         den = FIX2LONG(y);
1132     }
1133     else if (RB_TYPE_P(y, T_BIGNUM)) {
1134         den = rb_big2dbl(y);
1135     }
1136     else if (RB_TYPE_P(y, T_FLOAT)) {
1137         den = RFLOAT_VALUE(y);
1138     }
1139     else {
1140 	return rb_num_coerce_bin(x, y, '/');
1141     }
1142 
1143     ret = double_div_double(num, den);
1144     return DBL2NUM(ret);
1145 }
1146 
1147 /*
1148  *  call-seq:
1149  *     float.fdiv(numeric)  ->  float
1150  *     float.quo(numeric)   ->  float
1151  *
1152  *  Returns <code>float / numeric</code>, same as Float#/.
1153  */
1154 
1155 static VALUE
flo_quo(VALUE x,VALUE y)1156 flo_quo(VALUE x, VALUE y)
1157 {
1158     return num_funcall1(x, '/', y);
1159 }
1160 
1161 static void
flodivmod(double x,double y,double * divp,double * modp)1162 flodivmod(double x, double y, double *divp, double *modp)
1163 {
1164     double div, mod;
1165 
1166     if (isnan(y)) {
1167 	/* y is NaN so all results are NaN */
1168 	if (modp) *modp = y;
1169 	if (divp) *divp = y;
1170 	return;
1171     }
1172     if (y == 0.0) rb_num_zerodiv();
1173     if ((x == 0.0) || (isinf(y) && !isinf(x)))
1174         mod = x;
1175     else {
1176 #ifdef HAVE_FMOD
1177 	mod = fmod(x, y);
1178 #else
1179 	double z;
1180 
1181 	modf(x/y, &z);
1182 	mod = x - z * y;
1183 #endif
1184     }
1185     if (isinf(x) && !isinf(y))
1186 	div = x;
1187     else {
1188 	div = (x - mod) / y;
1189 	if (modp && divp) div = round(div);
1190     }
1191     if (y*mod < 0) {
1192 	mod += y;
1193 	div -= 1.0;
1194     }
1195     if (modp) *modp = mod;
1196     if (divp) *divp = div;
1197 }
1198 
1199 /*
1200  * Returns the modulo of division of x by y.
1201  * An error will be raised if y == 0.
1202  */
1203 
1204 MJIT_FUNC_EXPORTED double
ruby_float_mod(double x,double y)1205 ruby_float_mod(double x, double y)
1206 {
1207     double mod;
1208     flodivmod(x, y, 0, &mod);
1209     return mod;
1210 }
1211 
1212 /*
1213  *  call-seq:
1214  *     float % other        ->  float
1215  *     float.modulo(other)  ->  float
1216  *
1217  *  Returns the modulo after division of +float+ by +other+.
1218  *
1219  *     6543.21.modulo(137)      #=> 104.21000000000004
1220  *     6543.21.modulo(137.24)   #=> 92.92999999999961
1221  */
1222 
1223 static VALUE
flo_mod(VALUE x,VALUE y)1224 flo_mod(VALUE x, VALUE y)
1225 {
1226     double fy;
1227 
1228     if (RB_TYPE_P(y, T_FIXNUM)) {
1229 	fy = (double)FIX2LONG(y);
1230     }
1231     else if (RB_TYPE_P(y, T_BIGNUM)) {
1232 	fy = rb_big2dbl(y);
1233     }
1234     else if (RB_TYPE_P(y, T_FLOAT)) {
1235 	fy = RFLOAT_VALUE(y);
1236     }
1237     else {
1238 	return rb_num_coerce_bin(x, y, '%');
1239     }
1240     return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1241 }
1242 
1243 static VALUE
dbl2ival(double d)1244 dbl2ival(double d)
1245 {
1246     if (FIXABLE(d)) {
1247 	return LONG2FIX((long)d);
1248     }
1249     return rb_dbl2big(d);
1250 }
1251 
1252 /*
1253  *  call-seq:
1254  *     float.divmod(numeric)  ->  array
1255  *
1256  *  See Numeric#divmod.
1257  *
1258  *     42.0.divmod(6)   #=> [7, 0.0]
1259  *     42.0.divmod(5)   #=> [8, 2.0]
1260  */
1261 
1262 static VALUE
flo_divmod(VALUE x,VALUE y)1263 flo_divmod(VALUE x, VALUE y)
1264 {
1265     double fy, div, mod;
1266     volatile VALUE a, b;
1267 
1268     if (RB_TYPE_P(y, T_FIXNUM)) {
1269 	fy = (double)FIX2LONG(y);
1270     }
1271     else if (RB_TYPE_P(y, T_BIGNUM)) {
1272 	fy = rb_big2dbl(y);
1273     }
1274     else if (RB_TYPE_P(y, T_FLOAT)) {
1275 	fy = RFLOAT_VALUE(y);
1276     }
1277     else {
1278 	return rb_num_coerce_bin(x, y, id_divmod);
1279     }
1280     flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1281     a = dbl2ival(div);
1282     b = DBL2NUM(mod);
1283     return rb_assoc_new(a, b);
1284 }
1285 
1286 /*
1287  * call-seq:
1288  *    float ** other  ->  float
1289  *
1290  * Raises +float+ to the power of +other+.
1291  *
1292  *    2.0**3   #=> 8.0
1293  */
1294 
1295 VALUE
rb_float_pow(VALUE x,VALUE y)1296 rb_float_pow(VALUE x, VALUE y)
1297 {
1298     double dx, dy;
1299     if (RB_TYPE_P(y, T_FIXNUM)) {
1300 	dx = RFLOAT_VALUE(x);
1301 	dy = (double)FIX2LONG(y);
1302     }
1303     else if (RB_TYPE_P(y, T_BIGNUM)) {
1304 	dx = RFLOAT_VALUE(x);
1305 	dy = rb_big2dbl(y);
1306     }
1307     else if (RB_TYPE_P(y, T_FLOAT)) {
1308 	dx = RFLOAT_VALUE(x);
1309 	dy = RFLOAT_VALUE(y);
1310 	if (dx < 0 && dy != round(dy))
1311             return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1312     }
1313     else {
1314 	return rb_num_coerce_bin(x, y, idPow);
1315     }
1316     return DBL2NUM(pow(dx, dy));
1317 }
1318 
1319 /*
1320  *  call-seq:
1321  *     num.eql?(numeric)  ->  true or false
1322  *
1323  *  Returns +true+ if +num+ and +numeric+ are the same type and have equal
1324  *  values.  Contrast this with Numeric#==, which performs type conversions.
1325  *
1326  *     1 == 1.0        #=> true
1327  *     1.eql?(1.0)     #=> false
1328  *     1.0.eql?(1.0)   #=> true
1329  */
1330 
1331 static VALUE
num_eql(VALUE x,VALUE y)1332 num_eql(VALUE x, VALUE y)
1333 {
1334     if (TYPE(x) != TYPE(y)) return Qfalse;
1335 
1336     if (RB_TYPE_P(x, T_BIGNUM)) {
1337 	return rb_big_eql(x, y);
1338     }
1339 
1340     return rb_equal(x, y);
1341 }
1342 
1343 /*
1344  *  call-seq:
1345  *     number <=> other  ->  0 or nil
1346  *
1347  *  Returns zero if +number+ equals +other+, otherwise returns +nil+.
1348  */
1349 
1350 static VALUE
num_cmp(VALUE x,VALUE y)1351 num_cmp(VALUE x, VALUE y)
1352 {
1353     if (x == y) return INT2FIX(0);
1354     return Qnil;
1355 }
1356 
1357 static VALUE
num_equal(VALUE x,VALUE y)1358 num_equal(VALUE x, VALUE y)
1359 {
1360     VALUE result;
1361     if (x == y) return Qtrue;
1362     result = num_funcall1(y, id_eq, x);
1363     if (RTEST(result)) return Qtrue;
1364     return Qfalse;
1365 }
1366 
1367 /*
1368  *  call-seq:
1369  *     float == obj  ->  true or false
1370  *
1371  *  Returns +true+ only if +obj+ has the same value as +float+.
1372  *  Contrast this with Float#eql?, which requires +obj+ to be a Float.
1373  *
1374  *     1.0 == 1   #=> true
1375  *
1376  *  The result of <code>NaN == NaN</code> is undefined,
1377  *  so an implementation-dependent value is returned.
1378  */
1379 
1380 MJIT_FUNC_EXPORTED VALUE
rb_float_equal(VALUE x,VALUE y)1381 rb_float_equal(VALUE x, VALUE y)
1382 {
1383     volatile double a, b;
1384 
1385     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1386         return rb_integer_float_eq(y, x);
1387     }
1388     else if (RB_TYPE_P(y, T_FLOAT)) {
1389 	b = RFLOAT_VALUE(y);
1390 #if defined(_MSC_VER) && _MSC_VER < 1300
1391 	if (isnan(b)) return Qfalse;
1392 #endif
1393     }
1394     else {
1395 	return num_equal(x, y);
1396     }
1397     a = RFLOAT_VALUE(x);
1398 #if defined(_MSC_VER) && _MSC_VER < 1300
1399     if (isnan(a)) return Qfalse;
1400 #endif
1401     return (a == b)?Qtrue:Qfalse;
1402 }
1403 
1404 #define flo_eq rb_float_equal
1405 
1406 /*
1407  * call-seq:
1408  *    float.hash  ->  integer
1409  *
1410  * Returns a hash code for this float.
1411  *
1412  * See also Object#hash.
1413  */
1414 
1415 static VALUE
flo_hash(VALUE num)1416 flo_hash(VALUE num)
1417 {
1418     return rb_dbl_hash(RFLOAT_VALUE(num));
1419 }
1420 
1421 VALUE
rb_dbl_hash(double d)1422 rb_dbl_hash(double d)
1423 {
1424     return LONG2FIX(rb_dbl_long_hash(d));
1425 }
1426 
1427 VALUE
rb_dbl_cmp(double a,double b)1428 rb_dbl_cmp(double a, double b)
1429 {
1430     if (isnan(a) || isnan(b)) return Qnil;
1431     if (a == b) return INT2FIX(0);
1432     if (a > b) return INT2FIX(1);
1433     if (a < b) return INT2FIX(-1);
1434     return Qnil;
1435 }
1436 
1437 /*
1438  *  call-seq:
1439  *     float <=> real  ->  -1, 0, +1, or nil
1440  *
1441  *  Returns -1, 0, or +1 depending on whether +float+ is
1442  *  less than, equal to, or greater than +real+.
1443  *  This is the basis for the tests in the Comparable module.
1444  *
1445  *  The result of <code>NaN <=> NaN</code> is undefined,
1446  *  so an implementation-dependent value is returned.
1447  *
1448  *  +nil+ is returned if the two values are incomparable.
1449  */
1450 
1451 static VALUE
flo_cmp(VALUE x,VALUE y)1452 flo_cmp(VALUE x, VALUE y)
1453 {
1454     double a, b;
1455     VALUE i;
1456 
1457     a = RFLOAT_VALUE(x);
1458     if (isnan(a)) return Qnil;
1459     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1460         VALUE rel = rb_integer_float_cmp(y, x);
1461         if (FIXNUM_P(rel))
1462             return INT2FIX(-FIX2INT(rel));
1463         return rel;
1464     }
1465     else if (RB_TYPE_P(y, T_FLOAT)) {
1466 	b = RFLOAT_VALUE(y);
1467     }
1468     else {
1469 	if (isinf(a) && (i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0)) != Qundef) {
1470 	    if (RTEST(i)) {
1471 		int j = rb_cmpint(i, x, y);
1472 		j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1473 		return INT2FIX(j);
1474 	    }
1475 	    if (a > 0.0) return INT2FIX(1);
1476 	    return INT2FIX(-1);
1477 	}
1478 	return rb_num_coerce_cmp(x, y, id_cmp);
1479     }
1480     return rb_dbl_cmp(a, b);
1481 }
1482 
1483 MJIT_FUNC_EXPORTED int
rb_float_cmp(VALUE x,VALUE y)1484 rb_float_cmp(VALUE x, VALUE y)
1485 {
1486     return NUM2INT(flo_cmp(x, y));
1487 }
1488 
1489 /*
1490  * call-seq:
1491  *   float > real  ->  true or false
1492  *
1493  * Returns +true+ if +float+ is greater than +real+.
1494  *
1495  * The result of <code>NaN > NaN</code> is undefined,
1496  * so an implementation-dependent value is returned.
1497  */
1498 
1499 VALUE
rb_float_gt(VALUE x,VALUE y)1500 rb_float_gt(VALUE x, VALUE y)
1501 {
1502     double a, b;
1503 
1504     a = RFLOAT_VALUE(x);
1505     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1506         VALUE rel = rb_integer_float_cmp(y, x);
1507         if (FIXNUM_P(rel))
1508             return -FIX2INT(rel) > 0 ? Qtrue : Qfalse;
1509         return Qfalse;
1510     }
1511     else if (RB_TYPE_P(y, T_FLOAT)) {
1512 	b = RFLOAT_VALUE(y);
1513 #if defined(_MSC_VER) && _MSC_VER < 1300
1514 	if (isnan(b)) return Qfalse;
1515 #endif
1516     }
1517     else {
1518 	return rb_num_coerce_relop(x, y, '>');
1519     }
1520 #if defined(_MSC_VER) && _MSC_VER < 1300
1521     if (isnan(a)) return Qfalse;
1522 #endif
1523     return (a > b)?Qtrue:Qfalse;
1524 }
1525 
1526 /*
1527  * call-seq:
1528  *   float >= real  ->  true or false
1529  *
1530  * Returns +true+ if +float+ is greater than or equal to +real+.
1531  *
1532  * The result of <code>NaN >= NaN</code> is undefined,
1533  * so an implementation-dependent value is returned.
1534  */
1535 
1536 static VALUE
flo_ge(VALUE x,VALUE y)1537 flo_ge(VALUE x, VALUE y)
1538 {
1539     double a, b;
1540 
1541     a = RFLOAT_VALUE(x);
1542     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1543         VALUE rel = rb_integer_float_cmp(y, x);
1544         if (FIXNUM_P(rel))
1545             return -FIX2INT(rel) >= 0 ? Qtrue : Qfalse;
1546         return Qfalse;
1547     }
1548     else if (RB_TYPE_P(y, T_FLOAT)) {
1549 	b = RFLOAT_VALUE(y);
1550 #if defined(_MSC_VER) && _MSC_VER < 1300
1551 	if (isnan(b)) return Qfalse;
1552 #endif
1553     }
1554     else {
1555 	return rb_num_coerce_relop(x, y, idGE);
1556     }
1557 #if defined(_MSC_VER) && _MSC_VER < 1300
1558     if (isnan(a)) return Qfalse;
1559 #endif
1560     return (a >= b)?Qtrue:Qfalse;
1561 }
1562 
1563 /*
1564  * call-seq:
1565  *   float < real  ->  true or false
1566  *
1567  * Returns +true+ if +float+ is less than +real+.
1568  *
1569  * The result of <code>NaN < NaN</code> is undefined,
1570  * so an implementation-dependent value is returned.
1571  */
1572 
1573 static VALUE
flo_lt(VALUE x,VALUE y)1574 flo_lt(VALUE x, VALUE y)
1575 {
1576     double a, b;
1577 
1578     a = RFLOAT_VALUE(x);
1579     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1580         VALUE rel = rb_integer_float_cmp(y, x);
1581         if (FIXNUM_P(rel))
1582             return -FIX2INT(rel) < 0 ? Qtrue : Qfalse;
1583         return Qfalse;
1584     }
1585     else if (RB_TYPE_P(y, T_FLOAT)) {
1586 	b = RFLOAT_VALUE(y);
1587 #if defined(_MSC_VER) && _MSC_VER < 1300
1588 	if (isnan(b)) return Qfalse;
1589 #endif
1590     }
1591     else {
1592 	return rb_num_coerce_relop(x, y, '<');
1593     }
1594 #if defined(_MSC_VER) && _MSC_VER < 1300
1595     if (isnan(a)) return Qfalse;
1596 #endif
1597     return (a < b)?Qtrue:Qfalse;
1598 }
1599 
1600 /*
1601  * call-seq:
1602  *   float <= real  ->  true or false
1603  *
1604  * Returns +true+ if +float+ is less than or equal to +real+.
1605  *
1606  * The result of <code>NaN <= NaN</code> is undefined,
1607  * so an implementation-dependent value is returned.
1608  */
1609 
1610 static VALUE
flo_le(VALUE x,VALUE y)1611 flo_le(VALUE x, VALUE y)
1612 {
1613     double a, b;
1614 
1615     a = RFLOAT_VALUE(x);
1616     if (RB_TYPE_P(y, T_FIXNUM) || RB_TYPE_P(y, T_BIGNUM)) {
1617         VALUE rel = rb_integer_float_cmp(y, x);
1618         if (FIXNUM_P(rel))
1619             return -FIX2INT(rel) <= 0 ? Qtrue : Qfalse;
1620         return Qfalse;
1621     }
1622     else if (RB_TYPE_P(y, T_FLOAT)) {
1623 	b = RFLOAT_VALUE(y);
1624 #if defined(_MSC_VER) && _MSC_VER < 1300
1625 	if (isnan(b)) return Qfalse;
1626 #endif
1627     }
1628     else {
1629 	return rb_num_coerce_relop(x, y, idLE);
1630     }
1631 #if defined(_MSC_VER) && _MSC_VER < 1300
1632     if (isnan(a)) return Qfalse;
1633 #endif
1634     return (a <= b)?Qtrue:Qfalse;
1635 }
1636 
1637 /*
1638  *  call-seq:
1639  *     float.eql?(obj)  ->  true or false
1640  *
1641  *  Returns +true+ only if +obj+ is a Float with the same value as +float+.
1642  *  Contrast this with Float#==, which performs type conversions.
1643  *
1644  *     1.0.eql?(1)   #=> false
1645  *
1646  *  The result of <code>NaN.eql?(NaN)</code> is undefined,
1647  *  so an implementation-dependent value is returned.
1648  */
1649 
1650 MJIT_FUNC_EXPORTED VALUE
rb_float_eql(VALUE x,VALUE y)1651 rb_float_eql(VALUE x, VALUE y)
1652 {
1653     if (RB_TYPE_P(y, T_FLOAT)) {
1654 	double a = RFLOAT_VALUE(x);
1655 	double b = RFLOAT_VALUE(y);
1656 #if defined(_MSC_VER) && _MSC_VER < 1300
1657 	if (isnan(a) || isnan(b)) return Qfalse;
1658 #endif
1659 	if (a == b)
1660 	    return Qtrue;
1661     }
1662     return Qfalse;
1663 }
1664 
1665 #define flo_eql rb_float_eql
1666 
1667 /*
1668  * call-seq:
1669  *    float.to_f  ->  self
1670  *
1671  * Since +float+ is already a Float, returns +self+.
1672  */
1673 
1674 static VALUE
flo_to_f(VALUE num)1675 flo_to_f(VALUE num)
1676 {
1677     return num;
1678 }
1679 
1680 /*
1681  *  call-seq:
1682  *     float.abs        ->  float
1683  *     float.magnitude  ->  float
1684  *
1685  *  Returns the absolute value of +float+.
1686  *
1687  *     (-34.56).abs   #=> 34.56
1688  *     -34.56.abs     #=> 34.56
1689  *     34.56.abs      #=> 34.56
1690  *
1691  *  Float#magnitude is an alias for Float#abs.
1692  */
1693 
1694 VALUE
rb_float_abs(VALUE flt)1695 rb_float_abs(VALUE flt)
1696 {
1697     double val = fabs(RFLOAT_VALUE(flt));
1698     return DBL2NUM(val);
1699 }
1700 
1701 /*
1702  *  call-seq:
1703  *     float.zero?  ->  true or false
1704  *
1705  *  Returns +true+ if +float+ is 0.0.
1706  */
1707 
1708 static VALUE
flo_zero_p(VALUE num)1709 flo_zero_p(VALUE num)
1710 {
1711     return flo_iszero(num) ? Qtrue : Qfalse;
1712 }
1713 
1714 /*
1715  *  call-seq:
1716  *     float.nan?  ->  true or false
1717  *
1718  *  Returns +true+ if +float+ is an invalid IEEE floating point number.
1719  *
1720  *     a = -1.0      #=> -1.0
1721  *     a.nan?        #=> false
1722  *     a = 0.0/0.0   #=> NaN
1723  *     a.nan?        #=> true
1724  */
1725 
1726 static VALUE
flo_is_nan_p(VALUE num)1727 flo_is_nan_p(VALUE num)
1728 {
1729     double value = RFLOAT_VALUE(num);
1730 
1731     return isnan(value) ? Qtrue : Qfalse;
1732 }
1733 
1734 /*
1735  *  call-seq:
1736  *     float.infinite?  ->  -1, 1, or nil
1737  *
1738  *  Returns +nil+, -1, or 1 depending on whether the value is
1739  *  finite, <code>-Infinity</code>, or <code>+Infinity</code>.
1740  *
1741  *     (0.0).infinite?        #=> nil
1742  *     (-1.0/0.0).infinite?   #=> -1
1743  *     (+1.0/0.0).infinite?   #=> 1
1744  */
1745 
1746 VALUE
rb_flo_is_infinite_p(VALUE num)1747 rb_flo_is_infinite_p(VALUE num)
1748 {
1749     double value = RFLOAT_VALUE(num);
1750 
1751     if (isinf(value)) {
1752 	return INT2FIX( value < 0 ? -1 : 1 );
1753     }
1754 
1755     return Qnil;
1756 }
1757 
1758 /*
1759  *  call-seq:
1760  *     float.finite?  ->  true or false
1761  *
1762  *  Returns +true+ if +float+ is a valid IEEE floating point number,
1763  *  i.e. it is not infinite and Float#nan? is +false+.
1764  */
1765 
1766 VALUE
rb_flo_is_finite_p(VALUE num)1767 rb_flo_is_finite_p(VALUE num)
1768 {
1769     double value = RFLOAT_VALUE(num);
1770 
1771 #ifdef HAVE_ISFINITE
1772     if (!isfinite(value))
1773 	return Qfalse;
1774 #else
1775     if (isinf(value) || isnan(value))
1776 	return Qfalse;
1777 #endif
1778 
1779     return Qtrue;
1780 }
1781 
1782 /*
1783  *  call-seq:
1784  *     float.next_float  ->  float
1785  *
1786  *  Returns the next representable floating point number.
1787  *
1788  *  Float::MAX.next_float and Float::INFINITY.next_float is Float::INFINITY.
1789  *
1790  *  Float::NAN.next_float is Float::NAN.
1791  *
1792  *  For example:
1793  *
1794  *    0.01.next_float    #=> 0.010000000000000002
1795  *    1.0.next_float     #=> 1.0000000000000002
1796  *    100.0.next_float   #=> 100.00000000000001
1797  *
1798  *    0.01.next_float - 0.01     #=> 1.734723475976807e-18
1799  *    1.0.next_float - 1.0       #=> 2.220446049250313e-16
1800  *    100.0.next_float - 100.0   #=> 1.4210854715202004e-14
1801  *
1802  *    f = 0.01; 20.times { printf "%-20a %s\n", f, f.to_s; f = f.next_float }
1803  *    #=> 0x1.47ae147ae147bp-7 0.01
1804  *    #   0x1.47ae147ae147cp-7 0.010000000000000002
1805  *    #   0x1.47ae147ae147dp-7 0.010000000000000004
1806  *    #   0x1.47ae147ae147ep-7 0.010000000000000005
1807  *    #   0x1.47ae147ae147fp-7 0.010000000000000007
1808  *    #   0x1.47ae147ae148p-7  0.010000000000000009
1809  *    #   0x1.47ae147ae1481p-7 0.01000000000000001
1810  *    #   0x1.47ae147ae1482p-7 0.010000000000000012
1811  *    #   0x1.47ae147ae1483p-7 0.010000000000000014
1812  *    #   0x1.47ae147ae1484p-7 0.010000000000000016
1813  *    #   0x1.47ae147ae1485p-7 0.010000000000000018
1814  *    #   0x1.47ae147ae1486p-7 0.01000000000000002
1815  *    #   0x1.47ae147ae1487p-7 0.010000000000000021
1816  *    #   0x1.47ae147ae1488p-7 0.010000000000000023
1817  *    #   0x1.47ae147ae1489p-7 0.010000000000000024
1818  *    #   0x1.47ae147ae148ap-7 0.010000000000000026
1819  *    #   0x1.47ae147ae148bp-7 0.010000000000000028
1820  *    #   0x1.47ae147ae148cp-7 0.01000000000000003
1821  *    #   0x1.47ae147ae148dp-7 0.010000000000000031
1822  *    #   0x1.47ae147ae148ep-7 0.010000000000000033
1823  *
1824  *    f = 0.0
1825  *    100.times { f += 0.1 }
1826  *    f                           #=> 9.99999999999998       # should be 10.0 in the ideal world.
1827  *    10-f                        #=> 1.9539925233402755e-14 # the floating point error.
1828  *    10.0.next_float-10          #=> 1.7763568394002505e-15 # 1 ulp (unit in the last place).
1829  *    (10-f)/(10.0.next_float-10) #=> 11.0                   # the error is 11 ulp.
1830  *    (10-f)/(10*Float::EPSILON)  #=> 8.8                    # approximation of the above.
1831  *    "%a" % 10                   #=> "0x1.4p+3"
1832  *    "%a" % f                    #=> "0x1.3fffffffffff5p+3" # the last hex digit is 5.  16 - 5 = 11 ulp.
1833  */
1834 static VALUE
flo_next_float(VALUE vx)1835 flo_next_float(VALUE vx)
1836 {
1837     double x, y;
1838     x = NUM2DBL(vx);
1839     y = nextafter(x, HUGE_VAL);
1840     return DBL2NUM(y);
1841 }
1842 
1843 /*
1844  *  call-seq:
1845  *     float.prev_float  ->  float
1846  *
1847  *  Returns the previous representable floating point number.
1848  *
1849  *  (-Float::MAX).prev_float and (-Float::INFINITY).prev_float is -Float::INFINITY.
1850  *
1851  *  Float::NAN.prev_float is Float::NAN.
1852  *
1853  *  For example:
1854  *
1855  *    0.01.prev_float    #=> 0.009999999999999998
1856  *    1.0.prev_float     #=> 0.9999999999999999
1857  *    100.0.prev_float   #=> 99.99999999999999
1858  *
1859  *    0.01 - 0.01.prev_float     #=> 1.734723475976807e-18
1860  *    1.0 - 1.0.prev_float       #=> 1.1102230246251565e-16
1861  *    100.0 - 100.0.prev_float   #=> 1.4210854715202004e-14
1862  *
1863  *    f = 0.01; 20.times { printf "%-20a %s\n", f, f.to_s; f = f.prev_float }
1864  *    #=> 0x1.47ae147ae147bp-7 0.01
1865  *    #   0x1.47ae147ae147ap-7 0.009999999999999998
1866  *    #   0x1.47ae147ae1479p-7 0.009999999999999997
1867  *    #   0x1.47ae147ae1478p-7 0.009999999999999995
1868  *    #   0x1.47ae147ae1477p-7 0.009999999999999993
1869  *    #   0x1.47ae147ae1476p-7 0.009999999999999992
1870  *    #   0x1.47ae147ae1475p-7 0.00999999999999999
1871  *    #   0x1.47ae147ae1474p-7 0.009999999999999988
1872  *    #   0x1.47ae147ae1473p-7 0.009999999999999986
1873  *    #   0x1.47ae147ae1472p-7 0.009999999999999985
1874  *    #   0x1.47ae147ae1471p-7 0.009999999999999983
1875  *    #   0x1.47ae147ae147p-7  0.009999999999999981
1876  *    #   0x1.47ae147ae146fp-7 0.00999999999999998
1877  *    #   0x1.47ae147ae146ep-7 0.009999999999999978
1878  *    #   0x1.47ae147ae146dp-7 0.009999999999999976
1879  *    #   0x1.47ae147ae146cp-7 0.009999999999999974
1880  *    #   0x1.47ae147ae146bp-7 0.009999999999999972
1881  *    #   0x1.47ae147ae146ap-7 0.00999999999999997
1882  *    #   0x1.47ae147ae1469p-7 0.009999999999999969
1883  *    #   0x1.47ae147ae1468p-7 0.009999999999999967
1884  */
1885 static VALUE
flo_prev_float(VALUE vx)1886 flo_prev_float(VALUE vx)
1887 {
1888     double x, y;
1889     x = NUM2DBL(vx);
1890     y = nextafter(x, -HUGE_VAL);
1891     return DBL2NUM(y);
1892 }
1893 
1894 VALUE
rb_float_floor(VALUE num,int ndigits)1895 rb_float_floor(VALUE num, int ndigits)
1896 {
1897     double number, f;
1898     number = RFLOAT_VALUE(num);
1899     if (number == 0.0) {
1900 	return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
1901     }
1902     if (ndigits > 0) {
1903 	int binexp;
1904 	frexp(number, &binexp);
1905 	if (float_round_overflow(ndigits, binexp)) return num;
1906 	if (number > 0.0 && float_round_underflow(ndigits, binexp))
1907 	    return DBL2NUM(0.0);
1908 	f = pow(10, ndigits);
1909 	f = floor(number * f) / f;
1910 	return DBL2NUM(f);
1911     }
1912     else {
1913 	num = dbl2ival(floor(number));
1914 	if (ndigits < 0) num = rb_int_floor(num, ndigits);
1915 	return num;
1916     }
1917 }
1918 
1919 /*
1920  *  call-seq:
1921  *     float.floor([ndigits])  ->  integer or float
1922  *
1923  *  Returns the largest number less than or equal to +float+ with
1924  *  a precision of +ndigits+ decimal digits (default: 0).
1925  *
1926  *  When the precision is negative, the returned value is an integer
1927  *  with at least <code>ndigits.abs</code> trailing zeros.
1928  *
1929  *  Returns a floating point number when +ndigits+ is positive,
1930  *  otherwise returns an integer.
1931  *
1932  *     1.2.floor      #=> 1
1933  *     2.0.floor      #=> 2
1934  *     (-1.2).floor   #=> -2
1935  *     (-2.0).floor   #=> -2
1936  *
1937  *     1.234567.floor(2)   #=> 1.23
1938  *     1.234567.floor(3)   #=> 1.234
1939  *     1.234567.floor(4)   #=> 1.2345
1940  *     1.234567.floor(5)   #=> 1.23456
1941  *
1942  *     34567.89.floor(-5)  #=> 0
1943  *     34567.89.floor(-4)  #=> 30000
1944  *     34567.89.floor(-3)  #=> 34000
1945  *     34567.89.floor(-2)  #=> 34500
1946  *     34567.89.floor(-1)  #=> 34560
1947  *     34567.89.floor(0)   #=> 34567
1948  *     34567.89.floor(1)   #=> 34567.8
1949  *     34567.89.floor(2)   #=> 34567.89
1950  *     34567.89.floor(3)   #=> 34567.89
1951  *
1952  *  Note that the limited precision of floating point arithmetic
1953  *  might lead to surprising results:
1954  *
1955  *     (0.3 / 0.1).floor  #=> 2 (!)
1956  */
1957 
1958 static VALUE
flo_floor(int argc,VALUE * argv,VALUE num)1959 flo_floor(int argc, VALUE *argv, VALUE num)
1960 {
1961     int ndigits = 0;
1962     if (rb_check_arity(argc, 0, 1)) {
1963 	ndigits = NUM2INT(argv[0]);
1964     }
1965     return rb_float_floor(num, ndigits);
1966 }
1967 
1968 /*
1969  *  call-seq:
1970  *     float.ceil([ndigits])  ->  integer or float
1971  *
1972  *  Returns the smallest number greater than or equal to +float+ with
1973  *  a precision of +ndigits+ decimal digits (default: 0).
1974  *
1975  *  When the precision is negative, the returned value is an integer
1976  *  with at least <code>ndigits.abs</code> trailing zeros.
1977  *
1978  *  Returns a floating point number when +ndigits+ is positive,
1979  *  otherwise returns an integer.
1980  *
1981  *     1.2.ceil      #=> 2
1982  *     2.0.ceil      #=> 2
1983  *     (-1.2).ceil   #=> -1
1984  *     (-2.0).ceil   #=> -2
1985  *
1986  *     1.234567.ceil(2)   #=> 1.24
1987  *     1.234567.ceil(3)   #=> 1.235
1988  *     1.234567.ceil(4)   #=> 1.2346
1989  *     1.234567.ceil(5)   #=> 1.23457
1990  *
1991  *     34567.89.ceil(-5)  #=> 100000
1992  *     34567.89.ceil(-4)  #=> 40000
1993  *     34567.89.ceil(-3)  #=> 35000
1994  *     34567.89.ceil(-2)  #=> 34600
1995  *     34567.89.ceil(-1)  #=> 34570
1996  *     34567.89.ceil(0)   #=> 34568
1997  *     34567.89.ceil(1)   #=> 34567.9
1998  *     34567.89.ceil(2)   #=> 34567.89
1999  *     34567.89.ceil(3)   #=> 34567.89
2000  *
2001  *  Note that the limited precision of floating point arithmetic
2002  *  might lead to surprising results:
2003  *
2004  *     (2.1 / 0.7).ceil  #=> 4 (!)
2005  */
2006 
2007 static VALUE
flo_ceil(int argc,VALUE * argv,VALUE num)2008 flo_ceil(int argc, VALUE *argv, VALUE num)
2009 {
2010     double number, f;
2011     int ndigits = 0;
2012 
2013     if (rb_check_arity(argc, 0, 1)) {
2014 	ndigits = NUM2INT(argv[0]);
2015     }
2016     number = RFLOAT_VALUE(num);
2017     if (number == 0.0) {
2018 	return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2019     }
2020     if (ndigits > 0) {
2021 	int binexp;
2022 	frexp(number, &binexp);
2023 	if (float_round_overflow(ndigits, binexp)) return num;
2024 	if (number < 0.0 && float_round_underflow(ndigits, binexp))
2025 	    return DBL2NUM(0.0);
2026 	f = pow(10, ndigits);
2027 	f = ceil(number * f) / f;
2028 	return DBL2NUM(f);
2029     }
2030     else {
2031 	num = dbl2ival(ceil(number));
2032 	if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2033 	return num;
2034     }
2035 }
2036 
2037 static int
int_round_zero_p(VALUE num,int ndigits)2038 int_round_zero_p(VALUE num, int ndigits)
2039 {
2040     long bytes;
2041     /* If 10**N / 2 > num, then return 0 */
2042     /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2043     if (FIXNUM_P(num)) {
2044 	bytes = sizeof(long);
2045     }
2046     else if (RB_TYPE_P(num, T_BIGNUM)) {
2047 	bytes = rb_big_size(num);
2048     }
2049     else {
2050 	bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2051     }
2052     return (-0.415241 * ndigits - 0.125 > bytes);
2053 }
2054 
2055 static SIGNED_VALUE
int_round_half_even(SIGNED_VALUE x,SIGNED_VALUE y)2056 int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2057 {
2058     SIGNED_VALUE z = +(x + y / 2) / y;
2059     if ((z * y - x) * 2 == y) {
2060 	z &= ~1;
2061     }
2062     return z * y;
2063 }
2064 
2065 static SIGNED_VALUE
int_round_half_up(SIGNED_VALUE x,SIGNED_VALUE y)2066 int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2067 {
2068     return (x + y / 2) / y * y;
2069 }
2070 
2071 static SIGNED_VALUE
int_round_half_down(SIGNED_VALUE x,SIGNED_VALUE y)2072 int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2073 {
2074     return (x + y / 2 - 1) / y * y;
2075 }
2076 
2077 static int
int_half_p_half_even(VALUE num,VALUE n,VALUE f)2078 int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2079 {
2080     return (int)rb_int_odd_p(rb_int_idiv(n, f));
2081 }
2082 
2083 static int
int_half_p_half_up(VALUE num,VALUE n,VALUE f)2084 int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2085 {
2086     return int_pos_p(num);
2087 }
2088 
2089 static int
int_half_p_half_down(VALUE num,VALUE n,VALUE f)2090 int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2091 {
2092     return int_neg_p(num);
2093 }
2094 
2095 /*
2096  * Assumes num is an Integer, ndigits <= 0
2097  */
2098 VALUE
rb_int_round(VALUE num,int ndigits,enum ruby_num_rounding_mode mode)2099 rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2100 {
2101     VALUE n, f, h, r;
2102 
2103     if (int_round_zero_p(num, ndigits)) {
2104 	return INT2FIX(0);
2105     }
2106 
2107     f = int_pow(10, -ndigits);
2108     if (FIXNUM_P(num) && FIXNUM_P(f)) {
2109 	SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2110 	int neg = x < 0;
2111 	if (neg) x = -x;
2112 	x = ROUND_CALL(mode, int_round, (x, y));
2113 	if (neg) x = -x;
2114 	return LONG2NUM(x);
2115     }
2116     if (RB_TYPE_P(f, T_FLOAT)) {
2117 	/* then int_pow overflow */
2118 	return INT2FIX(0);
2119     }
2120     h = rb_int_idiv(f, INT2FIX(2));
2121     r = rb_int_modulo(num, f);
2122     n = rb_int_minus(num, r);
2123     r = rb_int_cmp(r, h);
2124     if (FIXNUM_POSITIVE_P(r) ||
2125 	(FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2126 	n = rb_int_plus(n, f);
2127     }
2128     return n;
2129 }
2130 
2131 VALUE
rb_int_floor(VALUE num,int ndigits)2132 rb_int_floor(VALUE num, int ndigits)
2133 {
2134     VALUE f;
2135 
2136     if (int_round_zero_p(num, ndigits))
2137 	return INT2FIX(0);
2138     f = int_pow(10, -ndigits);
2139     if (FIXNUM_P(num) && FIXNUM_P(f)) {
2140 	SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2141 	int neg = x < 0;
2142 	if (neg) x = -x + y - 1;
2143 	x = x / y * y;
2144 	if (neg) x = -x;
2145 	return LONG2NUM(x);
2146     }
2147     if (RB_TYPE_P(f, T_FLOAT)) {
2148 	/* then int_pow overflow */
2149 	return INT2FIX(0);
2150     }
2151     return rb_int_minus(num, rb_int_modulo(num, f));
2152 }
2153 
2154 VALUE
rb_int_ceil(VALUE num,int ndigits)2155 rb_int_ceil(VALUE num, int ndigits)
2156 {
2157     VALUE f;
2158 
2159     if (int_round_zero_p(num, ndigits))
2160 	return INT2FIX(0);
2161     f = int_pow(10, -ndigits);
2162     if (FIXNUM_P(num) && FIXNUM_P(f)) {
2163 	SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2164 	int neg = x < 0;
2165 	if (neg) x = -x;
2166 	else x += y - 1;
2167 	x = (x / y) * y;
2168 	if (neg) x = -x;
2169 	return LONG2NUM(x);
2170     }
2171     if (RB_TYPE_P(f, T_FLOAT)) {
2172 	/* then int_pow overflow */
2173 	return INT2FIX(0);
2174     }
2175     return rb_int_plus(num, rb_int_minus(f, rb_int_modulo(num, f)));
2176 }
2177 
2178 VALUE
rb_int_truncate(VALUE num,int ndigits)2179 rb_int_truncate(VALUE num, int ndigits)
2180 {
2181     VALUE f;
2182     VALUE m;
2183 
2184     if (int_round_zero_p(num, ndigits))
2185 	return INT2FIX(0);
2186     f = int_pow(10, -ndigits);
2187     if (FIXNUM_P(num) && FIXNUM_P(f)) {
2188 	SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2189 	int neg = x < 0;
2190 	if (neg) x = -x;
2191 	x = x / y * y;
2192 	if (neg) x = -x;
2193 	return LONG2NUM(x);
2194     }
2195     if (RB_TYPE_P(f, T_FLOAT)) {
2196 	/* then int_pow overflow */
2197 	return INT2FIX(0);
2198     }
2199     m = rb_int_modulo(num, f);
2200     if (int_neg_p(num)) {
2201 	return rb_int_plus(num, rb_int_minus(f, m));
2202     }
2203     else {
2204 	return rb_int_minus(num, m);
2205     }
2206 }
2207 
2208 /*
2209  *  call-seq:
2210  *     float.round([ndigits] [, half: mode])  ->  integer or float
2211  *
2212  *  Returns +float+ rounded to the nearest value with
2213  *  a precision of +ndigits+ decimal digits (default: 0).
2214  *
2215  *  When the precision is negative, the returned value is an integer
2216  *  with at least <code>ndigits.abs</code> trailing zeros.
2217  *
2218  *  Returns a floating point number when +ndigits+ is positive,
2219  *  otherwise returns an integer.
2220  *
2221  *     1.4.round      #=> 1
2222  *     1.5.round      #=> 2
2223  *     1.6.round      #=> 2
2224  *     (-1.5).round   #=> -2
2225  *
2226  *     1.234567.round(2)   #=> 1.23
2227  *     1.234567.round(3)   #=> 1.235
2228  *     1.234567.round(4)   #=> 1.2346
2229  *     1.234567.round(5)   #=> 1.23457
2230  *
2231  *     34567.89.round(-5)  #=> 0
2232  *     34567.89.round(-4)  #=> 30000
2233  *     34567.89.round(-3)  #=> 35000
2234  *     34567.89.round(-2)  #=> 34600
2235  *     34567.89.round(-1)  #=> 34570
2236  *     34567.89.round(0)   #=> 34568
2237  *     34567.89.round(1)   #=> 34567.9
2238  *     34567.89.round(2)   #=> 34567.89
2239  *     34567.89.round(3)   #=> 34567.89
2240  *
2241  *  If the optional +half+ keyword argument is given,
2242  *  numbers that are half-way between two possible rounded values
2243  *  will be rounded according to the specified tie-breaking +mode+:
2244  *
2245  *  * <code>:up</code> or +nil+: round half away from zero (default)
2246  *  * <code>:down</code>: round half toward zero
2247  *  * <code>:even</code>: round half toward the nearest even number
2248  *
2249  *     2.5.round(half: :up)      #=> 3
2250  *     2.5.round(half: :down)    #=> 2
2251  *     2.5.round(half: :even)    #=> 2
2252  *     3.5.round(half: :up)      #=> 4
2253  *     3.5.round(half: :down)    #=> 3
2254  *     3.5.round(half: :even)    #=> 4
2255  *     (-2.5).round(half: :up)   #=> -3
2256  *     (-2.5).round(half: :down) #=> -2
2257  *     (-2.5).round(half: :even) #=> -2
2258  */
2259 
2260 static VALUE
flo_round(int argc,VALUE * argv,VALUE num)2261 flo_round(int argc, VALUE *argv, VALUE num)
2262 {
2263     double number, f, x;
2264     VALUE nd, opt;
2265     int ndigits = 0;
2266     enum ruby_num_rounding_mode mode;
2267 
2268     if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2269 	ndigits = NUM2INT(nd);
2270     }
2271     mode = rb_num_get_rounding_option(opt);
2272     number = RFLOAT_VALUE(num);
2273     if (number == 0.0) {
2274 	return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2275     }
2276     if (ndigits < 0) {
2277 	return rb_int_round(flo_to_i(num), ndigits, mode);
2278     }
2279     if (ndigits == 0) {
2280 	x = ROUND_CALL(mode, round, (number, 1.0));
2281 	return dbl2ival(x);
2282     }
2283     if (isfinite(number)) {
2284 	int binexp;
2285 	frexp(number, &binexp);
2286 	if (float_round_overflow(ndigits, binexp)) return num;
2287 	if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2288 	f = pow(10, ndigits);
2289 	x = ROUND_CALL(mode, round, (number, f));
2290 	return DBL2NUM(x / f);
2291     }
2292     return num;
2293 }
2294 
2295 static int
float_round_overflow(int ndigits,int binexp)2296 float_round_overflow(int ndigits, int binexp)
2297 {
2298     enum {float_dig = DBL_DIG+2};
2299 
2300 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2301    i.e. such that  10 ** (exp - 1) <= |number| < 10 ** exp
2302    Recall that up to float_dig digits can be needed to represent a double,
2303    so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2304    will be an integer and thus the result is the original number.
2305    If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2306    if ndigits + exp < 0, the result is 0.
2307    We have:
2308 	2 ** (binexp-1) <= |number| < 2 ** binexp
2309 	10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2310 	If binexp >= 0, and since log_2(10) = 3.322259:
2311 	   10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2312 	   floor(binexp/4) <= exp <= ceil(binexp/3)
2313 	If binexp <= 0, swap the /4 and the /3
2314 	So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2315 	If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2316 */
2317     if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2318 	return TRUE;
2319     }
2320     return FALSE;
2321 }
2322 
2323 static int
float_round_underflow(int ndigits,int binexp)2324 float_round_underflow(int ndigits, int binexp)
2325 {
2326     if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2327 	return TRUE;
2328     }
2329     return FALSE;
2330 }
2331 
2332 /*
2333  *  call-seq:
2334  *     float.to_i    ->  integer
2335  *     float.to_int  ->  integer
2336  *
2337  *  Returns the +float+ truncated to an Integer.
2338  *
2339  *     1.2.to_i      #=> 1
2340  *     (-1.2).to_i   #=> -1
2341  *
2342  *  Note that the limited precision of floating point arithmetic
2343  *  might lead to surprising results:
2344  *
2345  *    (0.3 / 0.1).to_i  #=> 2 (!)
2346  *
2347  *  #to_int is an alias for #to_i.
2348  */
2349 
2350 static VALUE
flo_to_i(VALUE num)2351 flo_to_i(VALUE num)
2352 {
2353     double f = RFLOAT_VALUE(num);
2354 
2355     if (f > 0.0) f = floor(f);
2356     if (f < 0.0) f = ceil(f);
2357 
2358     return dbl2ival(f);
2359 }
2360 
2361 /*
2362  *  call-seq:
2363  *     float.truncate([ndigits])  ->  integer or float
2364  *
2365  *  Returns +float+ truncated (toward zero) to
2366  *  a precision of +ndigits+ decimal digits (default: 0).
2367  *
2368  *  When the precision is negative, the returned value is an integer
2369  *  with at least <code>ndigits.abs</code> trailing zeros.
2370  *
2371  *  Returns a floating point number when +ndigits+ is positive,
2372  *  otherwise returns an integer.
2373  *
2374  *     2.8.truncate           #=> 2
2375  *     (-2.8).truncate        #=> -2
2376  *     1.234567.truncate(2)   #=> 1.23
2377  *     34567.89.truncate(-2)  #=> 34500
2378  *
2379  *  Note that the limited precision of floating point arithmetic
2380  *  might lead to surprising results:
2381  *
2382  *     (0.3 / 0.1).truncate  #=> 2 (!)
2383  */
2384 static VALUE
flo_truncate(int argc,VALUE * argv,VALUE num)2385 flo_truncate(int argc, VALUE *argv, VALUE num)
2386 {
2387     if (signbit(RFLOAT_VALUE(num)))
2388 	return flo_ceil(argc, argv, num);
2389     else
2390 	return flo_floor(argc, argv, num);
2391 }
2392 
2393 /*
2394  *  call-seq:
2395  *     float.positive?  ->  true or false
2396  *
2397  *  Returns +true+ if +float+ is greater than 0.
2398  */
2399 
2400 static VALUE
flo_positive_p(VALUE num)2401 flo_positive_p(VALUE num)
2402 {
2403     double f = RFLOAT_VALUE(num);
2404     return f > 0.0 ? Qtrue : Qfalse;
2405 }
2406 
2407 /*
2408  *  call-seq:
2409  *     float.negative?  ->  true or false
2410  *
2411  *  Returns +true+ if +float+ is less than 0.
2412  */
2413 
2414 static VALUE
flo_negative_p(VALUE num)2415 flo_negative_p(VALUE num)
2416 {
2417     double f = RFLOAT_VALUE(num);
2418     return f < 0.0 ? Qtrue : Qfalse;
2419 }
2420 
2421 /*
2422  *  call-seq:
2423  *     num.floor([ndigits])  ->  integer or float
2424  *
2425  *  Returns the largest number less than or equal to +num+ with
2426  *  a precision of +ndigits+ decimal digits (default: 0).
2427  *
2428  *  Numeric implements this by converting its value to a Float and
2429  *  invoking Float#floor.
2430  */
2431 
2432 static VALUE
num_floor(int argc,VALUE * argv,VALUE num)2433 num_floor(int argc, VALUE *argv, VALUE num)
2434 {
2435     return flo_floor(argc, argv, rb_Float(num));
2436 }
2437 
2438 /*
2439  *  call-seq:
2440  *     num.ceil([ndigits])  ->  integer or float
2441  *
2442  *  Returns the smallest number greater than or equal to +num+ with
2443  *  a precision of +ndigits+ decimal digits (default: 0).
2444  *
2445  *  Numeric implements this by converting its value to a Float and
2446  *  invoking Float#ceil.
2447  */
2448 
2449 static VALUE
num_ceil(int argc,VALUE * argv,VALUE num)2450 num_ceil(int argc, VALUE *argv, VALUE num)
2451 {
2452     return flo_ceil(argc, argv, rb_Float(num));
2453 }
2454 
2455 /*
2456  *  call-seq:
2457  *     num.round([ndigits])  ->  integer or float
2458  *
2459  *  Returns +num+ rounded to the nearest value with
2460  *  a precision of +ndigits+ decimal digits (default: 0).
2461  *
2462  *  Numeric implements this by converting its value to a Float and
2463  *  invoking Float#round.
2464  */
2465 
2466 static VALUE
num_round(int argc,VALUE * argv,VALUE num)2467 num_round(int argc, VALUE* argv, VALUE num)
2468 {
2469     return flo_round(argc, argv, rb_Float(num));
2470 }
2471 
2472 /*
2473  *  call-seq:
2474  *     num.truncate([ndigits])  ->  integer or float
2475  *
2476  *  Returns +num+ truncated (toward zero) to
2477  *  a precision of +ndigits+ decimal digits (default: 0).
2478  *
2479  *  Numeric implements this by converting its value to a Float and
2480  *  invoking Float#truncate.
2481  */
2482 
2483 static VALUE
num_truncate(int argc,VALUE * argv,VALUE num)2484 num_truncate(int argc, VALUE *argv, VALUE num)
2485 {
2486     return flo_truncate(argc, argv, rb_Float(num));
2487 }
2488 
2489 double
ruby_float_step_size(double beg,double end,double unit,int excl)2490 ruby_float_step_size(double beg, double end, double unit, int excl)
2491 {
2492     const double epsilon = DBL_EPSILON;
2493     double n, err;
2494 
2495     if (unit == 0) {
2496         return HUGE_VAL;
2497     }
2498     n= (end - beg)/unit;
2499     err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2500     if (isinf(unit)) {
2501 	return unit > 0 ? beg <= end : beg >= end;
2502     }
2503     if (err>0.5) err=0.5;
2504     if (excl) {
2505 	if (n<=0) return 0;
2506 	if (n<1)
2507 	    n = 0;
2508 	else
2509 	    n = floor(n - err);
2510     }
2511     else {
2512 	if (n<0) return 0;
2513 	n = floor(n + err);
2514     }
2515     return n+1;
2516 }
2517 
2518 int
ruby_float_step(VALUE from,VALUE to,VALUE step,int excl,int allow_endless)2519 ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2520 {
2521     if (RB_TYPE_P(from, T_FLOAT) || RB_TYPE_P(to, T_FLOAT) || RB_TYPE_P(step, T_FLOAT)) {
2522 	double beg = NUM2DBL(from);
2523 	double end = (allow_endless && NIL_P(to)) ? HUGE_VAL : NUM2DBL(to);
2524 	double unit = NUM2DBL(step);
2525 	double n = ruby_float_step_size(beg, end, unit, excl);
2526 	long i;
2527 
2528 	if (isinf(unit)) {
2529 	    /* if unit is infinity, i*unit+beg is NaN */
2530 	    if (n) rb_yield(DBL2NUM(beg));
2531 	}
2532 	else if (unit == 0) {
2533 	    VALUE val = DBL2NUM(beg);
2534 	    for (;;)
2535 		rb_yield(val);
2536 	}
2537 	else {
2538 	    for (i=0; i<n; i++) {
2539 		double d = i*unit+beg;
2540 		if (unit >= 0 ? end < d : d < end) d = end;
2541 		rb_yield(DBL2NUM(d));
2542 	    }
2543 	}
2544 	return TRUE;
2545     }
2546     return FALSE;
2547 }
2548 
2549 VALUE
ruby_num_interval_step_size(VALUE from,VALUE to,VALUE step,int excl)2550 ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2551 {
2552     if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2553 	long delta, diff;
2554 
2555 	diff = FIX2LONG(step);
2556 	if (diff == 0) {
2557 	    return DBL2NUM(HUGE_VAL);
2558 	}
2559 	delta = FIX2LONG(to) - FIX2LONG(from);
2560 	if (diff < 0) {
2561 	    diff = -diff;
2562 	    delta = -delta;
2563 	}
2564 	if (excl) {
2565 	    delta--;
2566 	}
2567 	if (delta < 0) {
2568 	    return INT2FIX(0);
2569 	}
2570 	return ULONG2NUM(delta / diff + 1UL);
2571     }
2572     else if (RB_TYPE_P(from, T_FLOAT) || RB_TYPE_P(to, T_FLOAT) || RB_TYPE_P(step, T_FLOAT)) {
2573 	double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2574 
2575 	if (isinf(n)) return DBL2NUM(n);
2576 	if (POSFIXABLE(n)) return LONG2FIX(n);
2577 	return rb_dbl2big(n);
2578     }
2579     else {
2580 	VALUE result;
2581 	ID cmp = '>';
2582 	switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2583 	  case 0: return DBL2NUM(HUGE_VAL);
2584 	  case -1: cmp = '<'; break;
2585 	}
2586 	if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2587 	result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2588 	if (!excl || RTEST(rb_funcall(rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step)), cmp, 1, to))) {
2589 	    result = rb_funcall(result, '+', 1, INT2FIX(1));
2590 	}
2591 	return result;
2592     }
2593 }
2594 
2595 static int
num_step_negative_p(VALUE num)2596 num_step_negative_p(VALUE num)
2597 {
2598     const ID mid = '<';
2599     VALUE zero = INT2FIX(0);
2600     VALUE r;
2601 
2602     if (FIXNUM_P(num)) {
2603 	if (method_basic_p(rb_cInteger))
2604 	    return (SIGNED_VALUE)num < 0;
2605     }
2606     else if (RB_TYPE_P(num, T_BIGNUM)) {
2607 	if (method_basic_p(rb_cInteger))
2608 	    return BIGNUM_NEGATIVE_P(num);
2609     }
2610 
2611     r = rb_check_funcall(num, '>', 1, &zero);
2612     if (r == Qundef) {
2613 	coerce_failed(num, INT2FIX(0));
2614     }
2615     return !RTEST(r);
2616 }
2617 
2618 static int
num_step_extract_args(int argc,const VALUE * argv,VALUE * to,VALUE * step,VALUE * by)2619 num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2620 {
2621     VALUE hash;
2622 
2623     argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2624     if (!NIL_P(hash)) {
2625 	ID keys[2];
2626 	VALUE values[2];
2627 	keys[0] = id_to;
2628 	keys[1] = id_by;
2629 	rb_get_kwargs(hash, keys, 0, 2, values);
2630 	if (values[0] != Qundef) {
2631 	    if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2632 	    *to = values[0];
2633 	}
2634 	if (values[1] != Qundef) {
2635 	    if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2636 	    *by = values[1];
2637 	}
2638     }
2639 
2640     return argc;
2641 }
2642 
2643 static int
num_step_check_fix_args(int argc,VALUE * to,VALUE * step,VALUE by,int fix_nil,int allow_zero_step)2644 num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2645 {
2646     int desc;
2647     if (by != Qundef) {
2648         *step = by;
2649     }
2650     else {
2651         /* compatibility */
2652         if (argc > 1 && NIL_P(*step)) {
2653             rb_raise(rb_eTypeError, "step must be numeric");
2654         }
2655         if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2656             rb_raise(rb_eArgError, "step can't be 0");
2657         }
2658     }
2659     if (NIL_P(*step)) {
2660 	*step = INT2FIX(1);
2661     }
2662     desc = num_step_negative_p(*step);
2663     if (fix_nil && NIL_P(*to)) {
2664         *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2665     }
2666     return desc;
2667 }
2668 
2669 static int
num_step_scan_args(int argc,const VALUE * argv,VALUE * to,VALUE * step,int fix_nil,int allow_zero_step)2670 num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2671 {
2672     VALUE by = Qundef;
2673     argc = num_step_extract_args(argc, argv, to, step, &by);
2674     return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2675 }
2676 
2677 static VALUE
num_step_size(VALUE from,VALUE args,VALUE eobj)2678 num_step_size(VALUE from, VALUE args, VALUE eobj)
2679 {
2680     VALUE to, step;
2681     int argc = args ? RARRAY_LENINT(args) : 0;
2682     const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2683 
2684     num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2685 
2686     return ruby_num_interval_step_size(from, to, step, FALSE);
2687 }
2688 
2689 /*
2690  *  call-seq:
2691  *     num.step(by: step, to: limit) {|i| block }   ->  self
2692  *     num.step(by: step, to: limit)                ->  an_enumerator
2693  *     num.step(by: step, to: limit)                ->  an_arithmetic_sequence
2694  *     num.step(limit=nil, step=1) {|i| block }     ->  self
2695  *     num.step(limit=nil, step=1)                  ->  an_enumerator
2696  *     num.step(limit=nil, step=1)                  ->  an_arithmetic_sequence
2697  *
2698  *  Invokes the given block with the sequence of numbers starting at +num+,
2699  *  incremented by +step+ (defaulted to +1+) on each call.
2700  *
2701  *  The loop finishes when the value to be passed to the block is greater than
2702  *  +limit+ (if +step+ is positive) or less than +limit+ (if +step+ is
2703  *  negative), where +limit+ is defaulted to infinity.
2704  *
2705  *  In the recommended keyword argument style, either or both of
2706  *  +step+ and +limit+ (default infinity) can be omitted.  In the
2707  *  fixed position argument style, zero as a step
2708  *  (i.e. <code>num.step(limit, 0)</code>) is not allowed for historical
2709  *  compatibility reasons.
2710  *
2711  *  If all the arguments are integers, the loop operates using an integer
2712  *  counter.
2713  *
2714  *  If any of the arguments are floating point numbers, all are converted
2715  *  to floats, and the loop is executed
2716  *  <i>floor(n + n*Float::EPSILON) + 1</i> times,
2717  *  where <i>n = (limit - num)/step</i>.
2718  *
2719  *  Otherwise, the loop starts at +num+, uses either the
2720  *  less-than (<code><</code>) or greater-than (<code>></code>) operator
2721  *  to compare the counter against +limit+,
2722  *  and increments itself using the <code>+</code> operator.
2723  *
2724  *  If no block is given, an Enumerator is returned instead.
2725  *  Especially, the enumerator is an Enumerator::ArithmeticSequence
2726  *  if both +limit+ and +step+ are kind of Numeric or <code>nil</code>.
2727  *
2728  *  For example:
2729  *
2730  *     p 1.step.take(4)
2731  *     p 10.step(by: -1).take(4)
2732  *     3.step(to: 5) {|i| print i, " " }
2733  *     1.step(10, 2) {|i| print i, " " }
2734  *     Math::E.step(to: Math::PI, by: 0.2) {|f| print f, " " }
2735  *
2736  *  Will produce:
2737  *
2738  *     [1, 2, 3, 4]
2739  *     [10, 9, 8, 7]
2740  *     3 4 5
2741  *     1 3 5 7 9
2742  *     2.718281828459045 2.9182818284590453 3.118281828459045
2743  */
2744 
2745 static VALUE
num_step(int argc,VALUE * argv,VALUE from)2746 num_step(int argc, VALUE *argv, VALUE from)
2747 {
2748     VALUE to, step;
2749     int desc, inf;
2750 
2751     if (!rb_block_given_p()) {
2752         VALUE by = Qundef;
2753 
2754         num_step_extract_args(argc, argv, &to, &step, &by);
2755         if (by != Qundef) {
2756             step = by;
2757         }
2758         if (NIL_P(step)) {
2759             step = INT2FIX(1);
2760         }
2761         if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
2762             rb_obj_is_kind_of(step, rb_cNumeric)) {
2763             return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
2764                                     num_step_size, from, to, step, FALSE);
2765         }
2766 
2767         RETURN_SIZED_ENUMERATOR(from, argc, argv, num_step_size);
2768     }
2769 
2770     desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2771     if (rb_equal(step, INT2FIX(0))) {
2772 	inf = 1;
2773     }
2774     else if (RB_TYPE_P(to, T_FLOAT)) {
2775 	double f = RFLOAT_VALUE(to);
2776 	inf = isinf(f) && (signbit(f) ? desc : !desc);
2777     }
2778     else inf = 0;
2779 
2780     if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
2781 	long i = FIX2LONG(from);
2782 	long diff = FIX2LONG(step);
2783 
2784 	if (inf) {
2785 	    for (;; i += diff)
2786 		rb_yield(LONG2FIX(i));
2787 	}
2788 	else {
2789 	    long end = FIX2LONG(to);
2790 
2791 	    if (desc) {
2792 		for (; i >= end; i += diff)
2793 		    rb_yield(LONG2FIX(i));
2794 	    }
2795 	    else {
2796 		for (; i <= end; i += diff)
2797 		    rb_yield(LONG2FIX(i));
2798 	    }
2799 	}
2800     }
2801     else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
2802 	VALUE i = from;
2803 
2804 	if (inf) {
2805 	    for (;; i = rb_funcall(i, '+', 1, step))
2806 		rb_yield(i);
2807 	}
2808 	else {
2809 	    ID cmp = desc ? '<' : '>';
2810 
2811 	    for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
2812 		rb_yield(i);
2813 	}
2814     }
2815     return from;
2816 }
2817 
2818 static char *
out_of_range_float(char (* pbuf)[24],VALUE val)2819 out_of_range_float(char (*pbuf)[24], VALUE val)
2820 {
2821     char *const buf = *pbuf;
2822     char *s;
2823 
2824     snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
2825     if ((s = strchr(buf, ' ')) != 0) *s = '\0';
2826     return buf;
2827 }
2828 
2829 #define FLOAT_OUT_OF_RANGE(val, type) do { \
2830     char buf[24]; \
2831     rb_raise(rb_eRangeError, "float %s out of range of "type, \
2832 	     out_of_range_float(&buf, (val))); \
2833 } while (0)
2834 
2835 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
2836 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
2837 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
2838 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
2839   (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
2840    LONG_MIN <= (n): \
2841    LONG_MIN_MINUS_ONE < (n))
2842 
2843 long
rb_num2long(VALUE val)2844 rb_num2long(VALUE val)
2845 {
2846   again:
2847     if (NIL_P(val)) {
2848 	rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
2849     }
2850 
2851     if (FIXNUM_P(val)) return FIX2LONG(val);
2852 
2853     else if (RB_TYPE_P(val, T_FLOAT)) {
2854 	if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
2855 	    && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
2856 	    return (long)RFLOAT_VALUE(val);
2857 	}
2858 	else {
2859 	    FLOAT_OUT_OF_RANGE(val, "integer");
2860 	}
2861     }
2862     else if (RB_TYPE_P(val, T_BIGNUM)) {
2863 	return rb_big2long(val);
2864     }
2865     else {
2866 	val = rb_to_int(val);
2867 	goto again;
2868     }
2869 }
2870 
2871 static unsigned long
rb_num2ulong_internal(VALUE val,int * wrap_p)2872 rb_num2ulong_internal(VALUE val, int *wrap_p)
2873 {
2874   again:
2875     if (NIL_P(val)) {
2876        rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
2877     }
2878 
2879     if (FIXNUM_P(val)) {
2880         long l = FIX2LONG(val); /* this is FIX2LONG, intended */
2881         if (wrap_p)
2882             *wrap_p = l < 0;
2883         return (unsigned long)l;
2884     }
2885     else if (RB_TYPE_P(val, T_FLOAT)) {
2886 	double d = RFLOAT_VALUE(val);
2887 	if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
2888 	    if (wrap_p)
2889 		*wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually.  */
2890 	    if (0 <= d)
2891 		return (unsigned long)d;
2892 	    return (unsigned long)(long)d;
2893 	}
2894 	else {
2895 	    FLOAT_OUT_OF_RANGE(val, "integer");
2896 	}
2897     }
2898     else if (RB_TYPE_P(val, T_BIGNUM)) {
2899         {
2900             unsigned long ul = rb_big2ulong(val);
2901             if (wrap_p)
2902                 *wrap_p = BIGNUM_NEGATIVE_P(val);
2903             return ul;
2904         }
2905     }
2906     else {
2907         val = rb_to_int(val);
2908         goto again;
2909     }
2910 }
2911 
2912 unsigned long
rb_num2ulong(VALUE val)2913 rb_num2ulong(VALUE val)
2914 {
2915     return rb_num2ulong_internal(val, NULL);
2916 }
2917 
2918 #if SIZEOF_INT < SIZEOF_LONG
2919 void
rb_out_of_int(SIGNED_VALUE num)2920 rb_out_of_int(SIGNED_VALUE num)
2921 {
2922     rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'",
2923 	     num, num < 0 ? "small" : "big");
2924 }
2925 
2926 static void
check_int(long num)2927 check_int(long num)
2928 {
2929     if ((long)(int)num != num) {
2930 	rb_out_of_int(num);
2931     }
2932 }
2933 
2934 static void
check_uint(unsigned long num,int sign)2935 check_uint(unsigned long num, int sign)
2936 {
2937     if (sign) {
2938 	/* minus */
2939 	if (num < (unsigned long)INT_MIN)
2940 	    rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned int'", (long)num);
2941     }
2942     else {
2943 	/* plus */
2944 	if (UINT_MAX < num)
2945 	    rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num);
2946     }
2947 }
2948 
2949 long
rb_num2int(VALUE val)2950 rb_num2int(VALUE val)
2951 {
2952     long num = rb_num2long(val);
2953 
2954     check_int(num);
2955     return num;
2956 }
2957 
2958 long
rb_fix2int(VALUE val)2959 rb_fix2int(VALUE val)
2960 {
2961     long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
2962 
2963     check_int(num);
2964     return num;
2965 }
2966 
2967 unsigned long
rb_num2uint(VALUE val)2968 rb_num2uint(VALUE val)
2969 {
2970     int wrap;
2971     unsigned long num = rb_num2ulong_internal(val, &wrap);
2972 
2973     check_uint(num, wrap);
2974     return num;
2975 }
2976 
2977 unsigned long
rb_fix2uint(VALUE val)2978 rb_fix2uint(VALUE val)
2979 {
2980     unsigned long num;
2981 
2982     if (!FIXNUM_P(val)) {
2983 	return rb_num2uint(val);
2984     }
2985     num = FIX2ULONG(val);
2986 
2987     check_uint(num, rb_num_negative_int_p(val));
2988     return num;
2989 }
2990 #else
2991 long
rb_num2int(VALUE val)2992 rb_num2int(VALUE val)
2993 {
2994     return rb_num2long(val);
2995 }
2996 
2997 long
rb_fix2int(VALUE val)2998 rb_fix2int(VALUE val)
2999 {
3000     return FIX2INT(val);
3001 }
3002 #endif
3003 
3004 NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3005 static void
rb_out_of_short(SIGNED_VALUE num)3006 rb_out_of_short(SIGNED_VALUE num)
3007 {
3008     rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `short'",
3009 	     num, num < 0 ? "small" : "big");
3010 }
3011 
3012 static void
check_short(long num)3013 check_short(long num)
3014 {
3015     if ((long)(short)num != num) {
3016 	rb_out_of_short(num);
3017     }
3018 }
3019 
3020 static void
check_ushort(unsigned long num,int sign)3021 check_ushort(unsigned long num, int sign)
3022 {
3023     if (sign) {
3024 	/* minus */
3025 	if (num < (unsigned long)SHRT_MIN)
3026 	    rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned short'", (long)num);
3027     }
3028     else {
3029 	/* plus */
3030 	if (USHRT_MAX < num)
3031 	    rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned short'", num);
3032     }
3033 }
3034 
3035 short
rb_num2short(VALUE val)3036 rb_num2short(VALUE val)
3037 {
3038     long num = rb_num2long(val);
3039 
3040     check_short(num);
3041     return num;
3042 }
3043 
3044 short
rb_fix2short(VALUE val)3045 rb_fix2short(VALUE val)
3046 {
3047     long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3048 
3049     check_short(num);
3050     return num;
3051 }
3052 
3053 unsigned short
rb_num2ushort(VALUE val)3054 rb_num2ushort(VALUE val)
3055 {
3056     int wrap;
3057     unsigned long num = rb_num2ulong_internal(val, &wrap);
3058 
3059     check_ushort(num, wrap);
3060     return num;
3061 }
3062 
3063 unsigned short
rb_fix2ushort(VALUE val)3064 rb_fix2ushort(VALUE val)
3065 {
3066     unsigned long num;
3067 
3068     if (!FIXNUM_P(val)) {
3069 	return rb_num2ushort(val);
3070     }
3071     num = FIX2ULONG(val);
3072 
3073     check_ushort(num, rb_num_negative_int_p(val));
3074     return num;
3075 }
3076 
3077 VALUE
rb_num2fix(VALUE val)3078 rb_num2fix(VALUE val)
3079 {
3080     long v;
3081 
3082     if (FIXNUM_P(val)) return val;
3083 
3084     v = rb_num2long(val);
3085     if (!FIXABLE(v))
3086 	rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3087     return LONG2FIX(v);
3088 }
3089 
3090 #if HAVE_LONG_LONG
3091 
3092 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3093 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3094 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3095 #ifndef ULLONG_MAX
3096 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3097 #endif
3098 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3099   (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3100    LLONG_MIN <= (n): \
3101    LLONG_MIN_MINUS_ONE < (n))
3102 
3103 LONG_LONG
rb_num2ll(VALUE val)3104 rb_num2ll(VALUE val)
3105 {
3106     if (NIL_P(val)) {
3107 	rb_raise(rb_eTypeError, "no implicit conversion from nil");
3108     }
3109 
3110     if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3111 
3112     else if (RB_TYPE_P(val, T_FLOAT)) {
3113 	double d = RFLOAT_VALUE(val);
3114 	if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3115 	    return (LONG_LONG)d;
3116 	}
3117 	else {
3118 	    FLOAT_OUT_OF_RANGE(val, "long long");
3119 	}
3120     }
3121     else if (RB_TYPE_P(val, T_BIGNUM)) {
3122 	return rb_big2ll(val);
3123     }
3124     else if (RB_TYPE_P(val, T_STRING)) {
3125 	rb_raise(rb_eTypeError, "no implicit conversion from string");
3126     }
3127     else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3128 	rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3129     }
3130 
3131     val = rb_to_int(val);
3132     return NUM2LL(val);
3133 }
3134 
3135 unsigned LONG_LONG
rb_num2ull(VALUE val)3136 rb_num2ull(VALUE val)
3137 {
3138     if (RB_TYPE_P(val, T_NIL)) {
3139 	rb_raise(rb_eTypeError, "no implicit conversion from nil");
3140     }
3141     else if (RB_TYPE_P(val, T_FIXNUM)) {
3142 	return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3143     }
3144     else if (RB_TYPE_P(val, T_FLOAT)) {
3145 	double d = RFLOAT_VALUE(val);
3146 	if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3147 	    if (0 <= d)
3148 		return (unsigned LONG_LONG)d;
3149 	    return (unsigned LONG_LONG)(LONG_LONG)d;
3150 	}
3151 	else {
3152 	    FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3153 	}
3154     }
3155     else if (RB_TYPE_P(val, T_BIGNUM)) {
3156 	return rb_big2ull(val);
3157     }
3158     else if (RB_TYPE_P(val, T_STRING)) {
3159 	rb_raise(rb_eTypeError, "no implicit conversion from string");
3160     }
3161     else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3162 	rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3163     }
3164 
3165     val = rb_to_int(val);
3166     return NUM2ULL(val);
3167 }
3168 
3169 #endif  /* HAVE_LONG_LONG */
3170 
3171 /********************************************************************
3172  *
3173  * Document-class: Integer
3174  *
3175  *  Holds Integer values.  You cannot add a singleton method to an
3176  *  Integer object, any attempt to do so will raise a TypeError.
3177  *
3178  */
3179 
3180 /*
3181  *  call-seq:
3182  *     int.to_i    ->  integer
3183  *     int.to_int  ->  integer
3184  *
3185  *  Since +int+ is already an Integer, returns +self+.
3186  *
3187  *  #to_int is an alias for #to_i.
3188  */
3189 
3190 static VALUE
int_to_i(VALUE num)3191 int_to_i(VALUE num)
3192 {
3193     return num;
3194 }
3195 
3196 /*
3197  *  call-seq:
3198  *     int.integer?  ->  true
3199  *
3200  *  Since +int+ is already an Integer, this always returns +true+.
3201  */
3202 
3203 static VALUE
int_int_p(VALUE num)3204 int_int_p(VALUE num)
3205 {
3206     return Qtrue;
3207 }
3208 
3209 /*
3210  *  call-seq:
3211  *     int.odd?  ->  true or false
3212  *
3213  *  Returns +true+ if +int+ is an odd number.
3214  */
3215 
3216 VALUE
rb_int_odd_p(VALUE num)3217 rb_int_odd_p(VALUE num)
3218 {
3219     if (FIXNUM_P(num)) {
3220 	if (num & 2) {
3221 	    return Qtrue;
3222 	}
3223     }
3224     else if (RB_TYPE_P(num, T_BIGNUM)) {
3225 	return rb_big_odd_p(num);
3226     }
3227     else if (rb_funcall(num, '%', 1, INT2FIX(2)) != INT2FIX(0)) {
3228 	return Qtrue;
3229     }
3230     return Qfalse;
3231 }
3232 
3233 /*
3234  *  call-seq:
3235  *     int.even?  ->  true or false
3236  *
3237  *  Returns +true+ if +int+ is an even number.
3238  */
3239 
3240 static VALUE
int_even_p(VALUE num)3241 int_even_p(VALUE num)
3242 {
3243     if (FIXNUM_P(num)) {
3244 	if ((num & 2) == 0) {
3245 	    return Qtrue;
3246 	}
3247     }
3248     else if (RB_TYPE_P(num, T_BIGNUM)) {
3249 	return rb_big_even_p(num);
3250     }
3251     else if (rb_funcall(num, '%', 1, INT2FIX(2)) == INT2FIX(0)) {
3252 	return Qtrue;
3253     }
3254     return Qfalse;
3255 }
3256 
3257 /*
3258  *  call-seq:
3259  *     int.allbits?(mask)  ->  true or false
3260  *
3261  *  Returns +true+ if all bits of <code>+int+ & +mask+</code> are 1.
3262  */
3263 
3264 static VALUE
int_allbits_p(VALUE num,VALUE mask)3265 int_allbits_p(VALUE num, VALUE mask)
3266 {
3267     mask = rb_to_int(mask);
3268     return rb_int_equal(rb_int_and(num, mask), mask);
3269 }
3270 
3271 /*
3272  *  call-seq:
3273  *     int.anybits?(mask)  ->  true or false
3274  *
3275  *  Returns +true+ if any bits of <code>+int+ & +mask+</code> are 1.
3276  */
3277 
3278 static VALUE
int_anybits_p(VALUE num,VALUE mask)3279 int_anybits_p(VALUE num, VALUE mask)
3280 {
3281     mask = rb_to_int(mask);
3282     return num_zero_p(rb_int_and(num, mask)) ? Qfalse : Qtrue;
3283 }
3284 
3285 /*
3286  *  call-seq:
3287  *     int.nobits?(mask)  ->  true or false
3288  *
3289  *  Returns +true+ if no bits of <code>+int+ & +mask+</code> are 1.
3290  */
3291 
3292 static VALUE
int_nobits_p(VALUE num,VALUE mask)3293 int_nobits_p(VALUE num, VALUE mask)
3294 {
3295     mask = rb_to_int(mask);
3296     return num_zero_p(rb_int_and(num, mask));
3297 }
3298 
3299 /*
3300  *  Document-method: Integer#succ
3301  *  Document-method: Integer#next
3302  *  call-seq:
3303  *     int.next  ->  integer
3304  *     int.succ  ->  integer
3305  *
3306  *  Returns the successor of +int+,
3307  *  i.e. the Integer equal to <code>int+1</code>.
3308  *
3309  *     1.next      #=> 2
3310  *     (-1).next   #=> 0
3311  *     1.succ      #=> 2
3312  *     (-1).succ   #=> 0
3313  */
3314 
3315 VALUE
rb_int_succ(VALUE num)3316 rb_int_succ(VALUE num)
3317 {
3318     if (FIXNUM_P(num)) {
3319 	long i = FIX2LONG(num) + 1;
3320 	return LONG2NUM(i);
3321     }
3322     if (RB_TYPE_P(num, T_BIGNUM)) {
3323 	return rb_big_plus(num, INT2FIX(1));
3324     }
3325     return num_funcall1(num, '+', INT2FIX(1));
3326 }
3327 
3328 #define int_succ rb_int_succ
3329 
3330 /*
3331  *  call-seq:
3332  *     int.pred  ->  integer
3333  *
3334  *  Returns the predecessor of +int+,
3335  *  i.e. the Integer equal to <code>int-1</code>.
3336  *
3337  *     1.pred      #=> 0
3338  *     (-1).pred   #=> -2
3339  */
3340 
3341 VALUE
rb_int_pred(VALUE num)3342 rb_int_pred(VALUE num)
3343 {
3344     if (FIXNUM_P(num)) {
3345 	long i = FIX2LONG(num) - 1;
3346 	return LONG2NUM(i);
3347     }
3348     if (RB_TYPE_P(num, T_BIGNUM)) {
3349 	return rb_big_minus(num, INT2FIX(1));
3350     }
3351     return num_funcall1(num, '-', INT2FIX(1));
3352 }
3353 
3354 #define int_pred rb_int_pred
3355 
3356 /*
3357  *  Document-method: Integer#chr
3358  *  call-seq:
3359  *     int.chr([encoding])  ->  string
3360  *
3361  *  Returns a string containing the character represented by the +int+'s value
3362  *  according to +encoding+.
3363  *
3364  *     65.chr    #=> "A"
3365  *     230.chr   #=> "\xE6"
3366  *     255.chr(Encoding::UTF_8)   #=> "\u00FF"
3367  */
3368 
3369 VALUE
rb_enc_uint_chr(unsigned int code,rb_encoding * enc)3370 rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3371 {
3372     int n;
3373     VALUE str;
3374     switch (n = rb_enc_codelen(code, enc)) {
3375       case ONIGERR_INVALID_CODE_POINT_VALUE:
3376 	rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3377 	break;
3378       case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3379       case 0:
3380 	rb_raise(rb_eRangeError, "%u out of char range", code);
3381 	break;
3382     }
3383     str = rb_enc_str_new(0, n, enc);
3384     rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3385     if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3386 	rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3387     }
3388     return str;
3389 }
3390 
3391 static VALUE
int_chr(int argc,VALUE * argv,VALUE num)3392 int_chr(int argc, VALUE *argv, VALUE num)
3393 {
3394     char c;
3395     unsigned int i;
3396     rb_encoding *enc;
3397 
3398     if (rb_num_to_uint(num, &i) == 0) {
3399     }
3400     else if (FIXNUM_P(num)) {
3401 	rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3402     }
3403     else {
3404 	rb_raise(rb_eRangeError, "bignum out of char range");
3405     }
3406 
3407     switch (argc) {
3408       case 0:
3409 	if (0xff < i) {
3410 	    enc = rb_default_internal_encoding();
3411 	    if (!enc) {
3412 		rb_raise(rb_eRangeError, "%d out of char range", i);
3413 	    }
3414 	    goto decode;
3415 	}
3416 	c = (char)i;
3417 	if (i < 0x80) {
3418 	    return rb_usascii_str_new(&c, 1);
3419 	}
3420 	else {
3421 	    return rb_str_new(&c, 1);
3422 	}
3423       case 1:
3424 	break;
3425       default:
3426 	rb_check_arity(argc, 0, 1);
3427 	break;
3428     }
3429     enc = rb_to_encoding(argv[0]);
3430     if (!enc) enc = rb_ascii8bit_encoding();
3431   decode:
3432     return rb_enc_uint_chr(i, enc);
3433 }
3434 
3435 /*
3436  *  call-seq:
3437  *     int.ord  ->  self
3438  *
3439  *  Returns the +int+ itself.
3440  *
3441  *     97.ord   #=> 97
3442  *
3443  *  This method is intended for compatibility to character literals
3444  *  in Ruby 1.9.
3445  *
3446  *  For example, <code>?a.ord</code> returns 97 both in 1.8 and 1.9.
3447  */
3448 
3449 static VALUE
int_ord(VALUE num)3450 int_ord(VALUE num)
3451 {
3452     return num;
3453 }
3454 
3455 /*
3456  * Fixnum
3457  */
3458 
3459 
3460 /*
3461  * Document-method: Integer#-@
3462  * call-seq:
3463  *    -int  ->  integer
3464  *
3465  * Returns +int+, negated.
3466  */
3467 
3468 static VALUE
fix_uminus(VALUE num)3469 fix_uminus(VALUE num)
3470 {
3471     return LONG2NUM(-FIX2LONG(num));
3472 }
3473 
3474 VALUE
rb_int_uminus(VALUE num)3475 rb_int_uminus(VALUE num)
3476 {
3477     if (FIXNUM_P(num)) {
3478 	return fix_uminus(num);
3479     }
3480     else if (RB_TYPE_P(num, T_BIGNUM)) {
3481 	return rb_big_uminus(num);
3482     }
3483     return num_funcall0(num, idUMinus);
3484 }
3485 
3486 /*
3487  *  Document-method: Integer#to_s
3488  *  call-seq:
3489  *     int.to_s(base=10)  ->  string
3490  *
3491  *  Returns a string containing the place-value representation of +int+
3492  *  with radix +base+ (between 2 and 36).
3493  *
3494  *     12345.to_s       #=> "12345"
3495  *     12345.to_s(2)    #=> "11000000111001"
3496  *     12345.to_s(8)    #=> "30071"
3497  *     12345.to_s(10)   #=> "12345"
3498  *     12345.to_s(16)   #=> "3039"
3499  *     12345.to_s(36)   #=> "9ix"
3500  *     78546939656932.to_s(36)  #=> "rubyrules"
3501  */
3502 
3503 VALUE
rb_fix2str(VALUE x,int base)3504 rb_fix2str(VALUE x, int base)
3505 {
3506     char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3507     long val = FIX2LONG(x);
3508     unsigned long u;
3509     int neg = 0;
3510 
3511     if (base < 2 || 36 < base) {
3512 	rb_raise(rb_eArgError, "invalid radix %d", base);
3513     }
3514 #if SIZEOF_LONG < SIZEOF_VOIDP
3515 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3516     if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
3517 	(val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
3518 	rb_bug("Unnormalized Fixnum value %p", (void *)x);
3519     }
3520 # else
3521     /* should do something like above code, but currently ruby does not know */
3522     /* such platforms */
3523 # endif
3524 #endif
3525     if (val == 0) {
3526 	return rb_usascii_str_new2("0");
3527     }
3528     if (val < 0) {
3529 	u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3530 	neg = 1;
3531     }
3532     else {
3533 	u = val;
3534     }
3535     do {
3536 	*--b = ruby_digitmap[(int)(u % base)];
3537     } while (u /= base);
3538     if (neg) {
3539 	*--b = '-';
3540     }
3541 
3542     return rb_usascii_str_new(b, e - b);
3543 }
3544 
3545 static VALUE
int_to_s(int argc,VALUE * argv,VALUE x)3546 int_to_s(int argc, VALUE *argv, VALUE x)
3547 {
3548     int base;
3549 
3550     if (rb_check_arity(argc, 0, 1))
3551 	base = NUM2INT(argv[0]);
3552     else
3553 	base = 10;
3554     return rb_int2str(x, base);
3555 }
3556 
3557 VALUE
rb_int2str(VALUE x,int base)3558 rb_int2str(VALUE x, int base)
3559 {
3560     if (FIXNUM_P(x)) {
3561 	return rb_fix2str(x, base);
3562     }
3563     else if (RB_TYPE_P(x, T_BIGNUM)) {
3564 	return rb_big2str(x, base);
3565     }
3566 
3567     return rb_any_to_s(x);
3568 }
3569 
3570 /*
3571  * Document-method: Integer#+
3572  * call-seq:
3573  *    int + numeric  ->  numeric_result
3574  *
3575  * Performs addition: the class of the resulting object depends on
3576  * the class of +numeric+.
3577  */
3578 
3579 static VALUE
fix_plus(VALUE x,VALUE y)3580 fix_plus(VALUE x, VALUE y)
3581 {
3582     if (FIXNUM_P(y)) {
3583 	return rb_fix_plus_fix(x, y);
3584     }
3585     else if (RB_TYPE_P(y, T_BIGNUM)) {
3586 	return rb_big_plus(y, x);
3587     }
3588     else if (RB_TYPE_P(y, T_FLOAT)) {
3589 	return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
3590     }
3591     else if (RB_TYPE_P(y, T_COMPLEX)) {
3592 	return rb_complex_plus(y, x);
3593     }
3594     else {
3595 	return rb_num_coerce_bin(x, y, '+');
3596     }
3597 }
3598 
3599 VALUE
rb_fix_plus(VALUE x,VALUE y)3600 rb_fix_plus(VALUE x, VALUE y)
3601 {
3602     return fix_plus(x, y);
3603 }
3604 
3605 VALUE
rb_int_plus(VALUE x,VALUE y)3606 rb_int_plus(VALUE x, VALUE y)
3607 {
3608     if (FIXNUM_P(x)) {
3609 	return fix_plus(x, y);
3610     }
3611     else if (RB_TYPE_P(x, T_BIGNUM)) {
3612 	return rb_big_plus(x, y);
3613     }
3614     return rb_num_coerce_bin(x, y, '+');
3615 }
3616 
3617 /*
3618  * Document-method: Integer#-
3619  * call-seq:
3620  *    int - numeric  ->  numeric_result
3621  *
3622  * Performs subtraction: the class of the resulting object depends on
3623  * the class of +numeric+.
3624  */
3625 
3626 static VALUE
fix_minus(VALUE x,VALUE y)3627 fix_minus(VALUE x, VALUE y)
3628 {
3629     if (FIXNUM_P(y)) {
3630 	return rb_fix_minus_fix(x, y);
3631     }
3632     else if (RB_TYPE_P(y, T_BIGNUM)) {
3633 	x = rb_int2big(FIX2LONG(x));
3634 	return rb_big_minus(x, y);
3635     }
3636     else if (RB_TYPE_P(y, T_FLOAT)) {
3637 	return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
3638     }
3639     else {
3640 	return rb_num_coerce_bin(x, y, '-');
3641     }
3642 }
3643 
3644 VALUE
rb_int_minus(VALUE x,VALUE y)3645 rb_int_minus(VALUE x, VALUE y)
3646 {
3647     if (FIXNUM_P(x)) {
3648 	return fix_minus(x, y);
3649     }
3650     else if (RB_TYPE_P(x, T_BIGNUM)) {
3651 	return rb_big_minus(x, y);
3652     }
3653     return rb_num_coerce_bin(x, y, '-');
3654 }
3655 
3656 
3657 #define SQRT_LONG_MAX HALF_LONG_MSB
3658 /*tests if N*N would overflow*/
3659 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
3660 
3661 /*
3662  * Document-method: Integer#*
3663  * call-seq:
3664  *    int * numeric  ->  numeric_result
3665  *
3666  * Performs multiplication: the class of the resulting object depends on
3667  * the class of +numeric+.
3668  */
3669 
3670 static VALUE
fix_mul(VALUE x,VALUE y)3671 fix_mul(VALUE x, VALUE y)
3672 {
3673     if (FIXNUM_P(y)) {
3674 	return rb_fix_mul_fix(x, y);
3675     }
3676     else if (RB_TYPE_P(y, T_BIGNUM)) {
3677 	switch (x) {
3678 	  case INT2FIX(0): return x;
3679 	  case INT2FIX(1): return y;
3680 	}
3681 	return rb_big_mul(y, x);
3682     }
3683     else if (RB_TYPE_P(y, T_FLOAT)) {
3684 	return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
3685     }
3686     else if (RB_TYPE_P(y, T_COMPLEX)) {
3687 	return rb_complex_mul(y, x);
3688     }
3689     else {
3690 	return rb_num_coerce_bin(x, y, '*');
3691     }
3692 }
3693 
3694 VALUE
rb_int_mul(VALUE x,VALUE y)3695 rb_int_mul(VALUE x, VALUE y)
3696 {
3697     if (FIXNUM_P(x)) {
3698 	return fix_mul(x, y);
3699     }
3700     else if (RB_TYPE_P(x, T_BIGNUM)) {
3701 	return rb_big_mul(x, y);
3702     }
3703     return rb_num_coerce_bin(x, y, '*');
3704 }
3705 
3706 static double
fix_fdiv_double(VALUE x,VALUE y)3707 fix_fdiv_double(VALUE x, VALUE y)
3708 {
3709     if (FIXNUM_P(y)) {
3710         return double_div_double(FIX2LONG(x), FIX2LONG(y));
3711     }
3712     else if (RB_TYPE_P(y, T_BIGNUM)) {
3713         return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
3714     }
3715     else if (RB_TYPE_P(y, T_FLOAT)) {
3716         return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
3717     }
3718     else {
3719         return NUM2DBL(rb_num_coerce_bin(x, y, rb_intern("fdiv")));
3720     }
3721 }
3722 
3723 double
rb_int_fdiv_double(VALUE x,VALUE y)3724 rb_int_fdiv_double(VALUE x, VALUE y)
3725 {
3726     if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) {
3727 	VALUE gcd = rb_gcd(x, y);
3728 	if (!FIXNUM_ZERO_P(gcd)) {
3729 	    x = rb_int_idiv(x, gcd);
3730 	    y = rb_int_idiv(y, gcd);
3731 	}
3732     }
3733     if (FIXNUM_P(x)) {
3734         return fix_fdiv_double(x, y);
3735     }
3736     else if (RB_TYPE_P(x, T_BIGNUM)) {
3737         return rb_big_fdiv_double(x, y);
3738     }
3739     else {
3740         return nan("");
3741     }
3742 }
3743 
3744 /*
3745  *  Document-method: Integer#fdiv
3746  *  call-seq:
3747  *     int.fdiv(numeric)  ->  float
3748  *
3749  *  Returns the floating point result of dividing +int+ by +numeric+.
3750  *
3751  *     654321.fdiv(13731)      #=> 47.652829364212366
3752  *     654321.fdiv(13731.24)   #=> 47.65199646936475
3753  *     -654321.fdiv(13731)     #=> -47.652829364212366
3754  */
3755 
3756 VALUE
rb_int_fdiv(VALUE x,VALUE y)3757 rb_int_fdiv(VALUE x, VALUE y)
3758 {
3759     if (RB_INTEGER_TYPE_P(x)) {
3760         return DBL2NUM(rb_int_fdiv_double(x, y));
3761     }
3762     return Qnil;
3763 }
3764 
3765 /*
3766  * Document-method: Integer#/
3767  * call-seq:
3768  *    int / numeric  ->  numeric_result
3769  *
3770  * Performs division: the class of the resulting object depends on
3771  * the class of +numeric+.
3772  */
3773 
3774 static VALUE
fix_divide(VALUE x,VALUE y,ID op)3775 fix_divide(VALUE x, VALUE y, ID op)
3776 {
3777     if (FIXNUM_P(y)) {
3778 	if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
3779 	return rb_fix_div_fix(x, y);
3780     }
3781     else if (RB_TYPE_P(y, T_BIGNUM)) {
3782 	x = rb_int2big(FIX2LONG(x));
3783 	return rb_big_div(x, y);
3784     }
3785     else if (RB_TYPE_P(y, T_FLOAT)) {
3786 	    if (op == '/') {
3787                 double d = FIX2LONG(x);
3788                 return rb_flo_div_flo(DBL2NUM(d), y);
3789 	    }
3790 	    else {
3791                 VALUE v;
3792 		if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
3793                 v = fix_divide(x, y, '/');
3794                 return flo_floor(0, 0, v);
3795 	    }
3796     }
3797     else {
3798 	if (RB_TYPE_P(y, T_RATIONAL) &&
3799 	    op == '/' && FIX2LONG(x) == 1)
3800 	    return rb_rational_reciprocal(y);
3801 	return rb_num_coerce_bin(x, y, op);
3802     }
3803 }
3804 
3805 static VALUE
fix_div(VALUE x,VALUE y)3806 fix_div(VALUE x, VALUE y)
3807 {
3808     return fix_divide(x, y, '/');
3809 }
3810 
3811 VALUE
rb_int_div(VALUE x,VALUE y)3812 rb_int_div(VALUE x, VALUE y)
3813 {
3814     if (FIXNUM_P(x)) {
3815 	return fix_div(x, y);
3816     }
3817     else if (RB_TYPE_P(x, T_BIGNUM)) {
3818 	return rb_big_div(x, y);
3819     }
3820     return Qnil;
3821 }
3822 
3823 /*
3824  * Document-method: Integer#div
3825  * call-seq:
3826  *    int.div(numeric)  ->  integer
3827  *
3828  * Performs integer division: returns the integer result of dividing +int+
3829  * by +numeric+.
3830  */
3831 
3832 static VALUE
fix_idiv(VALUE x,VALUE y)3833 fix_idiv(VALUE x, VALUE y)
3834 {
3835     return fix_divide(x, y, id_div);
3836 }
3837 
3838 VALUE
rb_int_idiv(VALUE x,VALUE y)3839 rb_int_idiv(VALUE x, VALUE y)
3840 {
3841     if (FIXNUM_P(x)) {
3842 	return fix_idiv(x, y);
3843     }
3844     else if (RB_TYPE_P(x, T_BIGNUM)) {
3845 	return rb_big_idiv(x, y);
3846     }
3847     return num_div(x, y);
3848 }
3849 
3850 /*
3851  *  Document-method: Integer#%
3852  *  Document-method: Integer#modulo
3853  *  call-seq:
3854  *     int % other        ->  real
3855  *     int.modulo(other)  ->  real
3856  *
3857  *  Returns +int+ modulo +other+.
3858  *
3859  *  See Numeric#divmod for more information.
3860  */
3861 
3862 static VALUE
fix_mod(VALUE x,VALUE y)3863 fix_mod(VALUE x, VALUE y)
3864 {
3865     if (FIXNUM_P(y)) {
3866 	if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
3867 	return rb_fix_mod_fix(x, y);
3868     }
3869     else if (RB_TYPE_P(y, T_BIGNUM)) {
3870 	x = rb_int2big(FIX2LONG(x));
3871 	return rb_big_modulo(x, y);
3872     }
3873     else if (RB_TYPE_P(y, T_FLOAT)) {
3874 	return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
3875     }
3876     else {
3877 	return rb_num_coerce_bin(x, y, '%');
3878     }
3879 }
3880 
3881 VALUE
rb_int_modulo(VALUE x,VALUE y)3882 rb_int_modulo(VALUE x, VALUE y)
3883 {
3884     if (FIXNUM_P(x)) {
3885 	return fix_mod(x, y);
3886     }
3887     else if (RB_TYPE_P(x, T_BIGNUM)) {
3888 	return rb_big_modulo(x, y);
3889     }
3890     return num_modulo(x, y);
3891 }
3892 
3893 /*
3894  *  call-seq:
3895  *     int.remainder(numeric)  ->  real
3896  *
3897  *  Returns the remainder after dividing +int+ by +numeric+.
3898  *
3899  *  <code>x.remainder(y)</code> means <code>x-y*(x/y).truncate</code>.
3900  *
3901  *     5.remainder(3)     #=> 2
3902  *     -5.remainder(3)    #=> -2
3903  *     5.remainder(-3)    #=> 2
3904  *     -5.remainder(-3)   #=> -2
3905  *     5.remainder(1.5)   #=> 0.5
3906  *
3907  *  See Numeric#divmod.
3908  */
3909 
3910 static VALUE
int_remainder(VALUE x,VALUE y)3911 int_remainder(VALUE x, VALUE y)
3912 {
3913     if (FIXNUM_P(x)) {
3914 	return num_remainder(x, y);
3915     }
3916     else if (RB_TYPE_P(x, T_BIGNUM)) {
3917 	return rb_big_remainder(x, y);
3918     }
3919     return Qnil;
3920 }
3921 
3922 /*
3923  *  Document-method: Integer#divmod
3924  *  call-seq:
3925  *     int.divmod(numeric)  ->  array
3926  *
3927  *  See Numeric#divmod.
3928  */
3929 static VALUE
fix_divmod(VALUE x,VALUE y)3930 fix_divmod(VALUE x, VALUE y)
3931 {
3932     if (FIXNUM_P(y)) {
3933 	VALUE div, mod;
3934 	if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
3935 	rb_fix_divmod_fix(x, y, &div, &mod);
3936 	return rb_assoc_new(div, mod);
3937     }
3938     else if (RB_TYPE_P(y, T_BIGNUM)) {
3939 	x = rb_int2big(FIX2LONG(x));
3940 	return rb_big_divmod(x, y);
3941     }
3942     else if (RB_TYPE_P(y, T_FLOAT)) {
3943 	{
3944 	    double div, mod;
3945 	    volatile VALUE a, b;
3946 
3947 	    flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
3948 	    a = dbl2ival(div);
3949 	    b = DBL2NUM(mod);
3950 	    return rb_assoc_new(a, b);
3951 	}
3952     }
3953     else {
3954 	return rb_num_coerce_bin(x, y, id_divmod);
3955     }
3956 }
3957 
3958 VALUE
rb_int_divmod(VALUE x,VALUE y)3959 rb_int_divmod(VALUE x, VALUE y)
3960 {
3961     if (FIXNUM_P(x)) {
3962 	return fix_divmod(x, y);
3963     }
3964     else if (RB_TYPE_P(x, T_BIGNUM)) {
3965 	return rb_big_divmod(x, y);
3966     }
3967     return Qnil;
3968 }
3969 
3970 /*
3971  *  Document-method: Integer#**
3972  *  call-seq:
3973  *     int ** numeric  ->  numeric_result
3974  *
3975  *  Raises +int+ to the power of +numeric+, which may be negative or
3976  *  fractional.
3977  *  The result may be an Integer, a Float, a Rational, or a complex number.
3978  *
3979  *     2 ** 3        #=> 8
3980  *     2 ** -1       #=> (1/2)
3981  *     2 ** 0.5      #=> 1.4142135623730951
3982  *     (-1) ** 0.5   #=> (0.0+1.0i)
3983  *
3984  *     123456789 ** 2     #=> 15241578750190521
3985  *     123456789 ** 1.2   #=> 5126464716.0993185
3986  *     123456789 ** -2    #=> (1/15241578750190521)
3987  */
3988 
3989 static VALUE
int_pow(long x,unsigned long y)3990 int_pow(long x, unsigned long y)
3991 {
3992     int neg = x < 0;
3993     long z = 1;
3994 
3995     if (y == 0) return INT2FIX(1);
3996     if (y == 1) return LONG2NUM(x);
3997     if (neg) x = -x;
3998     if (y & 1)
3999 	z = x;
4000     else
4001 	neg = 0;
4002     y &= ~1;
4003     do {
4004 	while (y % 2 == 0) {
4005 	    if (!FIT_SQRT_LONG(x)) {
4006 		VALUE v;
4007 	      bignum:
4008 		v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4009 		if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4010 		    return v;
4011 		if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4012 		return v;
4013 	    }
4014 	    x = x * x;
4015 	    y >>= 1;
4016 	}
4017 	{
4018             if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4019 		goto bignum;
4020 	    }
4021 	    z = x * z;
4022 	}
4023     } while (--y);
4024     if (neg) z = -z;
4025     return LONG2NUM(z);
4026 }
4027 
4028 VALUE
rb_int_positive_pow(long x,unsigned long y)4029 rb_int_positive_pow(long x, unsigned long y)
4030 {
4031     return int_pow(x, y);
4032 }
4033 
4034 static VALUE
fix_pow(VALUE x,VALUE y)4035 fix_pow(VALUE x, VALUE y)
4036 {
4037     long a = FIX2LONG(x);
4038 
4039     if (FIXNUM_P(y)) {
4040 	long b = FIX2LONG(y);
4041 
4042 	if (a == 1) return INT2FIX(1);
4043 	if (a == -1) {
4044 	    if (b % 2 == 0)
4045 		return INT2FIX(1);
4046 	    else
4047 		return INT2FIX(-1);
4048 	}
4049 	if (b < 0) {
4050 	    if (a == 0) rb_num_zerodiv();
4051             y = rb_int_pow(x, LONG2NUM(-b));
4052             goto inverted;
4053 	}
4054 
4055 	if (b == 0) return INT2FIX(1);
4056 	if (b == 1) return x;
4057 	if (a == 0) {
4058 	    if (b > 0) return INT2FIX(0);
4059 	    return DBL2NUM(HUGE_VAL);
4060 	}
4061 	return int_pow(a, b);
4062     }
4063     else if (RB_TYPE_P(y, T_BIGNUM)) {
4064 	if (a == 1) return INT2FIX(1);
4065 	if (a == -1) {
4066 	    if (int_even_p(y)) return INT2FIX(1);
4067 	    else return INT2FIX(-1);
4068 	}
4069 	if (BIGNUM_NEGATIVE_P(y)) {
4070 	    if (a == 0) rb_num_zerodiv();
4071             y = rb_int_pow(x, rb_big_uminus(y));
4072           inverted:
4073             if (RB_FLOAT_TYPE_P(y)) {
4074                 double d = pow((double)a, RFLOAT_VALUE(y));
4075                 return DBL2NUM(1.0 / d);
4076             }
4077             return rb_rational_raw(INT2FIX(1), y);
4078 	}
4079 	if (a == 0) return INT2FIX(0);
4080 	x = rb_int2big(FIX2LONG(x));
4081 	return rb_big_pow(x, y);
4082     }
4083     else if (RB_TYPE_P(y, T_FLOAT)) {
4084 	double dy = RFLOAT_VALUE(y);
4085 	if (dy == 0.0) return DBL2NUM(1.0);
4086 	if (a == 0) {
4087 	    return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4088 	}
4089 	if (a == 1) return DBL2NUM(1.0);
4090 	{
4091 	    if (a < 0 && dy != round(dy))
4092                 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4093 	    return DBL2NUM(pow((double)a, dy));
4094 	}
4095     }
4096     else {
4097 	return rb_num_coerce_bin(x, y, idPow);
4098     }
4099 }
4100 
4101 VALUE
rb_int_pow(VALUE x,VALUE y)4102 rb_int_pow(VALUE x, VALUE y)
4103 {
4104     if (FIXNUM_P(x)) {
4105 	return fix_pow(x, y);
4106     }
4107     else if (RB_TYPE_P(x, T_BIGNUM)) {
4108 	return rb_big_pow(x, y);
4109     }
4110     return Qnil;
4111 }
4112 
4113 VALUE
rb_num_pow(VALUE x,VALUE y)4114 rb_num_pow(VALUE x, VALUE y)
4115 {
4116     VALUE z = rb_int_pow(x, y);
4117     if (!NIL_P(z)) return z;
4118     if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4119     if (SPECIAL_CONST_P(x)) return Qnil;
4120     switch (BUILTIN_TYPE(x)) {
4121       case T_COMPLEX:
4122         return rb_complex_pow(x, y);
4123       case T_RATIONAL:
4124         return rb_rational_pow(x, y);
4125     }
4126     return Qnil;
4127 }
4128 
4129 /*
4130  * Document-method: Integer#==
4131  * Document-method: Integer#===
4132  * call-seq:
4133  *    int == other  ->  true or false
4134  *
4135  * Returns +true+ if +int+ equals +other+ numerically.
4136  * Contrast this with Integer#eql?, which requires +other+ to be an Integer.
4137  *
4138  *    1 == 2     #=> false
4139  *    1 == 1.0   #=> true
4140  */
4141 
4142 static VALUE
fix_equal(VALUE x,VALUE y)4143 fix_equal(VALUE x, VALUE y)
4144 {
4145     if (x == y) return Qtrue;
4146     if (FIXNUM_P(y)) return Qfalse;
4147     else if (RB_TYPE_P(y, T_BIGNUM)) {
4148 	return rb_big_eq(y, x);
4149     }
4150     else if (RB_TYPE_P(y, T_FLOAT)) {
4151         return rb_integer_float_eq(x, y);
4152     }
4153     else {
4154 	return num_equal(x, y);
4155     }
4156 }
4157 
4158 VALUE
rb_int_equal(VALUE x,VALUE y)4159 rb_int_equal(VALUE x, VALUE y)
4160 {
4161     if (FIXNUM_P(x)) {
4162 	return fix_equal(x, y);
4163     }
4164     else if (RB_TYPE_P(x, T_BIGNUM)) {
4165 	return rb_big_eq(x, y);
4166     }
4167     return Qnil;
4168 }
4169 
4170 /*
4171  *  Document-method: Integer#<=>
4172  *  call-seq:
4173  *     int <=> numeric  ->  -1, 0, +1, or nil
4174  *
4175  *  Comparison---Returns -1, 0, or +1 depending on whether +int+ is
4176  *  less than, equal to, or greater than +numeric+.
4177  *
4178  *  This is the basis for the tests in the Comparable module.
4179  *
4180  *  +nil+ is returned if the two values are incomparable.
4181  */
4182 
4183 static VALUE
fix_cmp(VALUE x,VALUE y)4184 fix_cmp(VALUE x, VALUE y)
4185 {
4186     if (x == y) return INT2FIX(0);
4187     if (FIXNUM_P(y)) {
4188 	if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4189 	return INT2FIX(-1);
4190     }
4191     else if (RB_TYPE_P(y, T_BIGNUM)) {
4192 	VALUE cmp = rb_big_cmp(y, x);
4193 	switch (cmp) {
4194 	  case INT2FIX(+1): return INT2FIX(-1);
4195 	  case INT2FIX(-1): return INT2FIX(+1);
4196 	}
4197 	return cmp;
4198     }
4199     else if (RB_TYPE_P(y, T_FLOAT)) {
4200 	return rb_integer_float_cmp(x, y);
4201     }
4202     else {
4203 	return rb_num_coerce_cmp(x, y, id_cmp);
4204     }
4205     return rb_num_coerce_cmp(x, y, id_cmp);
4206 }
4207 
4208 VALUE
rb_int_cmp(VALUE x,VALUE y)4209 rb_int_cmp(VALUE x, VALUE y)
4210 {
4211     if (FIXNUM_P(x)) {
4212 	return fix_cmp(x, y);
4213     }
4214     else if (RB_TYPE_P(x, T_BIGNUM)) {
4215 	return rb_big_cmp(x, y);
4216     }
4217     else {
4218 	rb_raise(rb_eNotImpError, "need to define `<=>' in %s", rb_obj_classname(x));
4219     }
4220 }
4221 
4222 /*
4223  * Document-method: Integer#>
4224  * call-seq:
4225  *    int > real  ->  true or false
4226  *
4227  * Returns +true+ if the value of +int+ is greater than that of +real+.
4228  */
4229 
4230 static VALUE
fix_gt(VALUE x,VALUE y)4231 fix_gt(VALUE x, VALUE y)
4232 {
4233     if (FIXNUM_P(y)) {
4234 	if (FIX2LONG(x) > FIX2LONG(y)) return Qtrue;
4235 	return Qfalse;
4236     }
4237     else if (RB_TYPE_P(y, T_BIGNUM)) {
4238 	return rb_big_cmp(y, x) == INT2FIX(-1) ? Qtrue : Qfalse;
4239     }
4240     else if (RB_TYPE_P(y, T_FLOAT)) {
4241         return rb_integer_float_cmp(x, y) == INT2FIX(1) ? Qtrue : Qfalse;
4242     }
4243     else {
4244 	return rb_num_coerce_relop(x, y, '>');
4245     }
4246 }
4247 
4248 VALUE
rb_int_gt(VALUE x,VALUE y)4249 rb_int_gt(VALUE x, VALUE y)
4250 {
4251     if (FIXNUM_P(x)) {
4252 	return fix_gt(x, y);
4253     }
4254     else if (RB_TYPE_P(x, T_BIGNUM)) {
4255 	return rb_big_gt(x, y);
4256     }
4257     return Qnil;
4258 }
4259 
4260 /*
4261  * Document-method: Integer#>=
4262  * call-seq:
4263  *    int >= real  ->  true or false
4264  *
4265  * Returns +true+ if the value of +int+ is greater than or equal to that of
4266  * +real+.
4267  */
4268 
4269 static VALUE
fix_ge(VALUE x,VALUE y)4270 fix_ge(VALUE x, VALUE y)
4271 {
4272     if (FIXNUM_P(y)) {
4273 	if (FIX2LONG(x) >= FIX2LONG(y)) return Qtrue;
4274 	return Qfalse;
4275     }
4276     else if (RB_TYPE_P(y, T_BIGNUM)) {
4277 	return rb_big_cmp(y, x) != INT2FIX(+1) ? Qtrue : Qfalse;
4278     }
4279     else if (RB_TYPE_P(y, T_FLOAT)) {
4280 	VALUE rel = rb_integer_float_cmp(x, y);
4281 	return rel == INT2FIX(1) || rel == INT2FIX(0) ? Qtrue : Qfalse;
4282     }
4283     else {
4284 	return rb_num_coerce_relop(x, y, idGE);
4285     }
4286 }
4287 
4288 VALUE
rb_int_ge(VALUE x,VALUE y)4289 rb_int_ge(VALUE x, VALUE y)
4290 {
4291     if (FIXNUM_P(x)) {
4292 	return fix_ge(x, y);
4293     }
4294     else if (RB_TYPE_P(x, T_BIGNUM)) {
4295 	return rb_big_ge(x, y);
4296     }
4297     return Qnil;
4298 }
4299 
4300 /*
4301  * Document-method: Integer#<
4302  * call-seq:
4303  *    int < real  ->  true or false
4304  *
4305  * Returns +true+ if the value of +int+ is less than that of +real+.
4306  */
4307 
4308 static VALUE
fix_lt(VALUE x,VALUE y)4309 fix_lt(VALUE x, VALUE y)
4310 {
4311     if (FIXNUM_P(y)) {
4312 	if (FIX2LONG(x) < FIX2LONG(y)) return Qtrue;
4313 	return Qfalse;
4314     }
4315     else if (RB_TYPE_P(y, T_BIGNUM)) {
4316 	return rb_big_cmp(y, x) == INT2FIX(+1) ? Qtrue : Qfalse;
4317     }
4318     else if (RB_TYPE_P(y, T_FLOAT)) {
4319         return rb_integer_float_cmp(x, y) == INT2FIX(-1) ? Qtrue : Qfalse;
4320     }
4321     else {
4322 	return rb_num_coerce_relop(x, y, '<');
4323     }
4324 }
4325 
4326 static VALUE
int_lt(VALUE x,VALUE y)4327 int_lt(VALUE x, VALUE y)
4328 {
4329     if (FIXNUM_P(x)) {
4330 	return fix_lt(x, y);
4331     }
4332     else if (RB_TYPE_P(x, T_BIGNUM)) {
4333 	return rb_big_lt(x, y);
4334     }
4335     return Qnil;
4336 }
4337 
4338 /*
4339  * Document-method: Integer#<=
4340  * call-seq:
4341  *    int <= real  ->  true or false
4342  *
4343  * Returns +true+ if the value of +int+ is less than or equal to that of
4344  * +real+.
4345  */
4346 
4347 static VALUE
fix_le(VALUE x,VALUE y)4348 fix_le(VALUE x, VALUE y)
4349 {
4350     if (FIXNUM_P(y)) {
4351 	if (FIX2LONG(x) <= FIX2LONG(y)) return Qtrue;
4352 	return Qfalse;
4353     }
4354     else if (RB_TYPE_P(y, T_BIGNUM)) {
4355 	return rb_big_cmp(y, x) != INT2FIX(-1) ? Qtrue : Qfalse;
4356     }
4357     else if (RB_TYPE_P(y, T_FLOAT)) {
4358 	VALUE rel = rb_integer_float_cmp(x, y);
4359 	return rel == INT2FIX(-1) || rel == INT2FIX(0) ? Qtrue : Qfalse;
4360     }
4361     else {
4362 	return rb_num_coerce_relop(x, y, idLE);
4363     }
4364 }
4365 
4366 static VALUE
int_le(VALUE x,VALUE y)4367 int_le(VALUE x, VALUE y)
4368 {
4369     if (FIXNUM_P(x)) {
4370 	return fix_le(x, y);
4371     }
4372     else if (RB_TYPE_P(x, T_BIGNUM)) {
4373 	return rb_big_le(x, y);
4374     }
4375     return Qnil;
4376 }
4377 
4378 /*
4379  * Document-method: Integer#~
4380  * call-seq:
4381  *   ~int  ->  integer
4382  *
4383  * One's complement: returns a number where each bit is flipped.
4384  *
4385  * Inverts the bits in an Integer. As integers are conceptually of
4386  * infinite length, the result acts as if it had an infinite number of
4387  * one bits to the left. In hex representations, this is displayed
4388  * as two periods to the left of the digits.
4389  *
4390  *   sprintf("%X", ~0x1122334455)    #=> "..FEEDDCCBBAA"
4391  */
4392 
4393 static VALUE
fix_comp(VALUE num)4394 fix_comp(VALUE num)
4395 {
4396     return ~num | FIXNUM_FLAG;
4397 }
4398 
4399 static VALUE
int_comp(VALUE num)4400 int_comp(VALUE num)
4401 {
4402     if (FIXNUM_P(num)) {
4403 	return fix_comp(num);
4404     }
4405     else if (RB_TYPE_P(num, T_BIGNUM)) {
4406 	return rb_big_comp(num);
4407     }
4408     return Qnil;
4409 }
4410 
4411 static VALUE
num_funcall_bit_1(VALUE y,VALUE arg,int recursive)4412 num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
4413 {
4414     ID func = (ID)((VALUE *)arg)[0];
4415     VALUE x = ((VALUE *)arg)[1];
4416     if (recursive) {
4417 	num_funcall_op_1_recursion(x, func, y);
4418     }
4419     return rb_check_funcall(x, func, 1, &y);
4420 }
4421 
4422 VALUE
rb_num_coerce_bit(VALUE x,VALUE y,ID func)4423 rb_num_coerce_bit(VALUE x, VALUE y, ID func)
4424 {
4425     VALUE ret, args[3];
4426 
4427     args[0] = (VALUE)func;
4428     args[1] = x;
4429     args[2] = y;
4430     do_coerce(&args[1], &args[2], TRUE);
4431     ret = rb_exec_recursive_paired(num_funcall_bit_1,
4432 				   args[2], args[1], (VALUE)args);
4433     if (ret == Qundef) {
4434 	/* show the original object, not coerced object */
4435 	coerce_failed(x, y);
4436     }
4437     return ret;
4438 }
4439 
4440 /*
4441  * Document-method: Integer#&
4442  * call-seq:
4443  *   int & other_int  ->  integer
4444  *
4445  * Bitwise AND.
4446  */
4447 
4448 static VALUE
fix_and(VALUE x,VALUE y)4449 fix_and(VALUE x, VALUE y)
4450 {
4451     if (FIXNUM_P(y)) {
4452 	long val = FIX2LONG(x) & FIX2LONG(y);
4453 	return LONG2NUM(val);
4454     }
4455 
4456     if (RB_TYPE_P(y, T_BIGNUM)) {
4457 	return rb_big_and(y, x);
4458     }
4459 
4460     return rb_num_coerce_bit(x, y, '&');
4461 }
4462 
4463 VALUE
rb_int_and(VALUE x,VALUE y)4464 rb_int_and(VALUE x, VALUE y)
4465 {
4466     if (FIXNUM_P(x)) {
4467 	return fix_and(x, y);
4468     }
4469     else if (RB_TYPE_P(x, T_BIGNUM)) {
4470 	return rb_big_and(x, y);
4471     }
4472     return Qnil;
4473 }
4474 
4475 /*
4476  * Document-method: Integer#|
4477  * call-seq:
4478  *   int | other_int  ->  integer
4479  *
4480  * Bitwise OR.
4481  */
4482 
4483 static VALUE
fix_or(VALUE x,VALUE y)4484 fix_or(VALUE x, VALUE y)
4485 {
4486     if (FIXNUM_P(y)) {
4487 	long val = FIX2LONG(x) | FIX2LONG(y);
4488 	return LONG2NUM(val);
4489     }
4490 
4491     if (RB_TYPE_P(y, T_BIGNUM)) {
4492 	return rb_big_or(y, x);
4493     }
4494 
4495     return rb_num_coerce_bit(x, y, '|');
4496 }
4497 
4498 static VALUE
int_or(VALUE x,VALUE y)4499 int_or(VALUE x, VALUE y)
4500 {
4501     if (FIXNUM_P(x)) {
4502 	return fix_or(x, y);
4503     }
4504     else if (RB_TYPE_P(x, T_BIGNUM)) {
4505 	return rb_big_or(x, y);
4506     }
4507     return Qnil;
4508 }
4509 
4510 /*
4511  * Document-method: Integer#^
4512  * call-seq:
4513  *   int ^ other_int  ->  integer
4514  *
4515  * Bitwise EXCLUSIVE OR.
4516  */
4517 
4518 static VALUE
fix_xor(VALUE x,VALUE y)4519 fix_xor(VALUE x, VALUE y)
4520 {
4521     if (FIXNUM_P(y)) {
4522 	long val = FIX2LONG(x) ^ FIX2LONG(y);
4523 	return LONG2NUM(val);
4524     }
4525 
4526     if (RB_TYPE_P(y, T_BIGNUM)) {
4527 	return rb_big_xor(y, x);
4528     }
4529 
4530     return rb_num_coerce_bit(x, y, '^');
4531 }
4532 
4533 static VALUE
int_xor(VALUE x,VALUE y)4534 int_xor(VALUE x, VALUE y)
4535 {
4536     if (FIXNUM_P(x)) {
4537 	return fix_xor(x, y);
4538     }
4539     else if (RB_TYPE_P(x, T_BIGNUM)) {
4540 	return rb_big_xor(x, y);
4541     }
4542     return Qnil;
4543 }
4544 
4545 /*
4546  * Document-method: Integer#<<
4547  * call-seq:
4548  *   int << count  ->  integer
4549  *
4550  * Returns +int+ shifted left +count+ positions, or right if +count+
4551  * is negative.
4552  */
4553 
4554 static VALUE
rb_fix_lshift(VALUE x,VALUE y)4555 rb_fix_lshift(VALUE x, VALUE y)
4556 {
4557     long val, width;
4558 
4559     val = NUM2LONG(x);
4560     if (!FIXNUM_P(y))
4561 	return rb_big_lshift(rb_int2big(val), y);
4562     width = FIX2LONG(y);
4563     if (width < 0)
4564 	return fix_rshift(val, (unsigned long)-width);
4565     return fix_lshift(val, width);
4566 }
4567 
4568 static VALUE
fix_lshift(long val,unsigned long width)4569 fix_lshift(long val, unsigned long width)
4570 {
4571     if (width > (SIZEOF_LONG*CHAR_BIT-1)
4572 	|| ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
4573 	return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
4574     }
4575     val = val << width;
4576     return LONG2NUM(val);
4577 }
4578 
4579 VALUE
rb_int_lshift(VALUE x,VALUE y)4580 rb_int_lshift(VALUE x, VALUE y)
4581 {
4582     if (FIXNUM_P(x)) {
4583 	return rb_fix_lshift(x, y);
4584     }
4585     else if (RB_TYPE_P(x, T_BIGNUM)) {
4586 	return rb_big_lshift(x, y);
4587     }
4588     return Qnil;
4589 }
4590 
4591 /*
4592  * Document-method: Integer#>>
4593  * call-seq:
4594  *   int >> count  ->  integer
4595  *
4596  * Returns +int+ shifted right +count+ positions, or left if +count+
4597  * is negative.
4598  */
4599 
4600 static VALUE
rb_fix_rshift(VALUE x,VALUE y)4601 rb_fix_rshift(VALUE x, VALUE y)
4602 {
4603     long i, val;
4604 
4605     val = FIX2LONG(x);
4606     if (!FIXNUM_P(y))
4607 	return rb_big_rshift(rb_int2big(val), y);
4608     i = FIX2LONG(y);
4609     if (i == 0) return x;
4610     if (i < 0)
4611 	return fix_lshift(val, (unsigned long)-i);
4612     return fix_rshift(val, i);
4613 }
4614 
4615 static VALUE
fix_rshift(long val,unsigned long i)4616 fix_rshift(long val, unsigned long i)
4617 {
4618     if (i >= sizeof(long)*CHAR_BIT-1) {
4619 	if (val < 0) return INT2FIX(-1);
4620 	return INT2FIX(0);
4621     }
4622     val = RSHIFT(val, i);
4623     return LONG2FIX(val);
4624 }
4625 
4626 static VALUE
rb_int_rshift(VALUE x,VALUE y)4627 rb_int_rshift(VALUE x, VALUE y)
4628 {
4629     if (FIXNUM_P(x)) {
4630 	return rb_fix_rshift(x, y);
4631     }
4632     else if (RB_TYPE_P(x, T_BIGNUM)) {
4633 	return rb_big_rshift(x, y);
4634     }
4635     return Qnil;
4636 }
4637 
4638 /*
4639  *  Document-method: Integer#[]
4640  *  call-seq:
4641  *     int[n]  ->  0, 1
4642  *
4643  *  Bit Reference---Returns the <code>n</code>th bit in the
4644  *  binary representation of +int+, where <code>int[0]</code>
4645  *  is the least significant bit.
4646  *
4647  *     a = 0b11001100101010
4648  *     30.downto(0) {|n| print a[n] }
4649  *     #=> 0000000000000000011001100101010
4650  *
4651  *     a = 9**15
4652  *     50.downto(0) {|n| print a[n] }
4653  *     #=> 000101110110100000111000011110010100111100010111001
4654  */
4655 
4656 static VALUE
fix_aref(VALUE fix,VALUE idx)4657 fix_aref(VALUE fix, VALUE idx)
4658 {
4659     long val = FIX2LONG(fix);
4660     long i;
4661 
4662     idx = rb_to_int(idx);
4663     if (!FIXNUM_P(idx)) {
4664 	idx = rb_big_norm(idx);
4665 	if (!FIXNUM_P(idx)) {
4666 	    if (!BIGNUM_SIGN(idx) || val >= 0)
4667 		return INT2FIX(0);
4668 	    return INT2FIX(1);
4669 	}
4670     }
4671     i = FIX2LONG(idx);
4672 
4673     if (i < 0) return INT2FIX(0);
4674     if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
4675 	if (val < 0) return INT2FIX(1);
4676 	return INT2FIX(0);
4677     }
4678     if (val & (1L<<i))
4679 	return INT2FIX(1);
4680     return INT2FIX(0);
4681 }
4682 
4683 static VALUE
int_aref(VALUE num,VALUE idx)4684 int_aref(VALUE num, VALUE idx)
4685 {
4686     if (FIXNUM_P(num)) {
4687 	return fix_aref(num, idx);
4688     }
4689     else if (RB_TYPE_P(num, T_BIGNUM)) {
4690 	return rb_big_aref(num, idx);
4691     }
4692     return Qnil;
4693 }
4694 
4695 /*
4696  *  Document-method: Integer#to_f
4697  *  call-seq:
4698  *     int.to_f  ->  float
4699  *
4700  *  Converts +int+ to a Float.  If +int+ doesn't fit in a Float,
4701  *  the result is infinity.
4702  */
4703 
4704 static VALUE
int_to_f(VALUE num)4705 int_to_f(VALUE num)
4706 {
4707     double val;
4708 
4709     if (FIXNUM_P(num)) {
4710 	val = (double)FIX2LONG(num);
4711     }
4712     else if (RB_TYPE_P(num, T_BIGNUM)) {
4713 	val = rb_big2dbl(num);
4714     }
4715     else {
4716 	rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
4717     }
4718 
4719     return DBL2NUM(val);
4720 }
4721 
4722 /*
4723  *  Document-method: Integer#abs
4724  *  Document-method: Integer#magnitude
4725  *  call-seq:
4726  *     int.abs        ->  integer
4727  *     int.magnitude  ->  integer
4728  *
4729  *  Returns the absolute value of +int+.
4730  *
4731  *     (-12345).abs   #=> 12345
4732  *     -12345.abs     #=> 12345
4733  *     12345.abs      #=> 12345
4734  *
4735  *  Integer#magnitude is an alias for Integer#abs.
4736  */
4737 
4738 static VALUE
fix_abs(VALUE fix)4739 fix_abs(VALUE fix)
4740 {
4741     long i = FIX2LONG(fix);
4742 
4743     if (i < 0) i = -i;
4744 
4745     return LONG2NUM(i);
4746 }
4747 
4748 VALUE
rb_int_abs(VALUE num)4749 rb_int_abs(VALUE num)
4750 {
4751     if (FIXNUM_P(num)) {
4752 	return fix_abs(num);
4753     }
4754     else if (RB_TYPE_P(num, T_BIGNUM)) {
4755 	return rb_big_abs(num);
4756     }
4757     return Qnil;
4758 }
4759 
4760 /*
4761  *  Document-method: Integer#size
4762  *  call-seq:
4763  *     int.size  ->  int
4764  *
4765  *  Returns the number of bytes in the machine representation of +int+
4766  *  (machine dependent).
4767  *
4768  *     1.size               #=> 8
4769  *     -1.size              #=> 8
4770  *     2147483647.size      #=> 8
4771  *     (256**10 - 1).size   #=> 10
4772  *     (256**20 - 1).size   #=> 20
4773  *     (256**40 - 1).size   #=> 40
4774  */
4775 
4776 static VALUE
fix_size(VALUE fix)4777 fix_size(VALUE fix)
4778 {
4779     return INT2FIX(sizeof(long));
4780 }
4781 
4782 static VALUE
int_size(VALUE num)4783 int_size(VALUE num)
4784 {
4785     if (FIXNUM_P(num)) {
4786 	return fix_size(num);
4787     }
4788     else if (RB_TYPE_P(num, T_BIGNUM)) {
4789 	return rb_big_size_m(num);
4790     }
4791     return Qnil;
4792 }
4793 
4794 /*
4795  *  Document-method: Integer#bit_length
4796  *  call-seq:
4797  *     int.bit_length  ->  integer
4798  *
4799  *  Returns the number of bits of the value of +int+.
4800  *
4801  *  "Number of bits" means the bit position of the highest bit
4802  *  which is different from the sign bit
4803  *  (where the least significant bit has bit position 1).
4804  *  If there is no such bit (zero or minus one), zero is returned.
4805  *
4806  *  I.e. this method returns <i>ceil(log2(int < 0 ? -int : int+1))</i>.
4807  *
4808  *     (-2**1000-1).bit_length   #=> 1001
4809  *     (-2**1000).bit_length     #=> 1000
4810  *     (-2**1000+1).bit_length   #=> 1000
4811  *     (-2**12-1).bit_length     #=> 13
4812  *     (-2**12).bit_length       #=> 12
4813  *     (-2**12+1).bit_length     #=> 12
4814  *     -0x101.bit_length         #=> 9
4815  *     -0x100.bit_length         #=> 8
4816  *     -0xff.bit_length          #=> 8
4817  *     -2.bit_length             #=> 1
4818  *     -1.bit_length             #=> 0
4819  *     0.bit_length              #=> 0
4820  *     1.bit_length              #=> 1
4821  *     0xff.bit_length           #=> 8
4822  *     0x100.bit_length          #=> 9
4823  *     (2**12-1).bit_length      #=> 12
4824  *     (2**12).bit_length        #=> 13
4825  *     (2**12+1).bit_length      #=> 13
4826  *     (2**1000-1).bit_length    #=> 1000
4827  *     (2**1000).bit_length      #=> 1001
4828  *     (2**1000+1).bit_length    #=> 1001
4829  *
4830  *  This method can be used to detect overflow in Array#pack as follows:
4831  *
4832  *     if n.bit_length < 32
4833  *       [n].pack("l") # no overflow
4834  *     else
4835  *       raise "overflow"
4836  *     end
4837  */
4838 
4839 static VALUE
rb_fix_bit_length(VALUE fix)4840 rb_fix_bit_length(VALUE fix)
4841 {
4842     long v = FIX2LONG(fix);
4843     if (v < 0)
4844         v = ~v;
4845     return LONG2FIX(bit_length(v));
4846 }
4847 
4848 static VALUE
rb_int_bit_length(VALUE num)4849 rb_int_bit_length(VALUE num)
4850 {
4851     if (FIXNUM_P(num)) {
4852 	return rb_fix_bit_length(num);
4853     }
4854     else if (RB_TYPE_P(num, T_BIGNUM)) {
4855 	return rb_big_bit_length(num);
4856     }
4857     return Qnil;
4858 }
4859 
4860 /*
4861  *  Document-method: Integer#digits
4862  *  call-seq:
4863  *     int.digits        ->  array
4864  *     int.digits(base)  ->  array
4865  *
4866  *  Returns the digits of +int+'s place-value representation
4867  *  with radix +base+ (default: 10).
4868  *  The digits are returned as an array with the least significant digit
4869  *  as the first array element.
4870  *
4871  *  +base+ must be greater than or equal to 2.
4872  *
4873  *     12345.digits      #=> [5, 4, 3, 2, 1]
4874  *     12345.digits(7)   #=> [4, 6, 6, 0, 5]
4875  *     12345.digits(100) #=> [45, 23, 1]
4876  *
4877  *     -12345.digits(7)  #=> Math::DomainError
4878  */
4879 
4880 static VALUE
rb_fix_digits(VALUE fix,long base)4881 rb_fix_digits(VALUE fix, long base)
4882 {
4883     VALUE digits;
4884     long x = FIX2LONG(fix);
4885 
4886     assert(x >= 0);
4887 
4888     if (base < 2)
4889         rb_raise(rb_eArgError, "invalid radix %ld", base);
4890 
4891     if (x == 0)
4892         return rb_ary_new_from_args(1, INT2FIX(0));
4893 
4894     digits = rb_ary_new();
4895     while (x > 0) {
4896         long q = x % base;
4897         rb_ary_push(digits, LONG2NUM(q));
4898         x /= base;
4899     }
4900 
4901     return digits;
4902 }
4903 
4904 static VALUE
rb_int_digits_bigbase(VALUE num,VALUE base)4905 rb_int_digits_bigbase(VALUE num, VALUE base)
4906 {
4907     VALUE digits;
4908 
4909     assert(!rb_num_negative_p(num));
4910 
4911     if (RB_TYPE_P(base, T_BIGNUM))
4912         base = rb_big_norm(base);
4913 
4914     if (FIXNUM_P(base) && FIX2LONG(base) < 2)
4915         rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
4916     else if (RB_TYPE_P(base, T_BIGNUM) && BIGNUM_NEGATIVE_P(base))
4917         rb_raise(rb_eArgError, "negative radix");
4918 
4919     if (FIXNUM_P(base) && FIXNUM_P(num))
4920         return rb_fix_digits(num, FIX2LONG(base));
4921 
4922     if (FIXNUM_P(num))
4923         return rb_ary_new_from_args(1, num);
4924 
4925     digits = rb_ary_new();
4926     while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
4927         VALUE qr = rb_int_divmod(num, base);
4928         rb_ary_push(digits, RARRAY_AREF(qr, 1));
4929         num = RARRAY_AREF(qr, 0);
4930     }
4931 
4932     return digits;
4933 }
4934 
4935 static VALUE
rb_int_digits(int argc,VALUE * argv,VALUE num)4936 rb_int_digits(int argc, VALUE *argv, VALUE num)
4937 {
4938     VALUE base_value;
4939     long base;
4940 
4941     if (rb_num_negative_p(num))
4942         rb_raise(rb_eMathDomainError, "out of domain");
4943 
4944     if (rb_check_arity(argc, 0, 1)) {
4945         base_value = rb_to_int(argv[0]);
4946         if (!RB_INTEGER_TYPE_P(base_value))
4947             rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
4948                      rb_obj_classname(argv[0]));
4949         if (RB_TYPE_P(base_value, T_BIGNUM))
4950             return rb_int_digits_bigbase(num, base_value);
4951 
4952         base = FIX2LONG(base_value);
4953         if (base < 0)
4954             rb_raise(rb_eArgError, "negative radix");
4955         else if (base < 2)
4956             rb_raise(rb_eArgError, "invalid radix %ld", base);
4957     }
4958     else
4959         base = 10;
4960 
4961     if (FIXNUM_P(num))
4962         return rb_fix_digits(num, base);
4963     else if (RB_TYPE_P(num, T_BIGNUM))
4964         return rb_int_digits_bigbase(num, LONG2FIX(base));
4965 
4966     return Qnil;
4967 }
4968 
4969 /*
4970  *  Document-method: Integer#upto
4971  *  call-seq:
4972  *     int.upto(limit) {|i| block }  ->  self
4973  *     int.upto(limit)               ->  an_enumerator
4974  *
4975  *  Iterates the given block, passing in integer values from +int+ up to and
4976  *  including +limit+.
4977  *
4978  *  If no block is given, an Enumerator is returned instead.
4979  *
4980  *     5.upto(10) {|i| print i, " " }   #=> 5 6 7 8 9 10
4981  */
4982 
4983 static VALUE
int_upto_size(VALUE from,VALUE args,VALUE eobj)4984 int_upto_size(VALUE from, VALUE args, VALUE eobj)
4985 {
4986     return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
4987 }
4988 
4989 static VALUE
int_upto(VALUE from,VALUE to)4990 int_upto(VALUE from, VALUE to)
4991 {
4992     RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
4993     if (FIXNUM_P(from) && FIXNUM_P(to)) {
4994 	long i, end;
4995 
4996 	end = FIX2LONG(to);
4997 	for (i = FIX2LONG(from); i <= end; i++) {
4998 	    rb_yield(LONG2FIX(i));
4999 	}
5000     }
5001     else {
5002 	VALUE i = from, c;
5003 
5004 	while (!(c = rb_funcall(i, '>', 1, to))) {
5005 	    rb_yield(i);
5006 	    i = rb_funcall(i, '+', 1, INT2FIX(1));
5007 	}
5008 	if (NIL_P(c)) rb_cmperr(i, to);
5009     }
5010     return from;
5011 }
5012 
5013 /*
5014  *  Document-method: Integer#downto
5015  *  call-seq:
5016  *     int.downto(limit) {|i| block }  ->  self
5017  *     int.downto(limit)               ->  an_enumerator
5018  *
5019  *  Iterates the given block, passing in decreasing values from +int+ down to
5020  *  and including +limit+.
5021  *
5022  *  If no block is given, an Enumerator is returned instead.
5023  *
5024  *     5.downto(1) { |n| print n, ".. " }
5025  *     puts "Liftoff!"
5026  *     #=> "5.. 4.. 3.. 2.. 1.. Liftoff!"
5027  */
5028 
5029 static VALUE
int_downto_size(VALUE from,VALUE args,VALUE eobj)5030 int_downto_size(VALUE from, VALUE args, VALUE eobj)
5031 {
5032     return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5033 }
5034 
5035 static VALUE
int_downto(VALUE from,VALUE to)5036 int_downto(VALUE from, VALUE to)
5037 {
5038     RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5039     if (FIXNUM_P(from) && FIXNUM_P(to)) {
5040 	long i, end;
5041 
5042 	end = FIX2LONG(to);
5043 	for (i=FIX2LONG(from); i >= end; i--) {
5044 	    rb_yield(LONG2FIX(i));
5045 	}
5046     }
5047     else {
5048 	VALUE i = from, c;
5049 
5050 	while (!(c = rb_funcall(i, '<', 1, to))) {
5051 	    rb_yield(i);
5052 	    i = rb_funcall(i, '-', 1, INT2FIX(1));
5053 	}
5054 	if (NIL_P(c)) rb_cmperr(i, to);
5055     }
5056     return from;
5057 }
5058 
5059 /*
5060  *  Document-method: Integer#times
5061  *  call-seq:
5062  *     int.times {|i| block }  ->  self
5063  *     int.times               ->  an_enumerator
5064  *
5065  *  Iterates the given block +int+ times, passing in values from zero to
5066  *  <code>int - 1</code>.
5067  *
5068  *  If no block is given, an Enumerator is returned instead.
5069  *
5070  *     5.times {|i| print i, " " }   #=> 0 1 2 3 4
5071  */
5072 
5073 static VALUE
int_dotimes_size(VALUE num,VALUE args,VALUE eobj)5074 int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5075 {
5076     if (FIXNUM_P(num)) {
5077 	if (NUM2LONG(num) <= 0) return INT2FIX(0);
5078     }
5079     else {
5080 	if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) return INT2FIX(0);
5081     }
5082     return num;
5083 }
5084 
5085 static VALUE
int_dotimes(VALUE num)5086 int_dotimes(VALUE num)
5087 {
5088     RETURN_SIZED_ENUMERATOR(num, 0, 0, int_dotimes_size);
5089 
5090     if (FIXNUM_P(num)) {
5091 	long i, end;
5092 
5093 	end = FIX2LONG(num);
5094 	for (i=0; i<end; i++) {
5095 	    rb_yield_1(LONG2FIX(i));
5096 	}
5097     }
5098     else {
5099 	VALUE i = INT2FIX(0);
5100 
5101 	for (;;) {
5102 	    if (!RTEST(rb_funcall(i, '<', 1, num))) break;
5103 	    rb_yield(i);
5104 	    i = rb_funcall(i, '+', 1, INT2FIX(1));
5105 	}
5106     }
5107     return num;
5108 }
5109 
5110 /*
5111  *  Document-method: Integer#round
5112  *  call-seq:
5113  *     int.round([ndigits] [, half: mode])  ->  integer or float
5114  *
5115  *  Returns +int+ rounded to the nearest value with
5116  *  a precision of +ndigits+ decimal digits (default: 0).
5117  *
5118  *  When the precision is negative, the returned value is an integer
5119  *  with at least <code>ndigits.abs</code> trailing zeros.
5120  *
5121  *  Returns +self+ when +ndigits+ is zero or positive.
5122  *
5123  *     1.round           #=> 1
5124  *     1.round(2)        #=> 1
5125  *     15.round(-1)      #=> 20
5126  *     (-15).round(-1)   #=> -20
5127  *
5128  *  The optional +half+ keyword argument is available
5129  *  similar to Float#round.
5130  *
5131  *     25.round(-1, half: :up)      #=> 30
5132  *     25.round(-1, half: :down)    #=> 20
5133  *     25.round(-1, half: :even)    #=> 20
5134  *     35.round(-1, half: :up)      #=> 40
5135  *     35.round(-1, half: :down)    #=> 30
5136  *     35.round(-1, half: :even)    #=> 40
5137  *     (-25).round(-1, half: :up)   #=> -30
5138  *     (-25).round(-1, half: :down) #=> -20
5139  *     (-25).round(-1, half: :even) #=> -20
5140  */
5141 
5142 static VALUE
int_round(int argc,VALUE * argv,VALUE num)5143 int_round(int argc, VALUE* argv, VALUE num)
5144 {
5145     int ndigits;
5146     int mode;
5147     VALUE nd, opt;
5148 
5149     if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5150     ndigits = NUM2INT(nd);
5151     mode = rb_num_get_rounding_option(opt);
5152     if (ndigits >= 0) {
5153 	return num;
5154     }
5155     return rb_int_round(num, ndigits, mode);
5156 }
5157 
5158 /*
5159  *  Document-method: Integer#floor
5160  *  call-seq:
5161  *     int.floor([ndigits])  ->  integer or float
5162  *
5163  *  Returns the largest number less than or equal to +int+ with
5164  *  a precision of +ndigits+ decimal digits (default: 0).
5165  *
5166  *  When the precision is negative, the returned value is an integer
5167  *  with at least <code>ndigits.abs</code> trailing zeros.
5168  *
5169  *  Returns +self+ when +ndigits+ is zero or positive.
5170  *
5171  *     1.floor           #=> 1
5172  *     1.floor(2)        #=> 1
5173  *     18.floor(-1)      #=> 10
5174  *     (-18).floor(-1)   #=> -20
5175  */
5176 
5177 static VALUE
int_floor(int argc,VALUE * argv,VALUE num)5178 int_floor(int argc, VALUE* argv, VALUE num)
5179 {
5180     int ndigits;
5181 
5182     if (!rb_check_arity(argc, 0, 1)) return num;
5183     ndigits = NUM2INT(argv[0]);
5184     if (ndigits >= 0) {
5185 	return num;
5186     }
5187     return rb_int_floor(num, ndigits);
5188 }
5189 
5190 /*
5191  *  Document-method: Integer#ceil
5192  *  call-seq:
5193  *     int.ceil([ndigits])  ->  integer or float
5194  *
5195  *  Returns the smallest number greater than or equal to +int+ with
5196  *  a precision of +ndigits+ decimal digits (default: 0).
5197  *
5198  *  When the precision is negative, the returned value is an integer
5199  *  with at least <code>ndigits.abs</code> trailing zeros.
5200  *
5201  *  Returns +self+ when +ndigits+ is zero or positive.
5202  *
5203  *     1.ceil           #=> 1
5204  *     1.ceil(2)        #=> 1
5205  *     18.ceil(-1)      #=> 20
5206  *     (-18).ceil(-1)   #=> -10
5207  */
5208 
5209 static VALUE
int_ceil(int argc,VALUE * argv,VALUE num)5210 int_ceil(int argc, VALUE* argv, VALUE num)
5211 {
5212     int ndigits;
5213 
5214     if (!rb_check_arity(argc, 0, 1)) return num;
5215     ndigits = NUM2INT(argv[0]);
5216     if (ndigits >= 0) {
5217 	return num;
5218     }
5219     return rb_int_ceil(num, ndigits);
5220 }
5221 
5222 /*
5223  *  Document-method: Integer#truncate
5224  *  call-seq:
5225  *     int.truncate([ndigits])  ->  integer or float
5226  *
5227  *  Returns +int+ truncated (toward zero) to
5228  *  a precision of +ndigits+ decimal digits (default: 0).
5229  *
5230  *  When the precision is negative, the returned value is an integer
5231  *  with at least <code>ndigits.abs</code> trailing zeros.
5232  *
5233  *  Returns +self+ when +ndigits+ is zero or positive.
5234  *
5235  *     1.truncate           #=> 1
5236  *     1.truncate(2)        #=> 1
5237  *     18.truncate(-1)      #=> 10
5238  *     (-18).truncate(-1)   #=> -10
5239  */
5240 
5241 static VALUE
int_truncate(int argc,VALUE * argv,VALUE num)5242 int_truncate(int argc, VALUE* argv, VALUE num)
5243 {
5244     int ndigits;
5245 
5246     if (!rb_check_arity(argc, 0, 1)) return num;
5247     ndigits = NUM2INT(argv[0]);
5248     if (ndigits >= 0) {
5249 	return num;
5250     }
5251     return rb_int_truncate(num, ndigits);
5252 }
5253 
5254 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5255 rettype \
5256 prefix##_isqrt(argtype n) \
5257 { \
5258     if (!argtype##_IN_DOUBLE_P(n)) { \
5259 	unsigned int b = bit_length(n); \
5260 	argtype t; \
5261 	rettype x = (rettype)(n >> (b/2+1)); \
5262 	x |= ((rettype)1LU << (b-1)/2); \
5263 	while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5264 	return x; \
5265     } \
5266     return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5267 }
5268 
5269 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5270 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5271 #else
5272 # define RB_ULONG_IN_DOUBLE_P(n) 1
5273 #endif
5274 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5275 #define RB_ULONG unsigned long
5276 DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5277 
5278 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5279 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5280 #   define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5281 # else
5282 #   define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5283 # endif
5284 # ifdef ULL_TO_DOUBLE
5285 #   define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
5286 # else
5287 #   define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
5288 # endif
5289 DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
5290 #endif
5291 
5292 #define domain_error(msg) \
5293     rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
5294 
5295 VALUE rb_big_isqrt(VALUE);
5296 
5297 /*
5298  *  Document-method: Integer::sqrt
5299  *  call-seq:
5300  *     Integer.sqrt(n)  ->  integer
5301  *
5302  *  Returns the integer square root of the non-negative integer +n+,
5303  *  i.e. the largest non-negative integer less than or equal to the
5304  *  square root of +n+.
5305  *
5306  *    Integer.sqrt(0)        #=> 0
5307  *    Integer.sqrt(1)        #=> 1
5308  *    Integer.sqrt(24)       #=> 4
5309  *    Integer.sqrt(25)       #=> 5
5310  *    Integer.sqrt(10**400)  #=> 10**200
5311  *
5312  *  Equivalent to <code>Math.sqrt(n).floor</code>, except that
5313  *  the result of the latter code may differ from the true value
5314  *  due to the limited precision of floating point arithmetic.
5315  *
5316  *    Integer.sqrt(10**46)     #=> 100000000000000000000000
5317  *    Math.sqrt(10**46).floor  #=>  99999999999999991611392 (!)
5318  *
5319  *  If +n+ is not an Integer, it is converted to an Integer first.
5320  *  If +n+ is negative, a Math::DomainError is raised.
5321  */
5322 
5323 static VALUE
rb_int_s_isqrt(VALUE self,VALUE num)5324 rb_int_s_isqrt(VALUE self, VALUE num)
5325 {
5326     unsigned long n, sq;
5327     num = rb_to_int(num);
5328     if (FIXNUM_P(num)) {
5329 	if (FIXNUM_NEGATIVE_P(num)) {
5330 	    domain_error("isqrt");
5331 	}
5332 	n = FIX2ULONG(num);
5333 	sq = rb_ulong_isqrt(n);
5334 	return LONG2FIX(sq);
5335     }
5336     else {
5337 	size_t biglen;
5338 	if (RBIGNUM_NEGATIVE_P(num)) {
5339 	    domain_error("isqrt");
5340 	}
5341 	biglen = BIGNUM_LEN(num);
5342 	if (biglen == 0) return INT2FIX(0);
5343 #if SIZEOF_BDIGIT <= SIZEOF_LONG
5344 	/* short-circuit */
5345 	if (biglen == 1) {
5346 	    n = BIGNUM_DIGITS(num)[0];
5347 	    sq = rb_ulong_isqrt(n);
5348 	    return ULONG2NUM(sq);
5349 	}
5350 #endif
5351 	return rb_big_isqrt(num);
5352     }
5353 }
5354 
5355 /*
5356  *  Document-class: ZeroDivisionError
5357  *
5358  *  Raised when attempting to divide an integer by 0.
5359  *
5360  *     42 / 0   #=> ZeroDivisionError: divided by 0
5361  *
5362  *  Note that only division by an exact 0 will raise the exception:
5363  *
5364  *     42 /  0.0   #=> Float::INFINITY
5365  *     42 / -0.0   #=> -Float::INFINITY
5366  *     0  /  0.0   #=> NaN
5367  */
5368 
5369 /*
5370  *  Document-class: FloatDomainError
5371  *
5372  *  Raised when attempting to convert special float values (in particular
5373  *  +Infinity+ or +NaN+) to numerical classes which don't support them.
5374  *
5375  *     Float::INFINITY.to_r   #=> FloatDomainError: Infinity
5376  */
5377 
5378 /*
5379  * Document-class: Numeric
5380  *
5381  * Numeric is the class from which all higher-level numeric classes should inherit.
5382  *
5383  * Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
5384  * Integer are implemented as immediates, which means that each Integer is a single immutable
5385  * object which is always passed by value.
5386  *
5387  *   a = 1
5388  *   1.object_id == a.object_id   #=> true
5389  *
5390  * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
5391  * by preventing instantiation. If duplication is attempted, the same instance is returned.
5392  *
5393  *   Integer.new(1)                   #=> NoMethodError: undefined method `new' for Integer:Class
5394  *   1.dup                            #=> 1
5395  *   1.object_id == 1.dup.object_id   #=> true
5396  *
5397  * For this reason, Numeric should be used when defining other numeric classes.
5398  *
5399  * Classes which inherit from Numeric must implement +coerce+, which returns a two-member
5400  * Array containing an object that has been coerced into an instance of the new class
5401  * and +self+ (see #coerce).
5402  *
5403  * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
5404  * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
5405  * Comparable). These methods may rely on +coerce+ to ensure interoperability with
5406  * instances of other numeric classes.
5407  *
5408  *   class Tally < Numeric
5409  *     def initialize(string)
5410  *       @string = string
5411  *     end
5412  *
5413  *     def to_s
5414  *       @string
5415  *     end
5416  *
5417  *     def to_i
5418  *       @string.size
5419  *     end
5420  *
5421  *     def coerce(other)
5422  *       [self.class.new('|' * other.to_i), self]
5423  *     end
5424  *
5425  *     def <=>(other)
5426  *       to_i <=> other.to_i
5427  *     end
5428  *
5429  *     def +(other)
5430  *       self.class.new('|' * (to_i + other.to_i))
5431  *     end
5432  *
5433  *     def -(other)
5434  *       self.class.new('|' * (to_i - other.to_i))
5435  *     end
5436  *
5437  *     def *(other)
5438  *       self.class.new('|' * (to_i * other.to_i))
5439  *     end
5440  *
5441  *     def /(other)
5442  *       self.class.new('|' * (to_i / other.to_i))
5443  *     end
5444  *   end
5445  *
5446  *   tally = Tally.new('||')
5447  *   puts tally * 2            #=> "||||"
5448  *   puts tally > 1            #=> true
5449  */
5450 void
Init_Numeric(void)5451 Init_Numeric(void)
5452 {
5453 #undef rb_intern
5454 #define rb_intern(str) rb_intern_const(str)
5455 
5456 #ifdef _UNICOSMP
5457     /* Turn off floating point exceptions for divide by zero, etc. */
5458     _set_Creg(0, 0);
5459 #endif
5460     id_coerce = rb_intern("coerce");
5461     id_div = rb_intern("div");
5462     id_divmod = rb_intern("divmod");
5463 
5464     rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
5465     rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
5466     rb_cNumeric = rb_define_class("Numeric", rb_cObject);
5467 
5468     rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
5469     rb_include_module(rb_cNumeric, rb_mComparable);
5470     rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
5471     rb_define_method(rb_cNumeric, "clone", num_clone, -1);
5472     rb_define_method(rb_cNumeric, "dup", num_dup, 0);
5473 
5474     rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
5475     rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
5476     rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
5477     rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
5478     rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
5479     rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
5480     rb_define_method(rb_cNumeric, "div", num_div, 1);
5481     rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
5482     rb_define_method(rb_cNumeric, "%", num_modulo, 1);
5483     rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
5484     rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
5485     rb_define_method(rb_cNumeric, "abs", num_abs, 0);
5486     rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
5487     rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
5488 
5489     rb_define_method(rb_cNumeric, "real?", num_real_p, 0);
5490     rb_define_method(rb_cNumeric, "integer?", num_int_p, 0);
5491     rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
5492     rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
5493     rb_define_method(rb_cNumeric, "finite?", num_finite_p, 0);
5494     rb_define_method(rb_cNumeric, "infinite?", num_infinite_p, 0);
5495 
5496     rb_define_method(rb_cNumeric, "floor", num_floor, -1);
5497     rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
5498     rb_define_method(rb_cNumeric, "round", num_round, -1);
5499     rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
5500     rb_define_method(rb_cNumeric, "step", num_step, -1);
5501     rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
5502     rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
5503 
5504     rb_cInteger = rb_define_class("Integer", rb_cNumeric);
5505     rb_undef_alloc_func(rb_cInteger);
5506     rb_undef_method(CLASS_OF(rb_cInteger), "new");
5507     rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
5508 
5509     rb_define_method(rb_cInteger, "to_s", int_to_s, -1);
5510     rb_define_alias(rb_cInteger, "inspect", "to_s");
5511     rb_define_method(rb_cInteger, "integer?", int_int_p, 0);
5512     rb_define_method(rb_cInteger, "odd?", rb_int_odd_p, 0);
5513     rb_define_method(rb_cInteger, "even?", int_even_p, 0);
5514     rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
5515     rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
5516     rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
5517     rb_define_method(rb_cInteger, "upto", int_upto, 1);
5518     rb_define_method(rb_cInteger, "downto", int_downto, 1);
5519     rb_define_method(rb_cInteger, "times", int_dotimes, 0);
5520     rb_define_method(rb_cInteger, "succ", int_succ, 0);
5521     rb_define_method(rb_cInteger, "next", int_succ, 0);
5522     rb_define_method(rb_cInteger, "pred", int_pred, 0);
5523     rb_define_method(rb_cInteger, "chr", int_chr, -1);
5524     rb_define_method(rb_cInteger, "ord", int_ord, 0);
5525     rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
5526     rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
5527     rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
5528     rb_define_method(rb_cInteger, "floor", int_floor, -1);
5529     rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
5530     rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
5531     rb_define_method(rb_cInteger, "round", int_round, -1);
5532     rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
5533 
5534     rb_define_method(rb_cInteger, "-@", rb_int_uminus, 0);
5535     rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
5536     rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
5537     rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
5538     rb_define_method(rb_cInteger, "/", rb_int_div, 1);
5539     rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
5540     rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
5541     rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
5542     rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
5543     rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
5544     rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
5545     rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
5546 
5547     rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
5548 
5549     rb_define_method(rb_cInteger, "abs", rb_int_abs, 0);
5550     rb_define_method(rb_cInteger, "magnitude", rb_int_abs, 0);
5551 
5552     rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
5553     rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
5554     rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
5555     rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
5556     rb_define_method(rb_cInteger, "<", int_lt, 1);
5557     rb_define_method(rb_cInteger, "<=", int_le, 1);
5558 
5559     rb_define_method(rb_cInteger, "~", int_comp, 0);
5560     rb_define_method(rb_cInteger, "&", rb_int_and, 1);
5561     rb_define_method(rb_cInteger, "|", int_or,  1);
5562     rb_define_method(rb_cInteger, "^", int_xor, 1);
5563     rb_define_method(rb_cInteger, "[]", int_aref, 1);
5564 
5565     rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
5566     rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
5567 
5568     rb_define_method(rb_cInteger, "size", int_size, 0);
5569     rb_define_method(rb_cInteger, "bit_length", rb_int_bit_length, 0);
5570     rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
5571 
5572 #ifndef RUBY_INTEGER_UNIFICATION
5573     rb_cFixnum = rb_cInteger;
5574 #endif
5575     /* An obsolete class, use Integer */
5576     rb_define_const(rb_cObject, "Fixnum", rb_cInteger);
5577     rb_deprecate_constant(rb_cObject, "Fixnum");
5578 
5579     rb_cFloat  = rb_define_class("Float", rb_cNumeric);
5580 
5581     rb_undef_alloc_func(rb_cFloat);
5582     rb_undef_method(CLASS_OF(rb_cFloat), "new");
5583 
5584     /*
5585      *  Represents the rounding mode for floating point addition.
5586      *
5587      *  Usually defaults to 1, rounding to the nearest number.
5588      *
5589      *  Other modes include:
5590      *
5591      *  -1::	Indeterminable
5592      *	0::	Rounding towards zero
5593      *	1::	Rounding to the nearest number
5594      *	2::	Rounding towards positive infinity
5595      *	3::	Rounding towards negative infinity
5596      */
5597     rb_define_const(rb_cFloat, "ROUNDS", INT2FIX(FLT_ROUNDS));
5598     /*
5599      *	The base of the floating point, or number of unique digits used to
5600      *	represent the number.
5601      *
5602      *  Usually defaults to 2 on most systems, which would represent a base-10 decimal.
5603      */
5604     rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
5605     /*
5606      * The number of base digits for the +double+ data type.
5607      *
5608      * Usually defaults to 53.
5609      */
5610     rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
5611     /*
5612      *	The minimum number of significant decimal digits in a double-precision
5613      *	floating point.
5614      *
5615      *	Usually defaults to 15.
5616      */
5617     rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
5618     /*
5619      *	The smallest possible exponent value in a double-precision floating
5620      *	point.
5621      *
5622      *	Usually defaults to -1021.
5623      */
5624     rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
5625     /*
5626      *	The largest possible exponent value in a double-precision floating
5627      *	point.
5628      *
5629      *	Usually defaults to 1024.
5630      */
5631     rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
5632     /*
5633      *	The smallest negative exponent in a double-precision floating point
5634      *	where 10 raised to this power minus 1.
5635      *
5636      *	Usually defaults to -307.
5637      */
5638     rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
5639     /*
5640      *	The largest positive exponent in a double-precision floating point where
5641      *	10 raised to this power minus 1.
5642      *
5643      *	Usually defaults to 308.
5644      */
5645     rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
5646     /*
5647      *	The smallest positive normalized number in a double-precision floating point.
5648      *
5649      *	Usually defaults to 2.2250738585072014e-308.
5650      *
5651      *	If the platform supports denormalized numbers,
5652      *	there are numbers between zero and Float::MIN.
5653      *	0.0.next_float returns the smallest positive floating point number
5654      *	including denormalized numbers.
5655      */
5656     rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
5657     /*
5658      *	The largest possible integer in a double-precision floating point number.
5659      *
5660      *	Usually defaults to 1.7976931348623157e+308.
5661      */
5662     rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
5663     /*
5664      *	The difference between 1 and the smallest double-precision floating
5665      *	point number greater than 1.
5666      *
5667      *	Usually defaults to 2.2204460492503131e-16.
5668      */
5669     rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
5670     /*
5671      *	An expression representing positive infinity.
5672      */
5673     rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
5674     /*
5675      *	An expression representing a value which is "not a number".
5676      */
5677     rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
5678 
5679     rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
5680     rb_define_alias(rb_cFloat, "inspect", "to_s");
5681     rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
5682     rb_define_method(rb_cFloat, "-@", rb_float_uminus, 0);
5683     rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
5684     rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
5685     rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
5686     rb_define_method(rb_cFloat, "/", rb_float_div, 1);
5687     rb_define_method(rb_cFloat, "quo", flo_quo, 1);
5688     rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
5689     rb_define_method(rb_cFloat, "%", flo_mod, 1);
5690     rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
5691     rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
5692     rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
5693     rb_define_method(rb_cFloat, "==", flo_eq, 1);
5694     rb_define_method(rb_cFloat, "===", flo_eq, 1);
5695     rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
5696     rb_define_method(rb_cFloat, ">",  rb_float_gt, 1);
5697     rb_define_method(rb_cFloat, ">=", flo_ge, 1);
5698     rb_define_method(rb_cFloat, "<",  flo_lt, 1);
5699     rb_define_method(rb_cFloat, "<=", flo_le, 1);
5700     rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
5701     rb_define_method(rb_cFloat, "hash", flo_hash, 0);
5702     rb_define_method(rb_cFloat, "to_f", flo_to_f, 0);
5703     rb_define_method(rb_cFloat, "abs", rb_float_abs, 0);
5704     rb_define_method(rb_cFloat, "magnitude", rb_float_abs, 0);
5705     rb_define_method(rb_cFloat, "zero?", flo_zero_p, 0);
5706 
5707     rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
5708     rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
5709     rb_define_method(rb_cFloat, "floor", flo_floor, -1);
5710     rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
5711     rb_define_method(rb_cFloat, "round", flo_round, -1);
5712     rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
5713 
5714     rb_define_method(rb_cFloat, "nan?",      flo_is_nan_p, 0);
5715     rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
5716     rb_define_method(rb_cFloat, "finite?",   rb_flo_is_finite_p, 0);
5717     rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
5718     rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
5719     rb_define_method(rb_cFloat, "positive?", flo_positive_p, 0);
5720     rb_define_method(rb_cFloat, "negative?", flo_negative_p, 0);
5721 
5722     id_to = rb_intern("to");
5723     id_by = rb_intern("by");
5724 }
5725 
5726 #undef rb_float_value
5727 double
rb_float_value(VALUE v)5728 rb_float_value(VALUE v)
5729 {
5730     return rb_float_value_inline(v);
5731 }
5732 
5733 #undef rb_float_new
5734 VALUE
rb_float_new(double d)5735 rb_float_new(double d)
5736 {
5737     return rb_float_new_inline(d);
5738 }
5739