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