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