Ruby 4.1.0dev (2026-06-14 revision a6e302509bd198fbff4edd10f69eff9286e34464)
numeric.c (a6e302509bd198fbff4edd10f69eff9286e34464)
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/internal/config.h"
13
14#include <assert.h>
15#include <ctype.h>
16#include <math.h>
17#include <stdio.h>
18
19#ifdef HAVE_FLOAT_H
20#include <float.h>
21#endif
22
23#ifdef HAVE_IEEEFP_H
24#include <ieeefp.h>
25#endif
26
27#include "id.h"
28#include "internal.h"
29#include "internal/array.h"
30#include "internal/compilers.h"
31#include "internal/complex.h"
32#include "internal/enumerator.h"
33#include "internal/error.h"
34#include "internal/gc.h"
35#include "internal/hash.h"
36#include "internal/numeric.h"
37#include "internal/object.h"
38#include "internal/rational.h"
39#include "internal/string.h"
40#include "internal/util.h"
41#include "internal/variable.h"
42#include "ruby/encoding.h"
43#include "ruby/util.h"
44#include "builtin.h"
45
46/* use IEEE 64bit values if not defined */
47#ifndef FLT_RADIX
48#define FLT_RADIX 2
49#endif
50#ifndef DBL_MIN
51#define DBL_MIN 2.2250738585072014e-308
52#endif
53#ifndef DBL_MAX
54#define DBL_MAX 1.7976931348623157e+308
55#endif
56#ifndef DBL_MIN_EXP
57#define DBL_MIN_EXP (-1021)
58#endif
59#ifndef DBL_MAX_EXP
60#define DBL_MAX_EXP 1024
61#endif
62#ifndef DBL_MIN_10_EXP
63#define DBL_MIN_10_EXP (-307)
64#endif
65#ifndef DBL_MAX_10_EXP
66#define DBL_MAX_10_EXP 308
67#endif
68#ifndef DBL_DIG
69#define DBL_DIG 15
70#endif
71#ifndef DBL_MANT_DIG
72#define DBL_MANT_DIG 53
73#endif
74#ifndef DBL_EPSILON
75#define DBL_EPSILON 2.2204460492503131e-16
76#endif
77
78#define ACCURATE_POW10(ndigits) ((ndigits) < DBL_DIG)
79
80#ifndef USE_RB_INFINITY
81#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
82const union bytesequence4_or_float rb_infinity = {{0x00, 0x00, 0x80, 0x7f}};
83#else
84const union bytesequence4_or_float rb_infinity = {{0x7f, 0x80, 0x00, 0x00}};
85#endif
86
87#ifndef USE_RB_NAN
88#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
89const union bytesequence4_or_float rb_nan = {{0x00, 0x00, 0xc0, 0x7f}};
90#else
91const union bytesequence4_or_float rb_nan = {{0x7f, 0xc0, 0x00, 0x00}};
92#endif
93
94#ifndef HAVE_ROUND
95double
96round(double x)
97{
98 double f;
99
100 if (x > 0.0) {
101 f = floor(x);
102 x = f + (x - f >= 0.5);
103 }
104 else if (x < 0.0) {
105 f = ceil(x);
106 x = f - (f - x >= 0.5);
107 }
108 return x;
109}
110#endif
111
112static double
113round_half_up(double x, double s)
114{
115 double f, xs = x * s;
116
117 f = round(xs);
118 if (s == 1.0) return f;
119 if (x > 0) {
120 if ((double)((f + 0.5) / s) <= x) f += 1;
121 x = f;
122 }
123 else {
124 if ((double)((f - 0.5) / s) >= x) f -= 1;
125 x = f;
126 }
127 return x;
128}
129
130static double
131round_half_down(double x, double s)
132{
133 double f, xs = x * s;
134
135 f = round(xs);
136 if (x > 0) {
137 if ((double)((f - 0.5) / s) >= x) f -= 1;
138 x = f;
139 }
140 else {
141 if ((double)((f + 0.5) / s) <= x) f += 1;
142 x = f;
143 }
144 return x;
145}
146
147static double
148round_half_even(double x, double s)
149{
150 double u, v, us, vs, f, d, uf;
151
152 v = modf(x, &u);
153 us = u * s;
154 vs = v * s;
155
156 if (x > 0.0) {
157 f = floor(vs);
158 uf = us + f;
159 d = vs - f;
160 if (d > 0.5)
161 d = 1.0;
162 else if (d == 0.5 || ((double)((uf + 0.5) / s) <= x))
163 d = fmod(uf, 2.0);
164 else
165 d = 0.0;
166 x = f + d;
167 }
168 else if (x < 0.0) {
169 f = ceil(vs);
170 uf = us + f;
171 d = f - vs;
172 if (d > 0.5)
173 d = 1.0;
174 else if (d == 0.5 || ((double)((uf - 0.5) / s) >= x))
175 d = fmod(-uf, 2.0);
176 else
177 d = 0.0;
178 x = f - d;
179 }
180 return us + x;
181}
182
183static VALUE fix_lshift(long, unsigned long);
184static VALUE fix_rshift(long, unsigned long);
185static VALUE int_pow(long x, unsigned long y);
186static VALUE rb_int_floor(VALUE num, int ndigits);
187static VALUE rb_int_ceil(VALUE num, int ndigits);
188static VALUE flo_to_i(VALUE num);
189static int float_round_overflow(int ndigits, int binexp);
190static int float_round_underflow(int ndigits, int binexp);
191
192static ID id_coerce;
193#define id_div idDiv
194#define id_divmod idDivmod
195#define id_to_i idTo_i
196#define id_eq idEq
197#define id_cmp idCmp
198
202
205
206static ID id_to, id_by;
207
208void
210{
211 rb_raise(rb_eZeroDivError, "divided by 0");
212}
213
214enum ruby_num_rounding_mode
215rb_num_get_rounding_option(VALUE opts)
216{
217 static ID round_kwds[1];
218 VALUE rounding;
219 VALUE str;
220 const char *s;
221
222 if (!NIL_P(opts)) {
223 if (!round_kwds[0]) {
224 round_kwds[0] = rb_intern_const("half");
225 }
226 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
227 if (SYMBOL_P(rounding)) {
228 str = rb_sym2str(rounding);
229 }
230 else if (NIL_P(rounding)) {
231 goto noopt;
232 }
233 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
234 str = rb_check_string_type(rounding);
235 if (NIL_P(str)) goto invalid;
236 }
238 s = RSTRING_PTR(str);
239 switch (RSTRING_LEN(str)) {
240 case 2:
241 if (rb_memcicmp(s, "up", 2) == 0)
242 return RUBY_NUM_ROUND_HALF_UP;
243 break;
244 case 4:
245 if (rb_memcicmp(s, "even", 4) == 0)
246 return RUBY_NUM_ROUND_HALF_EVEN;
247 if (strncasecmp(s, "down", 4) == 0)
248 return RUBY_NUM_ROUND_HALF_DOWN;
249 break;
250 }
251 invalid:
252 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
253 }
254 noopt:
255 return RUBY_NUM_ROUND_DEFAULT;
256}
257
258/* experimental API */
259int
260rb_num_to_uint(VALUE val, unsigned int *ret)
261{
262#define NUMERR_TYPE 1
263#define NUMERR_NEGATIVE 2
264#define NUMERR_TOOLARGE 3
265 if (FIXNUM_P(val)) {
266 long v = FIX2LONG(val);
267#if SIZEOF_INT < SIZEOF_LONG
268 if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
269#endif
270 if (v < 0) return NUMERR_NEGATIVE;
271 *ret = (unsigned int)v;
272 return 0;
273 }
274
275 if (RB_BIGNUM_TYPE_P(val)) {
276 if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
277#if SIZEOF_INT < SIZEOF_LONG
278 /* long is 64bit */
279 return NUMERR_TOOLARGE;
280#else
281 /* long is 32bit */
282 if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
283 *ret = (unsigned int)rb_big2ulong((VALUE)val);
284 return 0;
285#endif
286 }
287 return NUMERR_TYPE;
288}
289
290#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
291
292static inline int
293int_pos_p(VALUE num)
294{
295 if (FIXNUM_P(num)) {
296 return FIXNUM_POSITIVE_P(num);
297 }
298 else if (RB_BIGNUM_TYPE_P(num)) {
299 return BIGNUM_POSITIVE_P(num);
300 }
301 rb_raise(rb_eTypeError, "not an Integer");
302}
303
304static inline int
305int_neg_p(VALUE num)
306{
307 if (FIXNUM_P(num)) {
308 return FIXNUM_NEGATIVE_P(num);
309 }
310 else if (RB_BIGNUM_TYPE_P(num)) {
311 return BIGNUM_NEGATIVE_P(num);
312 }
313 rb_raise(rb_eTypeError, "not an Integer");
314}
315
316int
317rb_int_positive_p(VALUE num)
318{
319 return int_pos_p(num);
320}
321
322int
323rb_int_negative_p(VALUE num)
324{
325 return int_neg_p(num);
326}
327
328int
329rb_num_negative_p(VALUE num)
330{
331 return rb_num_negative_int_p(num);
332}
333
334static VALUE
335num_funcall_op_0(VALUE x, VALUE arg, int recursive)
336{
337 ID func = (ID)arg;
338 if (recursive) {
339 const char *name = rb_id2name(func);
340 if (ISALNUM(name[0])) {
341 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
342 x, ID2SYM(func));
343 }
344 else if (name[0] && name[1] == '@' && !name[2]) {
345 rb_name_error(func, "%c%"PRIsVALUE,
346 name[0], x);
347 }
348 else {
349 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
350 ID2SYM(func), x);
351 }
352 }
353 return rb_funcallv(x, func, 0, 0);
354}
355
356static VALUE
357num_funcall0(VALUE x, ID func)
358{
359 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
360}
361
362NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
363
364static void
365num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
366{
367 const char *name = rb_id2name(func);
368 if (ISALNUM(name[0])) {
369 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
370 x, ID2SYM(func), y);
371 }
372 else {
373 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
374 x, ID2SYM(func), y);
375 }
376}
377
378static VALUE
379num_funcall_op_1(VALUE y, VALUE arg, int recursive)
380{
381 ID func = (ID)((VALUE *)arg)[0];
382 VALUE x = ((VALUE *)arg)[1];
383 if (recursive) {
384 num_funcall_op_1_recursion(x, func, y);
385 }
386 return rb_funcall(x, func, 1, y);
387}
388
389static VALUE
390num_funcall1(VALUE x, ID func, VALUE y)
391{
392 VALUE args[2];
393 args[0] = (VALUE)func;
394 args[1] = x;
395 return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
396}
397
398/*
399 * call-seq:
400 * coerce(other) -> array
401 *
402 * Returns a 2-element array containing two numeric elements,
403 * formed from the two operands +self+ and +other+,
404 * of a common compatible type.
405 *
406 * Of the Core and Standard Library classes,
407 * Integer, Rational, and Complex use this implementation.
408 *
409 * Examples:
410 *
411 * i = 2 # => 2
412 * i.coerce(3) # => [3, 2]
413 * i.coerce(3.0) # => [3.0, 2.0]
414 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
415 * i.coerce(Complex(3, 4)) # Raises RangeError.
416 *
417 * r = Rational(5, 2) # => (5/2)
418 * r.coerce(2) # => [(2/1), (5/2)]
419 * r.coerce(2.0) # => [2.0, 2.5]
420 * r.coerce(Rational(2, 3)) # => [(2/3), (5/2)]
421 * r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)]
422 *
423 * c = Complex(2, 3) # => (2+3i)
424 * c.coerce(2) # => [(2+0i), (2+3i)]
425 * c.coerce(2.0) # => [(2.0+0i), (2+3i)]
426 * c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)]
427 * c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
428 *
429 * Raises an exception if any type conversion fails.
430 *
431 */
432
433static VALUE
434num_coerce(VALUE x, VALUE y)
435{
436 if (CLASS_OF(x) == CLASS_OF(y))
437 return rb_assoc_new(y, x);
438 x = rb_Float(x);
439 y = rb_Float(y);
440 return rb_assoc_new(y, x);
441}
442
443NORETURN(static void coerce_failed(VALUE x, VALUE y));
444static void
445coerce_failed(VALUE x, VALUE y)
446{
447 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
448 y = rb_inspect(y);
449 }
450 else {
451 y = rb_obj_class(y);
452 }
453 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
454 y, rb_obj_class(x));
455}
456
457static int
458do_coerce(VALUE *x, VALUE *y, int err)
459{
460 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
461 if (UNDEF_P(ary)) {
462 if (err) {
463 coerce_failed(*x, *y);
464 }
465 return FALSE;
466 }
467 if (!err && NIL_P(ary)) {
468 return FALSE;
469 }
470 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
471 rb_raise(rb_eTypeError, "coerce must return [x, y]");
472 }
473
474 *x = RARRAY_AREF(ary, 0);
475 *y = RARRAY_AREF(ary, 1);
476 return TRUE;
477}
478
479VALUE
481{
482 do_coerce(&x, &y, TRUE);
483 return rb_funcall(x, func, 1, y);
484}
485
486VALUE
488{
489 if (do_coerce(&x, &y, FALSE))
490 return rb_funcall(x, func, 1, y);
491 return Qnil;
492}
493
494static VALUE
495ensure_cmp(VALUE c, VALUE x, VALUE y)
496{
497 if (NIL_P(c)) rb_cmperr_reason(x, y, "comparator returned nil");
498 return c;
499}
500
501VALUE
503{
504 VALUE x0 = x, y0 = y;
505
506 if (!do_coerce(&x, &y, FALSE)) {
507 rb_cmperr_reason(x0, y0, "coercion was not possible");
509 }
510 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
511}
512
513NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
514
515/*
516 * :nodoc:
517 *
518 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
519 *
520 * Numerics should be values; singleton_methods should not be added to them.
521 */
522
523static VALUE
524num_sadded(VALUE x, VALUE name)
525{
526 ID mid = rb_to_id(name);
527 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
529 rb_raise(rb_eTypeError,
530 "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
531 rb_id2str(mid),
532 rb_obj_class(x));
533
535}
536
537#if 0
538/*
539 * call-seq:
540 * clone(freeze: true) -> self
541 *
542 * Returns +self+.
543 *
544 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
545 *
546 * Related: Numeric#dup.
547 *
548 */
549static VALUE
550num_clone(int argc, VALUE *argv, VALUE x)
551{
552 return rb_immutable_obj_clone(argc, argv, x);
553}
554#else
555# define num_clone rb_immutable_obj_clone
556#endif
557
558/*
559 * call-seq:
560 * i -> complex
561 *
562 * Returns <tt>Complex(0, self)</tt>:
563 *
564 * 2.i # => (0+2i)
565 * -2.i # => (0-2i)
566 * 2.0.i # => (0+2.0i)
567 * Rational(1, 2).i # => (0+(1/2)*i)
568 * Complex(3, 4).i # Raises NoMethodError.
569 *
570 */
571
572static VALUE
573num_imaginary(VALUE num)
574{
575 return rb_complex_new(INT2FIX(0), num);
576}
577
578/*
579 * call-seq:
580 * -self -> numeric
581 *
582 * Returns +self+, negated.
583 */
584
585static VALUE
586num_uminus(VALUE num)
587{
588 VALUE zero;
589
590 zero = INT2FIX(0);
591 do_coerce(&zero, &num, TRUE);
592
593 return num_funcall1(zero, '-', num);
594}
595
596/*
597 * call-seq:
598 * fdiv(other) -> float
599 *
600 * Returns the quotient <tt>self/other</tt> as a float,
601 * using method +/+ as defined in the subclass of \Numeric.
602 * (\Numeric itself does not define +/+.)
603 *
604 * Of the Core and Standard Library classes,
605 * only BigDecimal uses this implementation.
606 *
607 */
608
609static VALUE
610num_fdiv(VALUE x, VALUE y)
611{
612 return rb_funcall(rb_Float(x), '/', 1, y);
613}
614
615/*
616 * call-seq:
617 * div(other) -> integer
618 *
619 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
620 * using method +/+ as defined in the subclass of \Numeric.
621 * (\Numeric itself does not define +/+.)
622 *
623 * Of the Core and Standard Library classes,
624 * Only Float and Rational use this implementation.
625 *
626 */
627
628static VALUE
629num_div(VALUE x, VALUE y)
630{
631 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
632 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
633}
634
635/*
636 * call-seq:
637 * self % other -> real_numeric
638 *
639 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
640 *
641 * Of the Core and Standard Library classes,
642 * only Rational uses this implementation.
643 *
644 * For Rational +r+ and real number +n+, these expressions are equivalent:
645 *
646 * r % n
647 * r-n*(r/n).floor
648 * r.divmod(n)[1]
649 *
650 * See Numeric#divmod.
651 *
652 * Examples:
653 *
654 * r = Rational(1, 2) # => (1/2)
655 * r2 = Rational(2, 3) # => (2/3)
656 * r % r2 # => (1/2)
657 * r % 2 # => (1/2)
658 * r % 2.0 # => 0.5
659 *
660 * r = Rational(301,100) # => (301/100)
661 * r2 = Rational(7,5) # => (7/5)
662 * r % r2 # => (21/100)
663 * r % -r2 # => (-119/100)
664 * (-r) % r2 # => (119/100)
665 * (-r) %-r2 # => (-21/100)
666 *
667 */
668
669static VALUE
670num_modulo(VALUE x, VALUE y)
671{
672 VALUE q = num_funcall1(x, id_div, y);
673 return rb_funcall(x, '-', 1,
674 rb_funcall(y, '*', 1, q));
675}
676
677/*
678 * call-seq:
679 * remainder(other) -> real_number
680 *
681 * Returns the remainder after dividing +self+ by +other+.
682 *
683 * Of the Core and Standard Library classes,
684 * only Float and Rational use this implementation.
685 *
686 * Examples:
687 *
688 * 11.0.remainder(4) # => 3.0
689 * 11.0.remainder(-4) # => 3.0
690 * -11.0.remainder(4) # => -3.0
691 * -11.0.remainder(-4) # => -3.0
692 *
693 * 12.0.remainder(4) # => 0.0
694 * 12.0.remainder(-4) # => 0.0
695 * -12.0.remainder(4) # => -0.0
696 * -12.0.remainder(-4) # => -0.0
697 *
698 * 13.0.remainder(4.0) # => 1.0
699 * 13.0.remainder(Rational(4, 1)) # => 1.0
700 *
701 * Rational(13, 1).remainder(4) # => (1/1)
702 * Rational(13, 1).remainder(-4) # => (1/1)
703 * Rational(-13, 1).remainder(4) # => (-1/1)
704 * Rational(-13, 1).remainder(-4) # => (-1/1)
705 *
706 */
707
708static VALUE
709num_remainder(VALUE x, VALUE y)
710{
712 do_coerce(&x, &y, TRUE);
713 }
714 VALUE z = num_funcall1(x, '%', y);
715
716 if ((!rb_equal(z, INT2FIX(0))) &&
717 ((rb_num_negative_int_p(x) &&
718 rb_num_positive_int_p(y)) ||
719 (rb_num_positive_int_p(x) &&
720 rb_num_negative_int_p(y)))) {
721 if (RB_FLOAT_TYPE_P(y)) {
722 if (isinf(RFLOAT_VALUE(y))) {
723 return x;
724 }
725 }
726 return rb_funcall(z, '-', 1, y);
727 }
728 return z;
729}
730
731/*
732 * call-seq:
733 * divmod(other) -> array
734 *
735 * Returns a 2-element array <tt>[q, r]</tt>, where
736 *
737 * q = (self/other).floor # Quotient
738 * r = self % other # Remainder
739 *
740 * Of the Core and Standard Library classes,
741 * only Rational uses this implementation.
742 *
743 * Examples:
744 *
745 * Rational(11, 1).divmod(4) # => [2, (3/1)]
746 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
747 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
748 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
749 *
750 * Rational(12, 1).divmod(4) # => [3, (0/1)]
751 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
752 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
753 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
754 *
755 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
756 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
757 */
758
759static VALUE
760num_divmod(VALUE x, VALUE y)
761{
762 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
763}
764
765/*
766 * call-seq:
767 * abs -> numeric
768 *
769 * Returns the absolute value of +self+.
770 *
771 * 12.abs #=> 12
772 * (-34.56).abs #=> 34.56
773 * -34.56.abs #=> 34.56
774 *
775 */
776
777static VALUE
778num_abs(VALUE num)
779{
780 if (rb_num_negative_int_p(num)) {
781 return num_funcall0(num, idUMinus);
782 }
783 return num;
784}
785
786/*
787 * call-seq:
788 * zero? -> true or false
789 *
790 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
791 *
792 * Of the Core and Standard Library classes,
793 * only Rational and Complex use this implementation.
794 *
795 */
796
797static VALUE
798num_zero_p(VALUE num)
799{
800 return rb_equal(num, INT2FIX(0));
801}
802
803static bool
804int_zero_p(VALUE num)
805{
806 if (FIXNUM_P(num)) {
807 return FIXNUM_ZERO_P(num);
808 }
809 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
810 return rb_bigzero_p(num);
811}
812
813VALUE
814rb_int_zero_p(VALUE num)
815{
816 return RBOOL(int_zero_p(num));
817}
818
819/*
820 * call-seq:
821 * nonzero? -> self or nil
822 *
823 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
824 * uses method <tt>zero?</tt> for the evaluation.
825 *
826 * The returned +self+ allows the method to be chained:
827 *
828 * a = %w[z Bb bB bb BB a aA Aa AA A]
829 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
830 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
831 *
832 * Of the Core and Standard Library classes,
833 * Integer, Float, Rational, and Complex use this implementation.
834 *
835 * Related: #zero?
836 *
837 */
838
839static VALUE
840num_nonzero_p(VALUE num)
841{
842 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
843 return Qnil;
844 }
845 return num;
846}
847
848/*
849 * call-seq:
850 * to_int -> integer
851 *
852 * Returns +self+ as an integer;
853 * converts using method +to_i+ in the subclass of \Numeric.
854 * (\Numeric itself does not define +to_i+.)
855 *
856 * Of the Core and Standard Library classes,
857 * only Rational and Complex use this implementation.
858 *
859 * Examples:
860 *
861 * Rational(1, 2).to_int # => 0
862 * Rational(2, 1).to_int # => 2
863 * Complex(2, 0).to_int # => 2
864 * Complex(2, 1).to_int # Raises RangeError (non-zero imaginary part)
865 *
866 */
867
868static VALUE
869num_to_int(VALUE num)
870{
871 return num_funcall0(num, id_to_i);
872}
873
874/*
875 * call-seq:
876 * positive? -> true or false
877 *
878 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
879 *
880 */
881
882static VALUE
883num_positive_p(VALUE num)
884{
885 const ID mid = '>';
886
887 if (FIXNUM_P(num)) {
888 if (method_basic_p(rb_cInteger))
889 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
890 }
891 else if (RB_BIGNUM_TYPE_P(num)) {
892 if (method_basic_p(rb_cInteger))
893 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
894 }
895 return rb_num_compare_with_zero(num, mid);
896}
897
898/*
899 * call-seq:
900 * negative? -> true or false
901 *
902 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
903 *
904 */
905
906static VALUE
907num_negative_p(VALUE num)
908{
909 return RBOOL(rb_num_negative_int_p(num));
910}
911
912VALUE
914{
915 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT, sizeof(struct RFloat));
916
917#if SIZEOF_DOUBLE <= SIZEOF_VALUE
918 flt->float_value = d;
919#else
920 union {
921 double d;
922 rb_float_value_type v;
923 } u = {d};
924 flt->float_value = u.v;
925#endif
926 OBJ_FREEZE((VALUE)flt);
927 return (VALUE)flt;
928}
929
930/*
931 * call-seq:
932 * to_s -> string
933 *
934 * Returns a string containing a representation of +self+;
935 * depending of the value of +self+, the string representation
936 * may contain:
937 *
938 * - A fixed-point number.
939 * 3.14.to_s # => "3.14"
940 * - A number in "scientific notation" (containing an exponent).
941 * (10.1**50).to_s # => "1.644631821843879e+50"
942 * - 'Infinity'.
943 * (10.1**500).to_s # => "Infinity"
944 * - '-Infinity'.
945 * (-10.1**500).to_s # => "-Infinity"
946 * - 'NaN' (indicating not-a-number).
947 * (0.0/0.0).to_s # => "NaN"
948 *
949 */
950
951static VALUE
952flo_to_s(VALUE flt)
953{
954 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
955 enum {float_dig = DBL_DIG+1};
956 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
957 double value = RFLOAT_VALUE(flt);
958 VALUE s;
959 char *p, *e;
960 int sign, decpt, digs;
961
962 if (isinf(value)) {
963 static const char minf[] = "-Infinity";
964 const int pos = (value > 0); /* skip "-" */
965 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
966 }
967 else if (isnan(value))
968 return rb_usascii_str_new2("NaN");
969
970 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
971 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
972 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
973 memcpy(buf, p, digs);
974 free(p);
975 if (decpt > 0) {
976 if (decpt < digs) {
977 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
978 buf[decpt] = '.';
979 rb_str_cat(s, buf, digs + 1);
980 }
981 else if (decpt <= DBL_DIG) {
982 long len;
983 char *ptr;
984 rb_str_cat(s, buf, digs);
985 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
986 ptr = RSTRING_PTR(s) + len;
987 if (decpt > digs) {
988 memset(ptr, '0', decpt - digs);
989 ptr += decpt - digs;
990 }
991 memcpy(ptr, ".0", 2);
992 }
993 else {
994 goto exp;
995 }
996 }
997 else if (decpt > -4) {
998 long len;
999 char *ptr;
1000 rb_str_cat(s, "0.", 2);
1001 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1002 ptr = RSTRING_PTR(s);
1003 memset(ptr += len, '0', -decpt);
1004 memcpy(ptr -= decpt, buf, digs);
1005 }
1006 else {
1007 goto exp;
1008 }
1009 return s;
1010
1011 exp:
1012 if (digs > 1) {
1013 memmove(buf + 2, buf + 1, digs - 1);
1014 }
1015 else {
1016 buf[2] = '0';
1017 digs++;
1018 }
1019 buf[1] = '.';
1020 rb_str_cat(s, buf, digs + 1);
1021 rb_str_catf(s, "e%+03d", decpt - 1);
1022 return s;
1023}
1024
1025/*
1026 * call-seq:
1027 * coerce(other) -> array
1028 *
1029 * Returns a 2-element array containing +other+ converted to a \Float
1030 * and +self+:
1031 *
1032 * f = 3.14 # => 3.14
1033 * f.coerce(2) # => [2.0, 3.14]
1034 * f.coerce(2.0) # => [2.0, 3.14]
1035 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1036 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1037 *
1038 * Raises an exception if a type conversion fails.
1039 *
1040 */
1041
1042static VALUE
1043flo_coerce(VALUE x, VALUE y)
1044{
1045 return rb_assoc_new(rb_Float(y), x);
1046}
1047
1048VALUE
1049rb_float_uminus(VALUE flt)
1050{
1051 return DBL2NUM(-RFLOAT_VALUE(flt));
1052}
1053
1054/*
1055 * call-seq:
1056 * self + other -> float or complex
1057 *
1058 * Returns the sum of +self+ and +other+;
1059 * the result may be inexact (see Float):
1060 *
1061 * 3.14 + 0 # => 3.14
1062 * 3.14 + 1 # => 4.140000000000001
1063 * -3.14 + 0 # => -3.14
1064 * -3.14 + 1 # => -2.14
1065
1066 * 3.14 + -3.14 # => 0.0
1067 * -3.14 + -3.14 # => -6.28
1068 *
1069 * 3.14 + Complex(1, 0) # => (4.140000000000001+0i)
1070 * 3.14 + Rational(1, 1) # => 4.140000000000001
1071 *
1072 */
1073
1074VALUE
1075rb_float_plus(VALUE x, VALUE y)
1076{
1077 if (FIXNUM_P(y)) {
1078 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1079 }
1080 else if (RB_BIGNUM_TYPE_P(y)) {
1081 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1082 }
1083 else if (RB_FLOAT_TYPE_P(y)) {
1084 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1085 }
1086 else {
1087 return rb_num_coerce_bin(x, y, '+');
1088 }
1089}
1090
1091/*
1092 * call-seq:
1093 * self - other -> numeric
1094 *
1095 * Returns the difference of +self+ and +other+:
1096 *
1097 * f = 3.14
1098 * f - 1 # => 2.14
1099 * f - 1.0 # => 2.14
1100 * f - Rational(1, 1) # => 2.14
1101 * f - Complex(1, 0) # => (2.14+0i)
1102 *
1103 */
1104
1105VALUE
1106rb_float_minus(VALUE x, VALUE y)
1107{
1108 if (FIXNUM_P(y)) {
1109 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1110 }
1111 else if (RB_BIGNUM_TYPE_P(y)) {
1112 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1113 }
1114 else if (RB_FLOAT_TYPE_P(y)) {
1115 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1116 }
1117 else {
1118 return rb_num_coerce_bin(x, y, '-');
1119 }
1120}
1121
1122/*
1123 * call-seq:
1124 * self * other -> numeric
1125 *
1126 * Returns the numeric product of +self+ and +other+:
1127 *
1128 * f = 3.14
1129 * f * 2 # => 6.28
1130 * f * 2.0 # => 6.28
1131 * f * Rational(1, 2) # => 1.57
1132 * f * Complex(2, 0) # => (6.28+0.0i)
1133 *
1134 */
1135
1136VALUE
1137rb_float_mul(VALUE x, VALUE y)
1138{
1139 if (FIXNUM_P(y)) {
1140 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1141 }
1142 else if (RB_BIGNUM_TYPE_P(y)) {
1143 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1144 }
1145 else if (RB_FLOAT_TYPE_P(y)) {
1146 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1147 }
1148 else {
1149 return rb_num_coerce_bin(x, y, '*');
1150 }
1151}
1152
1153static double
1154double_div_double(double x, double y)
1155{
1156 if (LIKELY(y != 0.0)) {
1157 return x / y;
1158 }
1159 else if (x == 0.0) {
1160 return nan("");
1161 }
1162 else {
1163 double z = signbit(y) ? -1.0 : 1.0;
1164 return x * z * HUGE_VAL;
1165 }
1166}
1167
1168VALUE
1169rb_flo_div_flo(VALUE x, VALUE y)
1170{
1171 double num = RFLOAT_VALUE(x);
1172 double den = RFLOAT_VALUE(y);
1173 double ret = double_div_double(num, den);
1174 return DBL2NUM(ret);
1175}
1176
1177/*
1178 * call-seq:
1179 * self / other -> numeric
1180 *
1181 * Returns the quotient of +self+ and +other+:
1182 *
1183 * f = 3.14
1184 * f / 2 # => 1.57
1185 * f / 2.0 # => 1.57
1186 * f / Rational(2, 1) # => 1.57
1187 * f / Complex(2, 0) # => (1.57+0.0i)
1188 *
1189 */
1190
1191VALUE
1192rb_float_div(VALUE x, VALUE y)
1193{
1194 double num = RFLOAT_VALUE(x);
1195 double den;
1196 double ret;
1197
1198 if (FIXNUM_P(y)) {
1199 den = FIX2LONG(y);
1200 }
1201 else if (RB_BIGNUM_TYPE_P(y)) {
1202 den = rb_big2dbl(y);
1203 }
1204 else if (RB_FLOAT_TYPE_P(y)) {
1205 den = RFLOAT_VALUE(y);
1206 }
1207 else {
1208 return rb_num_coerce_bin(x, y, '/');
1209 }
1210
1211 ret = double_div_double(num, den);
1212 return DBL2NUM(ret);
1213}
1214
1215/*
1216 * call-seq:
1217 * quo(other) -> numeric
1218 *
1219 * Returns the quotient from dividing +self+ by +other+:
1220 *
1221 * f = 3.14
1222 * f.quo(2) # => 1.57
1223 * f.quo(-2) # => -1.57
1224 * f.quo(Rational(2, 1)) # => 1.57
1225 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1226 *
1227 */
1228
1229static VALUE
1230flo_quo(VALUE x, VALUE y)
1231{
1232 return num_funcall1(x, '/', y);
1233}
1234
1235static void
1236flodivmod(double x, double y, double *divp, double *modp)
1237{
1238 double div, mod;
1239
1240 if (isnan(y)) {
1241 /* y is NaN so all results are NaN */
1242 if (modp) *modp = y;
1243 if (divp) *divp = y;
1244 return;
1245 }
1246 if (y == 0.0) rb_num_zerodiv();
1247 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1248 mod = x;
1249 else {
1250#ifdef HAVE_FMOD
1251 mod = fmod(x, y);
1252#else
1253 double z;
1254
1255 modf(x/y, &z);
1256 mod = x - z * y;
1257#endif
1258 }
1259 if (isinf(x) && !isinf(y))
1260 div = x;
1261 else {
1262 div = (x - mod) / y;
1263 if (modp && divp) div = round(div);
1264 }
1265 if (y*mod < 0) {
1266 mod += y;
1267 div -= 1.0;
1268 }
1269 if (modp) *modp = mod;
1270 if (divp) *divp = div;
1271}
1272
1273/*
1274 * Returns the modulo of division of x by y.
1275 * An error will be raised if y == 0.
1276 */
1277
1278double
1279ruby_float_mod(double x, double y)
1280{
1281 double mod;
1282 flodivmod(x, y, 0, &mod);
1283 return mod;
1284}
1285
1286/*
1287 * call-seq:
1288 * self % other -> float
1289 *
1290 * Returns +self+ modulo +other+ as a \Float.
1291 *
1292 * For float +f+ and real number +r+, these expressions are equivalent:
1293 *
1294 * f % r
1295 * f-r*(f/r).floor
1296 * f.divmod(r)[1]
1297 *
1298 * See Numeric#divmod.
1299 *
1300 * Examples:
1301 *
1302 * 10.0 % 2 # => 0.0
1303 * 10.0 % 3 # => 1.0
1304 * 10.0 % 4 # => 2.0
1305 *
1306 * 10.0 % -2 # => 0.0
1307 * 10.0 % -3 # => -2.0
1308 * 10.0 % -4 # => -2.0
1309 *
1310 * 10.0 % 4.0 # => 2.0
1311 * 10.0 % Rational(4, 1) # => 2.0
1312 *
1313 */
1314
1315static VALUE
1316flo_mod(VALUE x, VALUE y)
1317{
1318 double fy;
1319
1320 if (FIXNUM_P(y)) {
1321 fy = (double)FIX2LONG(y);
1322 }
1323 else if (RB_BIGNUM_TYPE_P(y)) {
1324 fy = rb_big2dbl(y);
1325 }
1326 else if (RB_FLOAT_TYPE_P(y)) {
1327 fy = RFLOAT_VALUE(y);
1328 }
1329 else {
1330 return rb_num_coerce_bin(x, y, '%');
1331 }
1332 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1333}
1334
1335static VALUE
1336dbl2ival(double d)
1337{
1338 if (FIXABLE(d)) {
1339 return LONG2FIX((long)d);
1340 }
1341 return rb_dbl2big(d);
1342}
1343
1344/*
1345 * call-seq:
1346 * divmod(other) -> array
1347 *
1348 * Returns a 2-element array <tt>[q, r]</tt>, where
1349 *
1350 * q = (self/other).floor # Quotient
1351 * r = self % other # Remainder
1352 *
1353 * Examples:
1354 *
1355 * 11.0.divmod(4) # => [2, 3.0]
1356 * 11.0.divmod(-4) # => [-3, -1.0]
1357 * -11.0.divmod(4) # => [-3, 1.0]
1358 * -11.0.divmod(-4) # => [2, -3.0]
1359 *
1360 * 12.0.divmod(4) # => [3, 0.0]
1361 * 12.0.divmod(-4) # => [-3, 0.0]
1362 * -12.0.divmod(4) # => [-3, -0.0]
1363 * -12.0.divmod(-4) # => [3, -0.0]
1364 *
1365 * 13.0.divmod(4.0) # => [3, 1.0]
1366 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1367 *
1368 */
1369
1370static VALUE
1371flo_divmod(VALUE x, VALUE y)
1372{
1373 double fy, div, mod;
1374 volatile VALUE a, b;
1375
1376 if (FIXNUM_P(y)) {
1377 fy = (double)FIX2LONG(y);
1378 }
1379 else if (RB_BIGNUM_TYPE_P(y)) {
1380 fy = rb_big2dbl(y);
1381 }
1382 else if (RB_FLOAT_TYPE_P(y)) {
1383 fy = RFLOAT_VALUE(y);
1384 }
1385 else {
1386 return rb_num_coerce_bin(x, y, id_divmod);
1387 }
1388 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1389 a = dbl2ival(div);
1390 b = DBL2NUM(mod);
1391 return rb_assoc_new(a, b);
1392}
1393
1394/*
1395 * call-seq:
1396 * self ** exponent -> numeric
1397 *
1398 * Returns +self+ raised to the power +exponent+:
1399 *
1400 * f = 3.14
1401 * f ** 2 # => 9.8596
1402 * f ** -2 # => 0.1014239928597509
1403 * f ** 2.1 # => 11.054834900588839
1404 * f ** Rational(2, 1) # => 9.8596
1405 * f ** Complex(2, 0) # => (9.8596+0i)
1406 *
1407 */
1408
1409VALUE
1410rb_float_pow(VALUE x, VALUE y)
1411{
1412 double dx, dy;
1413 if (y == INT2FIX(2)) {
1414 dx = RFLOAT_VALUE(x);
1415 return DBL2NUM(dx * dx);
1416 }
1417 else if (FIXNUM_P(y)) {
1418 dx = RFLOAT_VALUE(x);
1419 dy = (double)FIX2LONG(y);
1420 }
1421 else if (RB_BIGNUM_TYPE_P(y)) {
1422 dx = RFLOAT_VALUE(x);
1423 dy = rb_big2dbl(y);
1424 }
1425 else if (RB_FLOAT_TYPE_P(y)) {
1426 dx = RFLOAT_VALUE(x);
1427 dy = RFLOAT_VALUE(y);
1428 if (dx < 0 && dy != round(dy))
1429 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1430 }
1431 else {
1432 return rb_num_coerce_bin(x, y, idPow);
1433 }
1434 return DBL2NUM(pow(dx, dy));
1435}
1436
1437/*
1438 * call-seq:
1439 * eql?(other) -> true or false
1440 *
1441 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1442 *
1443 * Of the Core and Standard Library classes,
1444 * only Integer, Rational, and Complex use this implementation.
1445 *
1446 * Examples:
1447 *
1448 * 1.eql?(1) # => true
1449 * 1.eql?(1.0) # => false
1450 * 1.eql?(Rational(1, 1)) # => false
1451 * 1.eql?(Complex(1, 0)) # => false
1452 *
1453 * Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1454 * while <tt>==</tt> does not.
1455 *
1456 */
1457
1458static VALUE
1459num_eql(VALUE x, VALUE y)
1460{
1461 if (TYPE(x) != TYPE(y)) return Qfalse;
1462
1463 if (RB_BIGNUM_TYPE_P(x)) {
1464 return rb_big_eql(x, y);
1465 }
1466
1467 return rb_equal(x, y);
1468}
1469
1470/*
1471 * call-seq:
1472 * self <=> other -> zero or nil
1473 *
1474 * Compares +self+ and +other+.
1475 *
1476 * Returns:
1477 *
1478 * - Zero, if +self+ is the same as +other+.
1479 * - +nil+, otherwise.
1480 *
1481 * \Class \Numeric includes module Comparable,
1482 * each of whose methods uses Numeric#<=> for comparison.
1483 *
1484 * No subclass in the Ruby Core or Standard Library uses this implementation.
1485 */
1486
1487static VALUE
1488num_cmp(VALUE x, VALUE y)
1489{
1490 if (x == y) return INT2FIX(0);
1491 return Qnil;
1492}
1493
1494static VALUE
1495num_equal(VALUE x, VALUE y)
1496{
1497 VALUE result;
1498 if (x == y) return Qtrue;
1499 result = num_funcall1(y, id_eq, x);
1500 return RBOOL(RTEST(result));
1501}
1502
1503/*
1504 * call-seq:
1505 * self == other -> true or false
1506 *
1507 * Returns whether +other+ is numerically equal to +self+:
1508 *
1509 * 2.0 == 2 # => true
1510 * 2.0 == 2.0 # => true
1511 * 2.0 == Rational(2, 1) # => true
1512 * 2.0 == Complex(2, 0) # => true
1513 *
1514 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1515 *
1516 * Related: Float#eql? (requires +other+ to be a \Float).
1517 *
1518 */
1519
1520VALUE
1521rb_float_equal(VALUE x, VALUE y)
1522{
1523 volatile double a, b;
1524
1525 if (RB_INTEGER_TYPE_P(y)) {
1526 return rb_integer_float_eq(y, x);
1527 }
1528 else if (RB_FLOAT_TYPE_P(y)) {
1529 b = RFLOAT_VALUE(y);
1530 }
1531 else {
1532 return num_equal(x, y);
1533 }
1534 a = RFLOAT_VALUE(x);
1535 return RBOOL(a == b);
1536}
1537
1538#define flo_eq rb_float_equal
1539static VALUE rb_dbl_hash(double d);
1540
1541/*
1542 * call-seq:
1543 * hash -> integer
1544 *
1545 * Returns the integer hash value for +self+.
1546 *
1547 * See also Object#hash.
1548 */
1549
1550static VALUE
1551flo_hash(VALUE num)
1552{
1553 return rb_dbl_hash(RFLOAT_VALUE(num));
1554}
1555
1556static VALUE
1557rb_dbl_hash(double d)
1558{
1559 return ST2FIX(rb_dbl_long_hash(d));
1560}
1561
1562VALUE
1563rb_dbl_cmp(double a, double b)
1564{
1565 if (isnan(a) || isnan(b)) return Qnil;
1566 if (a == b) return INT2FIX(0);
1567 if (a > b) return INT2FIX(1);
1568 if (a < b) return INT2FIX(-1);
1569 return Qnil;
1570}
1571
1572/*
1573 * call-seq:
1574 * self <=> other -> -1, 0, 1, or nil
1575 *
1576 * Compares +self+ and +other+.
1577 *
1578 * Returns:
1579 *
1580 * - +-1+, if +self+ is less than +other+.
1581 * - +0+, if +self+ is equal to +other+.
1582 * - +1+, if +self+ is greater than +other+.
1583 * - +nil+, if the two values are incommensurate.
1584 *
1585 * Examples:
1586 *
1587 * 2.0 <=> 2.1 # => -1
1588 * 2.0 <=> 2 # => 0
1589 * 2.0 <=> 2.0 # => 0
1590 * 2.0 <=> Rational(2, 1) # => 0
1591 * 2.0 <=> Complex(2, 0) # => 0
1592 * 2.0 <=> 1.9 # => 1
1593 * 2.0 <=> 'foo' # => nil
1594 *
1595 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1596 *
1597 * \Class \Float includes module Comparable,
1598 * each of whose methods uses Float#<=> for comparison.
1599 *
1600 */
1601
1602static VALUE
1603flo_cmp(VALUE x, VALUE y)
1604{
1605 double a, b;
1606 VALUE i;
1607
1608 a = RFLOAT_VALUE(x);
1609 if (isnan(a)) return Qnil;
1610 if (RB_INTEGER_TYPE_P(y)) {
1611 VALUE rel = rb_integer_float_cmp(y, x);
1612 if (FIXNUM_P(rel))
1613 return LONG2FIX(-FIX2LONG(rel));
1614 return rel;
1615 }
1616 else if (RB_FLOAT_TYPE_P(y)) {
1617 b = RFLOAT_VALUE(y);
1618 }
1619 else {
1620 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1621 if (RTEST(i)) {
1622 int j = rb_cmpint(i, x, y);
1623 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1624 return INT2FIX(j);
1625 }
1626 if (a > 0.0) return INT2FIX(1);
1627 return INT2FIX(-1);
1628 }
1629 return rb_num_coerce_cmp(x, y, id_cmp);
1630 }
1631 return rb_dbl_cmp(a, b);
1632}
1633
1634int
1635rb_float_cmp(VALUE x, VALUE y)
1636{
1637 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1638}
1639
1640/*
1641 * call-seq:
1642 * self > other -> true or false
1643 *
1644 * Returns whether the value of +self+ is greater than the value of +other+;
1645 * +other+ must be numeric, but may not be Complex:
1646 *
1647 * 2.0 > 1 # => true
1648 * 2.0 > 1.0 # => true
1649 * 2.0 > Rational(1, 2) # => true
1650 * 2.0 > 2.0 # => false
1651 *
1652 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1653 *
1654 */
1655
1656VALUE
1657rb_float_gt(VALUE x, VALUE y)
1658{
1659 double a, b;
1660
1661 a = RFLOAT_VALUE(x);
1662 if (RB_INTEGER_TYPE_P(y)) {
1663 VALUE rel = rb_integer_float_cmp(y, x);
1664 if (FIXNUM_P(rel))
1665 return RBOOL(-FIX2LONG(rel) > 0);
1666 return Qfalse;
1667 }
1668 else if (RB_FLOAT_TYPE_P(y)) {
1669 b = RFLOAT_VALUE(y);
1670 }
1671 else {
1672 return rb_num_coerce_relop(x, y, '>');
1673 }
1674 return RBOOL(a > b);
1675}
1676
1677/*
1678 * call-seq:
1679 * self >= other -> true or false
1680 *
1681 * Returns whether the value of +self+ is greater than or equal to the value of +other+;
1682 * +other+ must be numeric, but may not be Complex:
1683 *
1684 * 2.0 >= 1 # => true
1685 * 2.0 >= 1.0 # => true
1686 * 2.0 >= Rational(1, 2) # => true
1687 * 2.0 >= 2.0 # => true
1688 * 2.0 >= 2.1 # => false
1689 *
1690 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1691 *
1692 */
1693
1694static VALUE
1695flo_ge(VALUE x, VALUE y)
1696{
1697 double a, b;
1698
1699 a = RFLOAT_VALUE(x);
1700 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1701 VALUE rel = rb_integer_float_cmp(y, x);
1702 if (FIXNUM_P(rel))
1703 return RBOOL(-FIX2LONG(rel) >= 0);
1704 return Qfalse;
1705 }
1706 else if (RB_FLOAT_TYPE_P(y)) {
1707 b = RFLOAT_VALUE(y);
1708 }
1709 else {
1710 return rb_num_coerce_relop(x, y, idGE);
1711 }
1712 return RBOOL(a >= b);
1713}
1714
1715/*
1716 * call-seq:
1717 * self < other -> true or false
1718 *
1719 * Returns whether the value of +self+ is less than the value of +other+;
1720 * +other+ must be numeric, but may not be Complex:
1721 *
1722 * 2.0 < 3 # => true
1723 * 2.0 < 3.0 # => true
1724 * 2.0 < Rational(3, 1) # => true
1725 * 2.0 < 2.0 # => false
1726 *
1727 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1728 */
1729
1730static VALUE
1731flo_lt(VALUE x, VALUE y)
1732{
1733 double a, b;
1734
1735 a = RFLOAT_VALUE(x);
1736 if (RB_INTEGER_TYPE_P(y)) {
1737 VALUE rel = rb_integer_float_cmp(y, x);
1738 if (FIXNUM_P(rel))
1739 return RBOOL(-FIX2LONG(rel) < 0);
1740 return Qfalse;
1741 }
1742 else if (RB_FLOAT_TYPE_P(y)) {
1743 b = RFLOAT_VALUE(y);
1744 }
1745 else {
1746 return rb_num_coerce_relop(x, y, '<');
1747 }
1748 return RBOOL(a < b);
1749}
1750
1751/*
1752 * call-seq:
1753 * self <= other -> true or false
1754 *
1755 * Returns whether the value of +self+ is less than or equal to the value of +other+;
1756 * +other+ must be numeric, but may not be Complex:
1757 *
1758 * 2.0 <= 3 # => true
1759 * 2.0 <= 3.0 # => true
1760 * 2.0 <= Rational(3, 1) # => true
1761 * 2.0 <= 2.0 # => true
1762 * 2.0 <= 1.0 # => false
1763 *
1764 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1765 *
1766 */
1767
1768static VALUE
1769flo_le(VALUE x, VALUE y)
1770{
1771 double a, b;
1772
1773 a = RFLOAT_VALUE(x);
1774 if (RB_INTEGER_TYPE_P(y)) {
1775 VALUE rel = rb_integer_float_cmp(y, x);
1776 if (FIXNUM_P(rel))
1777 return RBOOL(-FIX2LONG(rel) <= 0);
1778 return Qfalse;
1779 }
1780 else if (RB_FLOAT_TYPE_P(y)) {
1781 b = RFLOAT_VALUE(y);
1782 }
1783 else {
1784 return rb_num_coerce_relop(x, y, idLE);
1785 }
1786 return RBOOL(a <= b);
1787}
1788
1789/*
1790 * call-seq:
1791 * eql?(other) -> true or false
1792 *
1793 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1794 * +false+ otherwise:
1795 *
1796 * 2.0.eql?(2.0) # => true
1797 * 2.0.eql?(1.0) # => false
1798 * 2.0.eql?(1) # => false
1799 * 2.0.eql?(Rational(2, 1)) # => false
1800 * 2.0.eql?(Complex(2, 0)) # => false
1801 *
1802 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1803 *
1804 * Related: Float#== (performs type conversions).
1805 */
1806
1807VALUE
1808rb_float_eql(VALUE x, VALUE y)
1809{
1810 if (RB_FLOAT_TYPE_P(y)) {
1811 double a = RFLOAT_VALUE(x);
1812 double b = RFLOAT_VALUE(y);
1813 return RBOOL(a == b);
1814 }
1815 return Qfalse;
1816}
1817
1818#define flo_eql rb_float_eql
1819
1820VALUE
1821rb_float_abs(VALUE flt)
1822{
1823 double val = fabs(RFLOAT_VALUE(flt));
1824 return DBL2NUM(val);
1825}
1826
1827/*
1828 * call-seq:
1829 * nan? -> true or false
1830 *
1831 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1832 *
1833 * f = -1.0 #=> -1.0
1834 * f.nan? #=> false
1835 * f = 0.0/0.0 #=> NaN
1836 * f.nan? #=> true
1837 */
1838
1839static VALUE
1840flo_is_nan_p(VALUE num)
1841{
1842 double value = RFLOAT_VALUE(num);
1843
1844 return RBOOL(isnan(value));
1845}
1846
1847/*
1848 * call-seq:
1849 * infinite? -> -1, 1, or nil
1850 *
1851 * Returns:
1852 *
1853 * - 1, if +self+ is <tt>Infinity</tt>.
1854 * - -1 if +self+ is <tt>-Infinity</tt>.
1855 * - +nil+, otherwise.
1856 *
1857 * Examples:
1858 *
1859 * f = 1.0/0.0 # => Infinity
1860 * f.infinite? # => 1
1861 * f = -1.0/0.0 # => -Infinity
1862 * f.infinite? # => -1
1863 * f = 1.0 # => 1.0
1864 * f.infinite? # => nil
1865 * f = 0.0/0.0 # => NaN
1866 * f.infinite? # => nil
1867 *
1868 */
1869
1870VALUE
1871rb_flo_is_infinite_p(VALUE num)
1872{
1873 double value = RFLOAT_VALUE(num);
1874
1875 if (isinf(value)) {
1876 return INT2FIX( value < 0 ? -1 : 1 );
1877 }
1878
1879 return Qnil;
1880}
1881
1882/*
1883 * call-seq:
1884 * finite? -> true or false
1885 *
1886 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1887 * +false+ otherwise:
1888 *
1889 * f = 2.0 # => 2.0
1890 * f.finite? # => true
1891 * f = 1.0/0.0 # => Infinity
1892 * f.finite? # => false
1893 * f = -1.0/0.0 # => -Infinity
1894 * f.finite? # => false
1895 * f = 0.0/0.0 # => NaN
1896 * f.finite? # => false
1897 *
1898 */
1899
1900VALUE
1901rb_flo_is_finite_p(VALUE num)
1902{
1903 double value = RFLOAT_VALUE(num);
1904
1905 return RBOOL(isfinite(value));
1906}
1907
1908static VALUE
1909flo_nextafter(VALUE flo, double value)
1910{
1911 double x, y;
1912 x = NUM2DBL(flo);
1913 y = nextafter(x, value);
1914 return DBL2NUM(y);
1915}
1916
1917/*
1918 * call-seq:
1919 * next_float -> float
1920 *
1921 * Returns the next-larger representable \Float.
1922 *
1923 * These examples show the internally stored values (64-bit hexadecimal)
1924 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
1925 *
1926 * f = 0.0 # 0x0000000000000000
1927 * f.next_float # 0x0000000000000001
1928 *
1929 * f = 0.01 # 0x3f847ae147ae147b
1930 * f.next_float # 0x3f847ae147ae147c
1931 *
1932 * In the remaining examples here, the output is shown in the usual way
1933 * (result +to_s+):
1934 *
1935 * 0.01.next_float # => 0.010000000000000002
1936 * 1.0.next_float # => 1.0000000000000002
1937 * 100.0.next_float # => 100.00000000000001
1938 *
1939 * f = 0.01
1940 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
1941 *
1942 * Output:
1943 *
1944 * 0 0x1.47ae147ae147bp-7 0.01
1945 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
1946 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
1947 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
1948 *
1949 * f = 0.0; 100.times { f += 0.1 }
1950 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
1951 * 10-f # => 1.9539925233402755e-14 # the floating point error.
1952 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
1953 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
1954 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
1955 * "%a" % 10 # => "0x1.4p+3"
1956 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
1957 *
1958 * Related: Float#prev_float
1959 *
1960 */
1961static VALUE
1962flo_next_float(VALUE vx)
1963{
1964 return flo_nextafter(vx, HUGE_VAL);
1965}
1966
1967/*
1968 * call-seq:
1969 * float.prev_float -> float
1970 *
1971 * Returns the next-smaller representable \Float.
1972 *
1973 * These examples show the internally stored values (64-bit hexadecimal)
1974 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
1975 *
1976 * f = 5e-324 # 0x0000000000000001
1977 * f.prev_float # 0x0000000000000000
1978 *
1979 * f = 0.01 # 0x3f847ae147ae147b
1980 * f.prev_float # 0x3f847ae147ae147a
1981 *
1982 * In the remaining examples here, the output is shown in the usual way
1983 * (result +to_s+):
1984 *
1985 * 0.01.prev_float # => 0.009999999999999998
1986 * 1.0.prev_float # => 0.9999999999999999
1987 * 100.0.prev_float # => 99.99999999999999
1988 *
1989 * f = 0.01
1990 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
1991 *
1992 * Output:
1993 *
1994 * 0 0x1.47ae147ae147bp-7 0.01
1995 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
1996 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
1997 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
1998 *
1999 * Related: Float#next_float.
2000 *
2001 */
2002static VALUE
2003flo_prev_float(VALUE vx)
2004{
2005 return flo_nextafter(vx, -HUGE_VAL);
2006}
2007
2008VALUE
2009rb_float_floor(VALUE num, int ndigits)
2010{
2011 double number;
2012 number = RFLOAT_VALUE(num);
2013 if (number == 0.0) {
2014 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2015 }
2016 if (ndigits > 0) {
2017 int binexp;
2018 double f, mul, res;
2019 frexp(number, &binexp);
2020 if (float_round_overflow(ndigits, binexp)) return num;
2021 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2022 return DBL2NUM(0.0);
2023 if (!ACCURATE_POW10(ndigits)) {
2024 return rb_flo_floor_by_rational(num, ndigits);
2025 }
2026 f = pow(10, ndigits);
2027 mul = floor(number * f);
2028 res = (mul + 1) / f;
2029 if (res > number)
2030 res = mul / f;
2031 return DBL2NUM(res);
2032 }
2033 else {
2034 num = dbl2ival(floor(number));
2035 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2036 return num;
2037 }
2038}
2039
2040static int
2041flo_ndigits(int argc, VALUE *argv)
2042{
2043 if (rb_check_arity(argc, 0, 1)) {
2044 return NUM2INT(argv[0]);
2045 }
2046 return 0;
2047}
2048
2049/*
2050 * :markup: markdown
2051 *
2052 * call-seq:
2053 * floor(ndigits = 0) -> float or integer
2054 *
2055 * Returns a float or integer that is a "floor" value for `self`,
2056 * as specified by `ndigits`,
2057 * which must be an
2058 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2059 *
2060 * When `self` is zero,
2061 * returns a zero value:
2062 * a float if `ndigits` is positive,
2063 * an integer otherwise:
2064 *
2065 * ```
2066 * f = 0.0 # => 0.0
2067 * f.floor(20) # => 0.0
2068 * f.floor(0) # => 0
2069 * f.floor(-20) # => 0
2070 * ```
2071 *
2072 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2073 * digits after the decimal point (as available):
2074 *
2075 * ```
2076 * f = 12345.6789
2077 * f.floor(1) # => 12345.6
2078 * f.floor(3) # => 12345.678
2079 * f.floor(30) # => 12345.6789
2080 * f = -12345.6789
2081 * f.floor(1) # => -12345.7
2082 * f.floor(3) # => -12345.679
2083 * f.floor(30) # => -12345.6789
2084 * ```
2085 *
2086 * When `self` is non-zero and `ndigits` is non-positive,
2087 * returns an integer value based on a computed granularity:
2088 *
2089 * - The granularity is `10 ** ndigits.abs`.
2090 * - The returned value is the largest multiple of the granularity
2091 * that is less than or equal to `self`.
2092 *
2093 * Examples with positive `self`:
2094 *
2095 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2096 * |--------:|------------:|--------------------------:|
2097 * | 0 | 1 | 12345 |
2098 * | -1 | 10 | 12340 |
2099 * | -2 | 100 | 12300 |
2100 * | -3 | 1000 | 12000 |
2101 * | -4 | 10000 | 10000 |
2102 * | -5 | 100000 | 0 |
2103 *
2104 * Examples with negative `self`:
2105 *
2106 * | ndigits | Granularity | -12345.6789.floor(ndigits) |
2107 * |--------:|------------:|---------------------------:|
2108 * | 0 | 1 | -12346 |
2109 * | -1 | 10 | -12350 |
2110 * | -2 | 100 | -12400 |
2111 * | -3 | 1000 | -13000 |
2112 * | -4 | 10000 | -20000 |
2113 * | -5 | 100000 | -100000 |
2114 * | -6 | 1000000 | -1000000 |
2115 *
2116 * Note that the limited precision of floating-point arithmetic
2117 * may lead to surprising results:
2118 *
2119 * ```
2120 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2121 * ```
2122 *
2123 * Related: Float#ceil.
2124 *
2125 */
2126
2127static VALUE
2128flo_floor(int argc, VALUE *argv, VALUE num)
2129{
2130 int ndigits = flo_ndigits(argc, argv);
2131 return rb_float_floor(num, ndigits);
2132}
2133
2134/*
2135 * :markup: markdown
2136 *
2137 * call-seq:
2138 * ceil(ndigits = 0) -> float or integer
2139 *
2140 * Returns a numeric that is a "ceiling" value for `self`,
2141 * as specified by the given `ndigits`,
2142 * which must be an
2143 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2144 *
2145 * When `ndigits` is positive, returns a Float with `ndigits`
2146 * decimal digits after the decimal point
2147 * (as available, but no fewer than 1):
2148 *
2149 * ```
2150 * f = 12345.6789
2151 * f.ceil(1) # => 12345.7
2152 * f.ceil(3) # => 12345.679
2153 * f.ceil(30) # => 12345.6789
2154 * f = -12345.6789
2155 * f.ceil(1) # => -12345.6
2156 * f.ceil(3) # => -12345.678
2157 * f.ceil(30) # => -12345.6789
2158 * f = 0.0
2159 * f.ceil(1) # => 0.0
2160 * f.ceil(100) # => 0.0
2161 * ```
2162 *
2163 * When `ndigits` is non-positive,
2164 * returns an Integer based on a computed granularity:
2165 *
2166 * - The granularity is `10 ** ndigits.abs`.
2167 * - The returned value is the largest multiple of the granularity
2168 * that is less than or equal to `self`.
2169 *
2170 * Examples with positive `self`:
2171 *
2172 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2173 * |--------:|------------:|-------------------------:|
2174 * | 0 | 1 | 12346 |
2175 * | -1 | 10 | 12350 |
2176 * | -2 | 100 | 12400 |
2177 * | -3 | 1000 | 13000 |
2178 * | -4 | 10000 | 20000 |
2179 * | -5 | 100000 | 100000 |
2180 *
2181 * Examples with negative `self`:
2182 *
2183 * | ndigits | Granularity | -12345.6789.ceil(ndigits) |
2184 * |--------:|------------:|--------------------------:|
2185 * | 0 | 1 | -12345 |
2186 * | -1 | 10 | -12340 |
2187 * | -2 | 100 | -12300 |
2188 * | -3 | 1000 | -12000 |
2189 * | -4 | 10000 | -10000 |
2190 * | -5 | 100000 | 0 |
2191 *
2192 * When `self` is zero and `ndigits` is non-positive,
2193 * returns Integer zero:
2194 *
2195 * ```
2196 * 0.0.ceil(0) # => 0
2197 * 0.0.ceil(-1) # => 0
2198 * 0.0.ceil(-2) # => 0
2199 * ```
2200 *
2201 * Note that the limited precision of floating-point arithmetic
2202 * may lead to surprising results:
2203 *
2204 * ```
2205 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2206 * ```
2207 *
2208 * Related: Float#floor.
2209 *
2210 */
2211
2212static VALUE
2213flo_ceil(int argc, VALUE *argv, VALUE num)
2214{
2215 int ndigits = flo_ndigits(argc, argv);
2216 return rb_float_ceil(num, ndigits);
2217}
2218
2219VALUE
2220rb_float_ceil(VALUE num, int ndigits)
2221{
2222 double number, f;
2223
2224 number = RFLOAT_VALUE(num);
2225 if (number == 0.0) {
2226 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2227 }
2228 if (ndigits > 0) {
2229 int binexp;
2230 frexp(number, &binexp);
2231 if (float_round_overflow(ndigits, binexp)) return num;
2232 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2233 return DBL2NUM(0.0);
2234 if (!ACCURATE_POW10(ndigits)) {
2235 return rb_flo_ceil_by_rational(num, ndigits);
2236 }
2237 f = pow(10, ndigits);
2238 f = ceil(number * f) / f;
2239 return DBL2NUM(f);
2240 }
2241 else {
2242 num = dbl2ival(ceil(number));
2243 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2244 return num;
2245 }
2246}
2247
2248static int
2249int_round_zero_p(VALUE num, int ndigits)
2250{
2251 long bytes;
2252 /* If 10**N / 2 > num, then return 0 */
2253 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2254 if (FIXNUM_P(num)) {
2255 bytes = sizeof(long);
2256 }
2257 else if (RB_BIGNUM_TYPE_P(num)) {
2258 bytes = rb_big_size(num);
2259 }
2260 else {
2261 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2262 }
2263 return (-0.415241 * ndigits - 0.125 > bytes);
2264}
2265
2266static SIGNED_VALUE
2267int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2268{
2269 SIGNED_VALUE z = +(x + y / 2) / y;
2270 if ((z * y - x) * 2 == y) {
2271 z &= ~1;
2272 }
2273 return z * y;
2274}
2275
2276static SIGNED_VALUE
2277int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2278{
2279 return (x + y / 2) / y * y;
2280}
2281
2282static SIGNED_VALUE
2283int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2284{
2285 return (x + y / 2 - 1) / y * y;
2286}
2287
2288static int
2289int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2290{
2291 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2292}
2293
2294static int
2295int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2296{
2297 return int_pos_p(num);
2298}
2299
2300static int
2301int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2302{
2303 return int_neg_p(num);
2304}
2305
2306/*
2307 * Assumes num is an \Integer, ndigits <= 0
2308 */
2309static VALUE
2310rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2311{
2312 VALUE n, f, h, r;
2313
2314 if (int_round_zero_p(num, ndigits)) {
2315 return INT2FIX(0);
2316 }
2317
2318 f = int_pow(10, -ndigits);
2319 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2320 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2321 int neg = x < 0;
2322 if (neg) x = -x;
2323 x = ROUND_CALL(mode, int_round, (x, y));
2324 if (neg) x = -x;
2325 return LONG2NUM(x);
2326 }
2327 if (RB_FLOAT_TYPE_P(f)) {
2328 /* then int_pow overflow */
2329 return INT2FIX(0);
2330 }
2331 h = rb_int_idiv(f, INT2FIX(2));
2332 r = rb_int_modulo(num, f);
2333 n = rb_int_minus(num, r);
2334 r = rb_int_cmp(r, h);
2335 if (FIXNUM_POSITIVE_P(r) ||
2336 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2337 n = rb_int_plus(n, f);
2338 }
2339 return n;
2340}
2341
2342static VALUE
2343rb_int_floor(VALUE num, int ndigits)
2344{
2345 VALUE f = int_pow(10, -ndigits);
2346 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2347 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2348 int neg = x < 0;
2349 if (neg) x = -x + y - 1;
2350 x = x / y * y;
2351 if (neg) x = -x;
2352 return LONG2NUM(x);
2353 }
2354 else {
2355 bool neg = int_neg_p(num);
2356 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2357 num = rb_int_mul(rb_int_div(num, f), f);
2358 if (neg) num = rb_int_uminus(num);
2359 return num;
2360 }
2361}
2362
2363static VALUE
2364rb_int_ceil(VALUE num, int ndigits)
2365{
2366 VALUE f = int_pow(10, -ndigits);
2367 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2368 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2369 int neg = x < 0;
2370 if (neg) x = -x;
2371 else x += y - 1;
2372 x = (x / y) * y;
2373 if (neg) x = -x;
2374 return LONG2NUM(x);
2375 }
2376 else {
2377 bool neg = int_neg_p(num);
2378 if (neg)
2379 num = rb_int_uminus(num);
2380 else
2381 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2382 num = rb_int_mul(rb_int_div(num, f), f);
2383 if (neg) num = rb_int_uminus(num);
2384 return num;
2385 }
2386}
2387
2388VALUE
2389rb_int_truncate(VALUE num, int ndigits)
2390{
2391 VALUE f;
2392 VALUE m;
2393
2394 if (int_round_zero_p(num, ndigits))
2395 return INT2FIX(0);
2396 f = int_pow(10, -ndigits);
2397 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2398 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2399 int neg = x < 0;
2400 if (neg) x = -x;
2401 x = x / y * y;
2402 if (neg) x = -x;
2403 return LONG2NUM(x);
2404 }
2405 if (RB_FLOAT_TYPE_P(f)) {
2406 /* then int_pow overflow */
2407 return INT2FIX(0);
2408 }
2409 m = rb_int_modulo(num, f);
2410 if (int_neg_p(num)) {
2411 return rb_int_plus(num, rb_int_minus(f, m));
2412 }
2413 else {
2414 return rb_int_minus(num, m);
2415 }
2416}
2417
2418/*
2419 * call-seq:
2420 * round(ndigits = 0, half: :up) -> integer or float
2421 *
2422 * Returns +self+ rounded to the nearest value with
2423 * a precision of +ndigits+ decimal digits.
2424 *
2425 * When +ndigits+ is non-negative, returns a float with +ndigits+
2426 * after the decimal point (as available):
2427 *
2428 * f = 12345.6789
2429 * f.round(1) # => 12345.7
2430 * f.round(3) # => 12345.679
2431 * f = -12345.6789
2432 * f.round(1) # => -12345.7
2433 * f.round(3) # => -12345.679
2434 *
2435 * When +ndigits+ is negative, returns an integer
2436 * with at least <tt>ndigits.abs</tt> trailing zeros:
2437 *
2438 * f = 12345.6789
2439 * f.round(0) # => 12346
2440 * f.round(-3) # => 12000
2441 * f = -12345.6789
2442 * f.round(0) # => -12346
2443 * f.round(-3) # => -12000
2444 *
2445 * If keyword argument +half+ is given,
2446 * and +self+ is equidistant from the two candidate values,
2447 * the rounding is according to the given +half+ value:
2448 *
2449 * - +:up+ or +nil+: round away from zero:
2450 *
2451 * 2.5.round(half: :up) # => 3
2452 * 3.5.round(half: :up) # => 4
2453 * (-2.5).round(half: :up) # => -3
2454 *
2455 * - +:down+: round toward zero:
2456 *
2457 * 2.5.round(half: :down) # => 2
2458 * 3.5.round(half: :down) # => 3
2459 * (-2.5).round(half: :down) # => -2
2460 *
2461 * - +:even+: round toward the candidate whose last nonzero digit is even:
2462 *
2463 * 2.5.round(half: :even) # => 2
2464 * 3.5.round(half: :even) # => 4
2465 * (-2.5).round(half: :even) # => -2
2466 *
2467 * Raises and exception if the value for +half+ is invalid.
2468 *
2469 * Related: Float#truncate.
2470 *
2471 */
2472
2473static VALUE
2474flo_round(int argc, VALUE *argv, VALUE num)
2475{
2476 double number, f, x;
2477 VALUE nd, opt;
2478 int ndigits = 0;
2479 enum ruby_num_rounding_mode mode;
2480
2481 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2482 ndigits = NUM2INT(nd);
2483 }
2484 mode = rb_num_get_rounding_option(opt);
2485 number = RFLOAT_VALUE(num);
2486 if (number == 0.0) {
2487 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2488 }
2489 if (ndigits < 0) {
2490 return rb_int_round(flo_to_i(num), ndigits, mode);
2491 }
2492 if (ndigits == 0) {
2493 x = ROUND_CALL(mode, round, (number, 1.0));
2494 return dbl2ival(x);
2495 }
2496 if (isfinite(number)) {
2497 int binexp;
2498 frexp(number, &binexp);
2499 if (float_round_overflow(ndigits, binexp)) return num;
2500 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2501 if (!ACCURATE_POW10(ndigits)) {
2502 return rb_flo_round_by_rational(num, ndigits, mode);
2503 }
2504 f = pow(10, ndigits);
2505 x = ROUND_CALL(mode, round, (number, f));
2506 return DBL2NUM(x / f);
2507 }
2508 return num;
2509}
2510
2511static int
2512float_round_overflow(int ndigits, int binexp)
2513{
2514 enum {float_dig = DBL_DIG+2};
2515
2516/* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2517 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2518 Recall that up to float_dig digits can be needed to represent a double,
2519 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2520 will be an integer and thus the result is the original number.
2521 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2522 if ndigits + exp < 0, the result is 0.
2523 We have:
2524 2 ** (binexp-1) <= |number| < 2 ** binexp
2525 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2526 If binexp >= 0, and since log_2(10) = 3.322259:
2527 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2528 floor(binexp/4) <= exp <= ceil(binexp/3)
2529 If binexp <= 0, swap the /4 and the /3
2530 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2531 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2532*/
2533 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2534 return TRUE;
2535 }
2536 return FALSE;
2537}
2538
2539static int
2540float_round_underflow(int ndigits, int binexp)
2541{
2542 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2543 return TRUE;
2544 }
2545 return FALSE;
2546}
2547
2548/*
2549 * call-seq:
2550 * to_i -> integer
2551 *
2552 * Returns +self+ truncated to an Integer.
2553 *
2554 * 1.2.to_i # => 1
2555 * (-1.2).to_i # => -1
2556 *
2557 * Note that the limited precision of floating-point arithmetic
2558 * may lead to surprising results:
2559 *
2560 * (0.3 / 0.1).to_i # => 2 (!)
2561 *
2562 */
2563
2564static VALUE
2565flo_to_i(VALUE num)
2566{
2567 double f = RFLOAT_VALUE(num);
2568
2569 if (f > 0.0) f = floor(f);
2570 if (f < 0.0) f = ceil(f);
2571
2572 return dbl2ival(f);
2573}
2574
2575VALUE
2576rb_flo_to_i(VALUE num)
2577{
2578 return flo_to_i(num);
2579}
2580
2581/*
2582 * call-seq:
2583 * truncate(ndigits = 0) -> float or integer
2584 *
2585 * Returns +self+ truncated (toward zero) to
2586 * a precision of +ndigits+ decimal digits.
2587 *
2588 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2589 * after the decimal point (as available):
2590 *
2591 * f = 12345.6789
2592 * f.truncate(1) # => 12345.6
2593 * f.truncate(3) # => 12345.678
2594 * f = -12345.6789
2595 * f.truncate(1) # => -12345.6
2596 * f.truncate(3) # => -12345.678
2597 *
2598 * When +ndigits+ is negative, returns an integer
2599 * with at least <tt>ndigits.abs</tt> trailing zeros:
2600 *
2601 * f = 12345.6789
2602 * f.truncate(0) # => 12345
2603 * f.truncate(-3) # => 12000
2604 * f = -12345.6789
2605 * f.truncate(0) # => -12345
2606 * f.truncate(-3) # => -12000
2607 *
2608 * Note that the limited precision of floating-point arithmetic
2609 * may lead to surprising results:
2610 *
2611 * (0.3 / 0.1).truncate #=> 2 (!)
2612 *
2613 * Related: Float#round.
2614 *
2615 */
2616static VALUE
2617flo_truncate(int argc, VALUE *argv, VALUE num)
2618{
2619 if (signbit(RFLOAT_VALUE(num)))
2620 return flo_ceil(argc, argv, num);
2621 else
2622 return flo_floor(argc, argv, num);
2623}
2624
2625/*
2626 * call-seq:
2627 * floor(ndigits = 0) -> float or integer
2628 *
2629 * Returns the largest float or integer that is less than or equal to +self+,
2630 * as specified by the given +ndigits+,
2631 * which must be an
2632 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2633 *
2634 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2635 *
2636 * Related: #ceil, Float#floor.
2637 */
2638
2639static VALUE
2640num_floor(int argc, VALUE *argv, VALUE num)
2641{
2642 return flo_floor(argc, argv, rb_Float(num));
2643}
2644
2645/*
2646 * call-seq:
2647 * ceil(ndigits = 0) -> float or integer
2648 *
2649 * Returns the smallest float or integer that is greater than or equal to +self+,
2650 * as specified by the given +ndigits+,
2651 * which must be an
2652 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2653 *
2654 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2655 *
2656 * Related: #floor, Float#ceil.
2657 */
2658
2659static VALUE
2660num_ceil(int argc, VALUE *argv, VALUE num)
2661{
2662 return flo_ceil(argc, argv, rb_Float(num));
2663}
2664
2665/*
2666 * call-seq:
2667 * round(digits = 0) -> integer or float
2668 *
2669 * Returns +self+ rounded to the nearest value with
2670 * a precision of +digits+ decimal digits.
2671 *
2672 * \Numeric implements this by converting +self+ to a Float and
2673 * invoking Float#round.
2674 */
2675
2676static VALUE
2677num_round(int argc, VALUE* argv, VALUE num)
2678{
2679 return flo_round(argc, argv, rb_Float(num));
2680}
2681
2682/*
2683 * call-seq:
2684 * truncate(digits = 0) -> integer or float
2685 *
2686 * Returns +self+ truncated (toward zero) to
2687 * a precision of +digits+ decimal digits.
2688 *
2689 * \Numeric implements this by converting +self+ to a Float and
2690 * invoking Float#truncate.
2691 */
2692
2693static VALUE
2694num_truncate(int argc, VALUE *argv, VALUE num)
2695{
2696 return flo_truncate(argc, argv, rb_Float(num));
2697}
2698
2699double
2700ruby_float_step_size(double beg, double end, double unit, int excl)
2701{
2702 const double epsilon = DBL_EPSILON;
2703 double d, n, err;
2704
2705 if (unit == 0) {
2706 return HUGE_VAL;
2707 }
2708 if (isinf(unit)) {
2709 return unit > 0 ? beg <= end : beg >= end;
2710 }
2711 n= (end - beg)/unit;
2712 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2713 if (err>0.5) err=0.5;
2714 if (excl) {
2715 if (n<=0) return 0;
2716 if (n<1)
2717 n = 0;
2718 else
2719 n = floor(n - err);
2720 d = +((n + 1) * unit) + beg;
2721 if (beg < end) {
2722 if (d < end)
2723 n++;
2724 }
2725 else if (beg > end) {
2726 if (d > end)
2727 n++;
2728 }
2729 }
2730 else {
2731 if (n<0) return 0;
2732 n = floor(n + err);
2733 d = +((n + 1) * unit) + beg;
2734 if (beg < end) {
2735 if (d <= end)
2736 n++;
2737 }
2738 else if (beg > end) {
2739 if (d >= end)
2740 n++;
2741 }
2742 }
2743 return n+1;
2744}
2745
2746int
2747ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2748{
2749 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2750 double unit = NUM2DBL(step);
2751 double beg = NUM2DBL(from);
2752 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2753 double n = ruby_float_step_size(beg, end, unit, excl);
2754 long i;
2755
2756 if (isinf(unit)) {
2757 /* if unit is infinity, i*unit+beg is NaN */
2758 if (n) rb_yield(DBL2NUM(beg));
2759 }
2760 else if (unit == 0) {
2761 VALUE val = DBL2NUM(beg);
2762 for (;;)
2763 rb_yield(val);
2764 }
2765 else {
2766 for (i=0; i<n; i++) {
2767 double d = i*unit+beg;
2768 if (unit >= 0 ? end < d : d < end) d = end;
2769 rb_yield(DBL2NUM(d));
2770 }
2771 }
2772 return TRUE;
2773 }
2774 return FALSE;
2775}
2776
2777VALUE
2778ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2779{
2780 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2781 long delta, diff;
2782
2783 diff = FIX2LONG(step);
2784 if (diff == 0) {
2785 return DBL2NUM(HUGE_VAL);
2786 }
2787 delta = FIX2LONG(to) - FIX2LONG(from);
2788 if (diff < 0) {
2789 diff = -diff;
2790 delta = -delta;
2791 }
2792 if (excl) {
2793 delta--;
2794 }
2795 if (delta < 0) {
2796 return INT2FIX(0);
2797 }
2798 return ULONG2NUM(delta / diff + 1UL);
2799 }
2800 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2801 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2802
2803 if (isinf(n)) return DBL2NUM(n);
2804 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2805 return rb_dbl2big(n);
2806 }
2807 else {
2808 VALUE result;
2809 ID cmp = '>';
2810 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2811 case 0: return DBL2NUM(HUGE_VAL);
2812 case -1: cmp = '<'; break;
2813 }
2814 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2815 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2816 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2817 result = rb_funcall(result, '+', 1, INT2FIX(1));
2818 }
2819 return result;
2820 }
2821}
2822
2823static int
2824num_step_negative_p(VALUE num)
2825{
2826 const ID mid = '<';
2827 VALUE zero = INT2FIX(0);
2828 VALUE r;
2829
2830 if (FIXNUM_P(num)) {
2831 if (method_basic_p(rb_cInteger))
2832 return (SIGNED_VALUE)num < 0;
2833 }
2834 else if (RB_BIGNUM_TYPE_P(num)) {
2835 if (method_basic_p(rb_cInteger))
2836 return BIGNUM_NEGATIVE_P(num);
2837 }
2838
2839 r = rb_check_funcall(num, '>', 1, &zero);
2840 if (UNDEF_P(r)) {
2841 coerce_failed(num, INT2FIX(0));
2842 }
2843 return !RTEST(r);
2844}
2845
2846static int
2847num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2848{
2849 VALUE hash;
2850
2851 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2852 if (!NIL_P(hash)) {
2853 ID keys[2];
2854 VALUE values[2];
2855 keys[0] = id_to;
2856 keys[1] = id_by;
2857 rb_get_kwargs(hash, keys, 0, 2, values);
2858 if (!UNDEF_P(values[0])) {
2859 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2860 *to = values[0];
2861 }
2862 if (!UNDEF_P(values[1])) {
2863 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2864 *by = values[1];
2865 }
2866 }
2867
2868 return argc;
2869}
2870
2871static int
2872num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2873{
2874 int desc;
2875 if (!UNDEF_P(by)) {
2876 *step = by;
2877 }
2878 else {
2879 /* compatibility */
2880 if (argc > 1 && NIL_P(*step)) {
2881 rb_raise(rb_eTypeError, "step must be numeric");
2882 }
2883 }
2884 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2885 rb_raise(rb_eArgError, "step can't be 0");
2886 }
2887 if (NIL_P(*step)) {
2888 *step = INT2FIX(1);
2889 }
2890 desc = num_step_negative_p(*step);
2891 if (fix_nil && NIL_P(*to)) {
2892 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2893 }
2894 return desc;
2895}
2896
2897static int
2898num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2899{
2900 VALUE by = Qundef;
2901 argc = num_step_extract_args(argc, argv, to, step, &by);
2902 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2903}
2904
2905static VALUE
2906num_step_size(VALUE from, VALUE args, VALUE eobj)
2907{
2908 VALUE to, step;
2909 int argc = args ? RARRAY_LENINT(args) : 0;
2910 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2911
2912 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2913
2914 return ruby_num_interval_step_size(from, to, step, FALSE);
2915}
2916
2917/*
2918 * call-seq:
2919 * step(to = nil, by = 1) {|n| ... } -> self
2920 * step(to = nil, by = 1) -> enumerator
2921 * step(to = nil, by: 1) {|n| ... } -> self
2922 * step(to = nil, by: 1) -> enumerator
2923 * step(by: 1, to: ) {|n| ... } -> self
2924 * step(by: 1, to: ) -> enumerator
2925 * step(by: , to: nil) {|n| ... } -> self
2926 * step(by: , to: nil) -> enumerator
2927 *
2928 * Generates a sequence of numbers; with a block given, traverses the sequence.
2929 *
2930 * Of the Core and Standard Library classes,
2931 * Integer, Float, and Rational use this implementation.
2932 *
2933 * A quick example:
2934 *
2935 * squares = []
2936 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2937 * squares # => [1, 9, 25, 49, 81]
2938 *
2939 * The generated sequence:
2940 *
2941 * - Begins with +self+.
2942 * - Continues at intervals of +by+ (which may not be zero).
2943 * - Ends with the last number that is within or equal to +to+;
2944 * that is, less than or equal to +to+ if +by+ is positive,
2945 * greater than or equal to +to+ if +by+ is negative.
2946 * If +to+ is +nil+, the sequence is of infinite length.
2947 *
2948 * If a block is given, calls the block with each number in the sequence;
2949 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2950 *
2951 * <b>Keyword Arguments</b>
2952 *
2953 * With keyword arguments +by+ and +to+,
2954 * their values (or defaults) determine the step and limit:
2955 *
2956 * # Both keywords given.
2957 * squares = []
2958 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2959 * squares # => [16, 36, 64, 100]
2960 * cubes = []
2961 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2962 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2963 * squares = []
2964 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2965 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2966 *
2967 * squares = []
2968 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2969 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2970 *
2971 * # Only keyword to given.
2972 * squares = []
2973 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
2974 * squares # => [16, 25, 36, 49, 64, 81, 100]
2975 * # Only by given.
2976 *
2977 * # Only keyword by given
2978 * squares = []
2979 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
2980 * squares # => [16, 36, 64, 100, 144]
2981 *
2982 * # No block given.
2983 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
2984 * e.class # => Enumerator::ArithmeticSequence
2985 *
2986 * <b>Positional Arguments</b>
2987 *
2988 * With optional positional arguments +to+ and +by+,
2989 * their values (or defaults) determine the step and limit:
2990 *
2991 * squares = []
2992 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
2993 * squares # => [16, 36, 64, 100]
2994 * squares = []
2995 * 4.step(10) {|i| squares.push(i*i) }
2996 * squares # => [16, 25, 36, 49, 64, 81, 100]
2997 * squares = []
2998 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
2999 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3000 *
3001 * <b>Implementation Notes</b>
3002 *
3003 * If all the arguments are integers, the loop operates using an integer
3004 * counter.
3005 *
3006 * If any of the arguments are floating point numbers, all are converted
3007 * to floats, and the loop is executed
3008 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3009 * where <i>n = (limit - self)/step</i>.
3010 *
3011 */
3012
3013static VALUE
3014num_step(int argc, VALUE *argv, VALUE from)
3015{
3016 VALUE to, step;
3017 int desc, inf;
3018
3019 if (!rb_block_given_p()) {
3020 VALUE by = Qundef;
3021
3022 num_step_extract_args(argc, argv, &to, &step, &by);
3023 if (!UNDEF_P(by)) {
3024 step = by;
3025 }
3026 if (NIL_P(step)) {
3027 step = INT2FIX(1);
3028 }
3029 else if (rb_equal(step, INT2FIX(0))) {
3030 rb_raise(rb_eArgError, "step can't be 0");
3031 }
3032 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3034 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3035 num_step_size, from, to, step, FALSE);
3036 }
3037
3038 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3039 }
3040
3041 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3042 if (rb_equal(step, INT2FIX(0))) {
3043 inf = 1;
3044 }
3045 else if (RB_FLOAT_TYPE_P(to)) {
3046 double f = RFLOAT_VALUE(to);
3047 inf = isinf(f) && (signbit(f) ? desc : !desc);
3048 }
3049 else inf = 0;
3050
3051 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3052 long i = FIX2LONG(from);
3053 long diff = FIX2LONG(step);
3054
3055 if (inf) {
3056 for (;; i += diff)
3057 rb_yield(LONG2FIX(i));
3058 }
3059 else {
3060 long end = FIX2LONG(to);
3061
3062 if (desc) {
3063 for (; i >= end; i += diff)
3064 rb_yield(LONG2FIX(i));
3065 }
3066 else {
3067 for (; i <= end; i += diff)
3068 rb_yield(LONG2FIX(i));
3069 }
3070 }
3071 }
3072 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3073 VALUE i = from;
3074
3075 if (inf) {
3076 for (;; i = rb_funcall(i, '+', 1, step))
3077 rb_yield(i);
3078 }
3079 else {
3080 ID cmp = desc ? '<' : '>';
3081
3082 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3083 rb_yield(i);
3084 }
3085 }
3086 return from;
3087}
3088
3089static char *
3090out_of_range_float(char (*pbuf)[24], VALUE val)
3091{
3092 char *const buf = *pbuf;
3093 char *s;
3094
3095 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3096 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3097 return buf;
3098}
3099
3100#define FLOAT_OUT_OF_RANGE(val, type) do { \
3101 char buf[24]; \
3102 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3103 out_of_range_float(&buf, (val))); \
3104} while (0)
3105
3106#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3107#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3108#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3109#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3110 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3111 LONG_MIN <= (n): \
3112 LONG_MIN_MINUS_ONE < (n))
3113
3114long
3116{
3117 again:
3118 if (NIL_P(val)) {
3119 rb_no_implicit_conversion(val, "Integer");
3120 }
3121
3122 if (FIXNUM_P(val)) return FIX2LONG(val);
3123
3124 else if (RB_FLOAT_TYPE_P(val)) {
3125 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3126 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3127 return (long)RFLOAT_VALUE(val);
3128 }
3129 else {
3130 FLOAT_OUT_OF_RANGE(val, "integer");
3131 }
3132 }
3133 else if (RB_BIGNUM_TYPE_P(val)) {
3134 return rb_big2long(val);
3135 }
3136 else {
3137 val = rb_to_int(val);
3138 goto again;
3139 }
3140}
3141
3142static unsigned long
3143rb_num2ulong_internal(VALUE val, int *wrap_p)
3144{
3145 again:
3146 if (NIL_P(val)) {
3147 rb_no_implicit_conversion(val, "Integer");
3148 }
3149
3150 if (FIXNUM_P(val)) {
3151 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3152 if (wrap_p)
3153 *wrap_p = l < 0;
3154 return (unsigned long)l;
3155 }
3156 else if (RB_FLOAT_TYPE_P(val)) {
3157 double d = RFLOAT_VALUE(val);
3158 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3159 if (wrap_p)
3160 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3161 if (0 <= d)
3162 return (unsigned long)d;
3163 return (unsigned long)(long)d;
3164 }
3165 else {
3166 FLOAT_OUT_OF_RANGE(val, "integer");
3167 }
3168 }
3169 else if (RB_BIGNUM_TYPE_P(val)) {
3170 {
3171 unsigned long ul = rb_big2ulong(val);
3172 if (wrap_p)
3173 *wrap_p = BIGNUM_NEGATIVE_P(val);
3174 return ul;
3175 }
3176 }
3177 else {
3178 val = rb_to_int(val);
3179 goto again;
3180 }
3181}
3182
3183unsigned long
3185{
3186 return rb_num2ulong_internal(val, NULL);
3187}
3188
3189void
3191{
3192 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3193 num, num < 0 ? "small" : "big");
3194}
3195
3196#if SIZEOF_INT < SIZEOF_LONG
3197static void
3198check_int(long num)
3199{
3200 if ((long)(int)num != num) {
3201 rb_out_of_int(num);
3202 }
3203}
3204
3205static void
3206check_uint(unsigned long num, int sign)
3207{
3208 if (sign) {
3209 /* minus */
3210 if (num < (unsigned long)INT_MIN)
3211 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3212 }
3213 else {
3214 /* plus */
3215 if (UINT_MAX < num)
3216 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3217 }
3218}
3219
3220long
3221rb_num2int(VALUE val)
3222{
3223 long num = rb_num2long(val);
3224
3225 check_int(num);
3226 return num;
3227}
3228
3229long
3230rb_fix2int(VALUE val)
3231{
3232 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3233
3234 check_int(num);
3235 return num;
3236}
3237
3238unsigned long
3239rb_num2uint(VALUE val)
3240{
3241 int wrap;
3242 unsigned long num = rb_num2ulong_internal(val, &wrap);
3243
3244 check_uint(num, wrap);
3245 return num;
3246}
3247
3248unsigned long
3249rb_fix2uint(VALUE val)
3250{
3251 unsigned long num;
3252
3253 if (!FIXNUM_P(val)) {
3254 return rb_num2uint(val);
3255 }
3256 num = FIX2ULONG(val);
3257
3258 check_uint(num, FIXNUM_NEGATIVE_P(val));
3259 return num;
3260}
3261#else
3262long
3264{
3265 return rb_num2long(val);
3266}
3267
3268long
3270{
3271 return FIX2INT(val);
3272}
3273
3274unsigned long
3276{
3277 return rb_num2ulong(val);
3278}
3279
3280unsigned long
3282{
3283 return RB_FIX2ULONG(val);
3284}
3285#endif
3286
3287NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3288static void
3289rb_out_of_short(SIGNED_VALUE num)
3290{
3291 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3292 num, num < 0 ? "small" : "big");
3293}
3294
3295static void
3296check_short(long num)
3297{
3298 if ((long)(short)num != num) {
3299 rb_out_of_short(num);
3300 }
3301}
3302
3303static void
3304check_ushort(unsigned long num, int sign)
3305{
3306 if (sign) {
3307 /* minus */
3308 if (num < (unsigned long)SHRT_MIN)
3309 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3310 }
3311 else {
3312 /* plus */
3313 if (USHRT_MAX < num)
3314 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3315 }
3316}
3317
3318short
3320{
3321 long num = rb_num2long(val);
3322
3323 check_short(num);
3324 return num;
3325}
3326
3327short
3329{
3330 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3331
3332 check_short(num);
3333 return num;
3334}
3335
3336unsigned short
3338{
3339 int wrap;
3340 unsigned long num = rb_num2ulong_internal(val, &wrap);
3341
3342 check_ushort(num, wrap);
3343 return num;
3344}
3345
3346unsigned short
3348{
3349 unsigned long num;
3350
3351 if (!FIXNUM_P(val)) {
3352 return rb_num2ushort(val);
3353 }
3354 num = FIX2ULONG(val);
3355
3356 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3357 return num;
3358}
3359
3360VALUE
3362{
3363 long v;
3364
3365 if (FIXNUM_P(val)) return val;
3366
3367 v = rb_num2long(val);
3368 if (!FIXABLE(v))
3369 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3370 return LONG2FIX(v);
3371}
3372
3373#if HAVE_LONG_LONG
3374
3375#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3376#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3377#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3378#ifndef ULLONG_MAX
3379#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3380#endif
3381#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3382 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3383 LLONG_MIN <= (n): \
3384 LLONG_MIN_MINUS_ONE < (n))
3385
3387rb_num2ll(VALUE val)
3388{
3389 if (NIL_P(val)) {
3390 rb_no_implicit_conversion(val, "Integer");
3391 }
3392
3393 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3394
3395 else if (RB_FLOAT_TYPE_P(val)) {
3396 double d = RFLOAT_VALUE(val);
3397 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3398 return (LONG_LONG)d;
3399 }
3400 else {
3401 FLOAT_OUT_OF_RANGE(val, "long long");
3402 }
3403 }
3404 else if (RB_BIGNUM_TYPE_P(val)) {
3405 return rb_big2ll(val);
3406 }
3407 else if (val == Qfalse || val == Qtrue || RB_TYPE_P(val, T_STRING)) {
3408 rb_no_implicit_conversion(val, "Integer");
3409 }
3410
3411 val = rb_to_int(val);
3412 return NUM2LL(val);
3413}
3414
3415unsigned LONG_LONG
3416rb_num2ull(VALUE val)
3417{
3418 if (NIL_P(val)) {
3419 rb_no_implicit_conversion(val, "Integer");
3420 }
3421 else if (FIXNUM_P(val)) {
3422 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3423 }
3424 else if (RB_FLOAT_TYPE_P(val)) {
3425 double d = RFLOAT_VALUE(val);
3426 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3427 if (0 <= d)
3428 return (unsigned LONG_LONG)d;
3429 return (unsigned LONG_LONG)(LONG_LONG)d;
3430 }
3431 else {
3432 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3433 }
3434 }
3435 else if (RB_BIGNUM_TYPE_P(val)) {
3436 return rb_big2ull(val);
3437 }
3438 else {
3439 val = rb_to_int(val);
3440 return NUM2ULL(val);
3441 }
3442}
3443
3444#endif /* HAVE_LONG_LONG */
3445
3446// Conversion functions for unified 128-bit integer structures,
3447// These work with or without native 128-bit integer support.
3448
3449#ifndef HAVE_UINT128_T
3450// Helper function to build 128-bit value from bignum digits (fallback path).
3451static inline void
3452rb_uint128_from_bignum_digits_fallback(rb_uint128_t *result, BDIGIT *digits, size_t length)
3453{
3454 // Build the 128-bit value from bignum digits:
3455 for (long i = length - 1; i >= 0; i--) {
3456 // Shift both low and high parts:
3457 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3458 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3459 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3460 }
3461}
3462
3463// Helper function to convert absolute value of negative bignum to two's complement.
3464// Ruby stores negative bignums as absolute values, so we need to convert to two's complement.
3465static inline void
3466rb_uint128_twos_complement_negate(rb_uint128_t *value)
3467{
3468 if (value->parts.low == 0) {
3469 value->parts.high = ~value->parts.high + 1;
3470 }
3471 else {
3472 value->parts.low = ~value->parts.low + 1;
3473 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3474 }
3475}
3476#endif
3477
3479rb_numeric_to_uint128(VALUE x)
3480{
3481 rb_uint128_t result = {0};
3482 if (RB_FIXNUM_P(x)) {
3483 long value = RB_FIX2LONG(x);
3484 if (value < 0) {
3485 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3486 }
3487#ifdef HAVE_UINT128_T
3488 result.value = (uint128_t)value;
3489#else
3490 result.parts.low = (uint64_t)value;
3491 result.parts.high = 0;
3492#endif
3493 return result;
3494 }
3495 else if (RB_BIGNUM_TYPE_P(x)) {
3496 if (BIGNUM_NEGATIVE_P(x)) {
3497 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3498 }
3499 size_t length = BIGNUM_LEN(x);
3500#ifdef HAVE_UINT128_T
3501 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3502 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3503 }
3504 BDIGIT *digits = BIGNUM_DIGITS(x);
3505 result.value = 0;
3506 for (long i = length - 1; i >= 0; i--) {
3507 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3508 }
3509#else
3510 // Check if bignum fits in 128 bits (16 bytes)
3511 if (length > roomof(16, SIZEOF_BDIGIT)) {
3512 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3513 }
3514 BDIGIT *digits = BIGNUM_DIGITS(x);
3515 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3516#endif
3517 return result;
3518 }
3519 else {
3520 rb_raise(rb_eTypeError, "not an integer");
3521 }
3522}
3523
3525rb_numeric_to_int128(VALUE x)
3526{
3527 rb_int128_t result = {0};
3528 if (RB_FIXNUM_P(x)) {
3529 long value = RB_FIX2LONG(x);
3530#ifdef HAVE_UINT128_T
3531 result.value = (int128_t)value;
3532#else
3533 if (value < 0) {
3534 // Two's complement representation: for negative values, sign extend
3535 // Convert to unsigned: for -1, we want all bits set
3536 result.parts.low = (uint64_t)value; // This will be the two's complement representation
3537 result.parts.high = UINT64_MAX; // Sign extend: all bits set for negative
3538 }
3539 else {
3540 result.parts.low = (uint64_t)value;
3541 result.parts.high = 0;
3542 }
3543#endif
3544 return result;
3545 }
3546 else if (RB_BIGNUM_TYPE_P(x)) {
3547 size_t length = BIGNUM_LEN(x);
3548#ifdef HAVE_UINT128_T
3549 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3550 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3551 }
3552 BDIGIT *digits = BIGNUM_DIGITS(x);
3553 uint128_t unsigned_result = 0;
3554 for (long i = length - 1; i >= 0; i--) {
3555 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3556 }
3557 if (BIGNUM_NEGATIVE_P(x)) {
3558 // Convert from two's complement
3559 // Maximum negative value is 2^127
3560 if (unsigned_result > ((uint128_t)1 << 127)) {
3561 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3562 }
3563 result.value = -(int128_t)(unsigned_result - 1) - 1;
3564 }
3565 else {
3566 // Maximum positive value is 2^127 - 1
3567 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3568 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3569 }
3570 result.value = (int128_t)unsigned_result;
3571 }
3572#else
3573 if (length > roomof(16, SIZEOF_BDIGIT)) {
3574 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3575 }
3576 BDIGIT *digits = BIGNUM_DIGITS(x);
3577 rb_uint128_t unsigned_result = {0};
3578 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3579 if (BIGNUM_NEGATIVE_P(x)) {
3580 // Check if value fits in signed 128-bit (max negative is 2^127)
3581 uint64_t max_neg_high = (uint64_t)1 << 63;
3582 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3583 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3584 }
3585 // Convert from absolute value to two's complement (Ruby stores negative as absolute value)
3586 rb_uint128_twos_complement_negate(&unsigned_result);
3587 result.parts.low = unsigned_result.parts.low;
3588 result.parts.high = (int64_t)unsigned_result.parts.high; // Sign extend
3589 }
3590 else {
3591 // Check if value fits in signed 128-bit (max positive is 2^127 - 1)
3592 // Max positive: high = 0x7FFFFFFFFFFFFFFF, low = 0xFFFFFFFFFFFFFFFF
3593 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3594 if (unsigned_result.parts.high > max_pos_high) {
3595 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3596 }
3597 result.parts.low = unsigned_result.parts.low;
3598 result.parts.high = unsigned_result.parts.high;
3599 }
3600#endif
3601 return result;
3602 }
3603 else {
3604 rb_raise(rb_eTypeError, "not an integer");
3605 }
3606}
3607
3608VALUE
3609rb_uint128_to_numeric(rb_uint128_t n)
3610{
3611#ifdef HAVE_UINT128_T
3612 if (n.value <= (uint128_t)RUBY_FIXNUM_MAX) {
3613 return LONG2FIX((long)n.value);
3614 }
3615 return rb_uint128t2big(n.value);
3616#else
3617 // If high part is zero and low part fits in fixnum
3618 if (n.parts.high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3619 return LONG2FIX((long)n.parts.low);
3620 }
3621 // Convert to bignum by building it from the two 64-bit parts
3622 VALUE bignum = rb_ull2big(n.parts.low);
3623 if (n.parts.high > 0) {
3624 VALUE high_bignum = rb_ull2big(n.parts.high);
3625 // Multiply high part by 2^64 and add to low part
3626 VALUE shifted_value = rb_int_lshift(high_bignum, INT2FIX(64));
3627 bignum = rb_int_plus(bignum, shifted_value);
3628 }
3629 return bignum;
3630#endif
3631}
3632
3633VALUE
3634rb_int128_to_numeric(rb_int128_t n)
3635{
3636#ifdef HAVE_UINT128_T
3637 if (FIXABLE(n.value)) {
3638 return LONG2FIX((long)n.value);
3639 }
3640 return rb_int128t2big(n.value);
3641#else
3642 int64_t high = (int64_t)n.parts.high;
3643 // If it's a small positive value that fits in fixnum
3644 if (high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3645 return LONG2FIX((long)n.parts.low);
3646 }
3647 // Check if it's negative (high bit of high part is set)
3648 if (high < 0) {
3649 // Negative value - convert from two's complement to absolute value
3650 rb_uint128_t unsigned_value = {0};
3651 if (n.parts.low == 0) {
3652 unsigned_value.parts.low = 0;
3653 unsigned_value.parts.high = ~n.parts.high + 1;
3654 }
3655 else {
3656 unsigned_value.parts.low = ~n.parts.low + 1;
3657 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3658 }
3659 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3660 return rb_int_uminus(bignum);
3661 }
3662 else {
3663 // Positive value
3664 union uint128_int128_conversion conversion = {
3665 .int128 = n
3666 };
3667 return rb_uint128_to_numeric(conversion.uint128);
3668 }
3669#endif
3670}
3671
3672/********************************************************************
3673 *
3674 * Document-class: Integer
3675 *
3676 * An \Integer object represents an integer value.
3677 *
3678 * You can create an \Integer object explicitly with:
3679 *
3680 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3681 *
3682 * You can convert certain objects to Integers with:
3683 *
3684 * - Method #Integer.
3685 *
3686 * An attempt to add a singleton method to an instance of this class
3687 * causes an exception to be raised.
3688 *
3689 * == What's Here
3690 *
3691 * First, what's elsewhere. Class \Integer:
3692 *
3693 * - Inherits from
3694 * {class Numeric}[rdoc-ref:Numeric@Whats+Here]
3695 * and {class Object}[rdoc-ref:Object@Whats+Here].
3696 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
3697 *
3698 * Here, class \Integer provides methods for:
3699 *
3700 * - {Querying}[rdoc-ref:Integer@Querying]
3701 * - {Comparing}[rdoc-ref:Integer@Comparing]
3702 * - {Converting}[rdoc-ref:Integer@Converting]
3703 * - {Other}[rdoc-ref:Integer@Other]
3704 *
3705 * === Querying
3706 *
3707 * - #allbits?: Returns whether all bits in +self+ are set.
3708 * - #anybits?: Returns whether any bits in +self+ are set.
3709 * - #nobits?: Returns whether no bits in +self+ are set.
3710 *
3711 * === Comparing
3712 *
3713 * - #<: Returns whether +self+ is less than the given value.
3714 * - #<=: Returns whether +self+ is less than or equal to the given value.
3715 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3716 * to, or greater than the given value.
3717 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3718 * value.
3719 * - #>: Returns whether +self+ is greater than the given value.
3720 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3721 *
3722 * === Converting
3723 *
3724 * - ::sqrt: Returns the integer square root of the given value.
3725 * - ::try_convert: Returns the given value converted to an \Integer.
3726 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3727 * - #&: Returns the bitwise AND of +self+ and the given value.
3728 * - #*: Returns the product of +self+ and the given value.
3729 * - #**: Returns the value of +self+ raised to the power of the given value.
3730 * - #+: Returns the sum of +self+ and the given value.
3731 * - #-: Returns the difference of +self+ and the given value.
3732 * - #/: Returns the quotient of +self+ and the given value.
3733 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3734 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3735 * - #[]: Returns a slice of bits from +self+.
3736 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3737 * - #|: Returns the bitwise OR of +self+ and the given value.
3738 * - #ceil: Returns the smallest number greater than or equal to +self+.
3739 * - #chr: Returns a 1-character string containing the character
3740 * represented by the value of +self+.
3741 * - #digits: Returns an array of integers representing the base-radix digits
3742 * of +self+.
3743 * - #div: Returns the integer result of dividing +self+ by the given value.
3744 * - #divmod: Returns a 2-element array containing the quotient and remainder
3745 * results of dividing +self+ by the given value.
3746 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3747 * - #floor: Returns the greatest number smaller than or equal to +self+.
3748 * - #pow: Returns the modular exponentiation of +self+.
3749 * - #pred: Returns the integer predecessor of +self+.
3750 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3751 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3752 * - #succ (aliased as #next): Returns the integer successor of +self+.
3753 * - #to_f: Returns +self+ converted to a Float.
3754 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3755 * representation of +self+ in the given radix.
3756 * - #truncate: Returns +self+ truncated to the given precision.
3757 *
3758 * === Other
3759 *
3760 * - #downto: Calls the given block with each integer value from +self+
3761 * down to the given value.
3762 * - #times: Calls the given block +self+ times with each integer
3763 * in <tt>(0..self-1)</tt>.
3764 * - #upto: Calls the given block with each integer value from +self+
3765 * up to the given value.
3766 *
3767 */
3768
3769VALUE
3770rb_int_odd_p(VALUE num)
3771{
3772 if (FIXNUM_P(num)) {
3773 return RBOOL(num & 2);
3774 }
3775 else {
3776 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3777 return rb_big_odd_p(num);
3778 }
3779}
3780
3781static VALUE
3782int_even_p(VALUE num)
3783{
3784 if (FIXNUM_P(num)) {
3785 return RBOOL((num & 2) == 0);
3786 }
3787 else {
3788 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3789 return rb_big_even_p(num);
3790 }
3791}
3792
3793VALUE
3794rb_int_even_p(VALUE num)
3795{
3796 return int_even_p(num);
3797}
3798
3799/*
3800 * call-seq:
3801 * allbits?(mask) -> true or false
3802 *
3803 * Returns +true+ if all bits that are set (=1) in +mask+
3804 * are also set in +self+; returns +false+ otherwise.
3805 *
3806 * Example values:
3807 *
3808 * 0b1010101 self
3809 * 0b1010100 mask
3810 * 0b1010100 self & mask
3811 * true self.allbits?(mask)
3812 *
3813 * 0b1010100 self
3814 * 0b1010101 mask
3815 * 0b1010100 self & mask
3816 * false self.allbits?(mask)
3817 *
3818 * Related: Integer#anybits?, Integer#nobits?.
3819 *
3820 */
3821
3822static VALUE
3823int_allbits_p(VALUE num, VALUE mask)
3824{
3825 mask = rb_to_int(mask);
3826 return rb_int_equal(rb_int_and(num, mask), mask);
3827}
3828
3829/*
3830 * call-seq:
3831 * anybits?(mask) -> true or false
3832 *
3833 * Returns +true+ if any bit that is set (=1) in +mask+
3834 * is also set in +self+; returns +false+ otherwise.
3835 *
3836 * Example values:
3837 *
3838 * 0b10000010 self
3839 * 0b11111111 mask
3840 * 0b10000010 self & mask
3841 * true self.anybits?(mask)
3842 *
3843 * 0b00000000 self
3844 * 0b11111111 mask
3845 * 0b00000000 self & mask
3846 * false self.anybits?(mask)
3847 *
3848 * Related: Integer#allbits?, Integer#nobits?.
3849 *
3850 */
3851
3852static VALUE
3853int_anybits_p(VALUE num, VALUE mask)
3854{
3855 mask = rb_to_int(mask);
3856 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3857}
3858
3859/*
3860 * call-seq:
3861 * nobits?(mask) -> true or false
3862 *
3863 * Returns +true+ if no bit that is set (=1) in +mask+
3864 * is also set in +self+; returns +false+ otherwise.
3865 *
3866 * Example values:
3867 *
3868 * 0b11110000 self
3869 * 0b00001111 mask
3870 * 0b00000000 self & mask
3871 * true self.nobits?(mask)
3872 *
3873 * 0b00000001 self
3874 * 0b11111111 mask
3875 * 0b00000001 self & mask
3876 * false self.nobits?(mask)
3877 *
3878 * Related: Integer#allbits?, Integer#anybits?.
3879 *
3880 */
3881
3882static VALUE
3883int_nobits_p(VALUE num, VALUE mask)
3884{
3885 mask = rb_to_int(mask);
3886 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3887}
3888
3889/*
3890 * call-seq:
3891 * succ -> next_integer
3892 *
3893 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3894 *
3895 * 1.succ #=> 2
3896 * -1.succ #=> 0
3897 *
3898 * Related: Integer#pred (predecessor value).
3899 */
3900
3901VALUE
3902rb_int_succ(VALUE num)
3903{
3904 if (FIXNUM_P(num)) {
3905 long i = FIX2LONG(num) + 1;
3906 return LONG2NUM(i);
3907 }
3908 if (RB_BIGNUM_TYPE_P(num)) {
3909 return rb_big_plus(num, INT2FIX(1));
3910 }
3911 return num_funcall1(num, '+', INT2FIX(1));
3912}
3913
3914#define int_succ rb_int_succ
3915
3916/*
3917 * call-seq:
3918 * pred -> next_integer
3919 *
3920 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3921 *
3922 * 1.pred #=> 0
3923 * -1.pred #=> -2
3924 *
3925 * Related: Integer#succ (successor value).
3926 *
3927 */
3928
3929static VALUE
3930rb_int_pred(VALUE num)
3931{
3932 if (FIXNUM_P(num)) {
3933 long i = FIX2LONG(num) - 1;
3934 return LONG2NUM(i);
3935 }
3936 if (RB_BIGNUM_TYPE_P(num)) {
3937 return rb_big_minus(num, INT2FIX(1));
3938 }
3939 return num_funcall1(num, '-', INT2FIX(1));
3940}
3941
3942#define int_pred rb_int_pred
3943
3944VALUE
3945rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3946{
3947 int n;
3948 VALUE str;
3949 switch (n = rb_enc_codelen(code, enc)) {
3950 case ONIGERR_INVALID_CODE_POINT_VALUE:
3951 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3952 break;
3953 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3954 case 0:
3955 rb_raise(rb_eRangeError, "%u out of char range", code);
3956 break;
3957 }
3958 str = rb_enc_str_new(0, n, enc);
3959 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3960 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3961 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3962 }
3963 return str;
3964}
3965
3966/* call-seq:
3967 * chr -> string
3968 * chr(encoding) -> string
3969 *
3970 * Returns a 1-character string containing the character
3971 * represented by the value of +self+, according to the given +encoding+.
3972 *
3973 * 65.chr # => "A"
3974 * 0.chr # => "\x00"
3975 * 255.chr # => "\xFF"
3976 * string = 255.chr(Encoding::UTF_8)
3977 * string.encoding # => Encoding::UTF_8
3978 *
3979 * Raises an exception if +self+ is negative.
3980 *
3981 * Related: Integer#ord.
3982 *
3983 */
3984
3985static VALUE
3986int_chr(int argc, VALUE *argv, VALUE num)
3987{
3988 char c;
3989 unsigned int i;
3990 rb_encoding *enc;
3991
3992 if (rb_num_to_uint(num, &i) == 0) {
3993 }
3994 else if (FIXNUM_P(num)) {
3995 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3996 }
3997 else {
3998 rb_raise(rb_eRangeError, "bignum out of char range");
3999 }
4000
4001 switch (argc) {
4002 case 0:
4003 if (0xff < i) {
4004 enc = rb_default_internal_encoding();
4005 if (!enc) {
4006 rb_raise(rb_eRangeError, "%u out of char range", i);
4007 }
4008 goto decode;
4009 }
4010 c = (char)i;
4011 if (i < 0x80) {
4012 return rb_usascii_str_new(&c, 1);
4013 }
4014 else {
4015 return rb_str_new(&c, 1);
4016 }
4017 case 1:
4018 break;
4019 default:
4020 rb_error_arity(argc, 0, 1);
4021 }
4022 enc = rb_to_encoding(argv[0]);
4023 if (!enc) enc = rb_ascii8bit_encoding();
4024 decode:
4025 return rb_enc_uint_chr(i, enc);
4026}
4027
4028/*
4029 * Fixnum
4030 */
4031
4032static VALUE
4033fix_uminus(VALUE num)
4034{
4035 return LONG2NUM(-FIX2LONG(num));
4036}
4037
4038VALUE
4039rb_int_uminus(VALUE num)
4040{
4041 if (FIXNUM_P(num)) {
4042 return fix_uminus(num);
4043 }
4044 else {
4045 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
4046 return rb_big_uminus(num);
4047 }
4048}
4049
4050/* ruby_decimal_digit_pairs is defined in bignum.c and declared in
4051 * internal/bignum.h. See there for the rationale of the 2-digit
4052 * lookup-table itoa optimisation; both rb_fix2str here and big2str_2bdigits
4053 * in bignum.c consume it. */
4054
4055VALUE
4056rb_fix2str(VALUE x, int base)
4057{
4058 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
4059 long val = FIX2LONG(x);
4060 unsigned long u;
4061 int neg = 0;
4062
4063 if (base < 2 || 36 < base) {
4064 rb_raise(rb_eArgError, "invalid radix %d", base);
4065 }
4066#if SIZEOF_LONG < SIZEOF_VOIDP
4067# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4068 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4069 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4070 rb_bug("Unnormalized Fixnum value %p", (void *)x);
4071 }
4072# else
4073 /* should do something like above code, but currently ruby does not know */
4074 /* such platforms */
4075# endif
4076#endif
4077 if (val == 0) {
4078 return rb_usascii_str_new2("0");
4079 }
4080 if (val < 0) {
4081 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
4082 neg = 1;
4083 }
4084 else {
4085 u = val;
4086 }
4087 if (base == 10) {
4088 /* Emit two digits per iteration from a precomputed table. The
4089 * compiler lowers `u % 100` and `u / 100` to a single multiply +
4090 * shift, so each iteration costs roughly one multiply, one shift,
4091 * and two stores. About 2x fewer iterations than the classic
4092 * per-digit loop for multi-digit inputs. */
4093 while (u >= 100) {
4094 unsigned long idx = (u % 100) * 2;
4095 u /= 100;
4096 b -= 2;
4097 b[0] = ruby_decimal_digit_pairs[idx];
4098 b[1] = ruby_decimal_digit_pairs[idx + 1];
4099 }
4100 if (u >= 10) {
4101 unsigned long idx = u * 2;
4102 b -= 2;
4103 b[0] = ruby_decimal_digit_pairs[idx];
4104 b[1] = ruby_decimal_digit_pairs[idx + 1];
4105 }
4106 else {
4107 *--b = (char)('0' + u);
4108 }
4109 }
4110 else {
4111 do {
4112 *--b = ruby_digitmap[(int)(u % base)];
4113 } while (u /= base);
4114 }
4115 if (neg) {
4116 *--b = '-';
4117 }
4118
4119 return rb_usascii_str_new(b, e - b);
4120}
4121
4122static VALUE rb_fix_to_s_static[10];
4123
4124VALUE
4125rb_fix_to_s(VALUE x)
4126{
4127 long i = FIX2LONG(x);
4128 if (i >= 0 && i < 10) {
4129 return rb_fix_to_s_static[i];
4130 }
4131 return rb_fix2str(x, 10);
4132}
4133
4134/*
4135 * call-seq:
4136 * to_s(base = 10) -> string
4137 *
4138 * Returns a string containing the place-value representation of +self+
4139 * in radix +base+ (in 2..36).
4140 *
4141 * 12345.to_s # => "12345"
4142 * 12345.to_s(2) # => "11000000111001"
4143 * 12345.to_s(8) # => "30071"
4144 * 12345.to_s(10) # => "12345"
4145 * 12345.to_s(16) # => "3039"
4146 * 12345.to_s(36) # => "9ix"
4147 * 78546939656932.to_s(36) # => "rubyrules"
4148 *
4149 * Raises an exception if +base+ is out of range.
4150 */
4151
4152VALUE
4153rb_int_to_s(int argc, VALUE *argv, VALUE x)
4154{
4155 int base;
4156
4157 if (rb_check_arity(argc, 0, 1))
4158 base = NUM2INT(argv[0]);
4159 else
4160 base = 10;
4161 return rb_int2str(x, base);
4162}
4163
4164VALUE
4165rb_int2str(VALUE x, int base)
4166{
4167 if (FIXNUM_P(x)) {
4168 return rb_fix2str(x, base);
4169 }
4170 else if (RB_BIGNUM_TYPE_P(x)) {
4171 return rb_big2str(x, base);
4172 }
4173
4174 return rb_any_to_s(x);
4175}
4176
4177static VALUE
4178fix_plus(VALUE x, VALUE y)
4179{
4180 if (FIXNUM_P(y)) {
4181 return rb_fix_plus_fix(x, y);
4182 }
4183 else if (RB_BIGNUM_TYPE_P(y)) {
4184 return rb_big_plus(y, x);
4185 }
4186 else if (RB_FLOAT_TYPE_P(y)) {
4187 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4188 }
4189 else if (RB_TYPE_P(y, T_COMPLEX)) {
4190 return rb_complex_plus(y, x);
4191 }
4192 else {
4193 return rb_num_coerce_bin(x, y, '+');
4194 }
4195}
4196
4197VALUE
4198rb_fix_plus(VALUE x, VALUE y)
4199{
4200 return fix_plus(x, y);
4201}
4202
4203/*
4204 * call-seq:
4205 * self + other -> numeric
4206 *
4207 * Returns the sum of +self+ and +other+:
4208 *
4209 * 1 + 1 # => 2
4210 * 1 + -1 # => 0
4211 * 1 + 0 # => 1
4212 * 1 + -2 # => -1
4213 * 1 + Complex(1, 0) # => (2+0i)
4214 * 1 + Rational(1, 1) # => (2/1)
4215 *
4216 * For a computation involving Floats, the result may be inexact (see Float#+):
4217 *
4218 * 1 + 3.14 # => 4.140000000000001
4219 */
4220
4221VALUE
4222rb_int_plus(VALUE x, VALUE y)
4223{
4224 if (FIXNUM_P(x)) {
4225 return fix_plus(x, y);
4226 }
4227 else if (RB_BIGNUM_TYPE_P(x)) {
4228 return rb_big_plus(x, y);
4229 }
4230 return rb_num_coerce_bin(x, y, '+');
4231}
4232
4233static VALUE
4234fix_minus(VALUE x, VALUE y)
4235{
4236 if (FIXNUM_P(y)) {
4237 return rb_fix_minus_fix(x, y);
4238 }
4239 else if (RB_BIGNUM_TYPE_P(y)) {
4240 x = rb_int2big(FIX2LONG(x));
4241 return rb_big_minus(x, y);
4242 }
4243 else if (RB_FLOAT_TYPE_P(y)) {
4244 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4245 }
4246 else {
4247 return rb_num_coerce_bin(x, y, '-');
4248 }
4249}
4250
4251/*
4252 * call-seq:
4253 * self - other -> numeric
4254 *
4255 * Returns the difference of +self+ and +other+:
4256 *
4257 * 4 - 2 # => 2
4258 * -4 - 2 # => -6
4259 * -4 - -2 # => -2
4260 * 4 - 2.0 # => 2.0
4261 * 4 - Rational(2, 1) # => (2/1)
4262 * 4 - Complex(2, 0) # => (2+0i)
4263 *
4264 */
4265
4266VALUE
4267rb_int_minus(VALUE x, VALUE y)
4268{
4269 if (FIXNUM_P(x)) {
4270 return fix_minus(x, y);
4271 }
4272 else if (RB_BIGNUM_TYPE_P(x)) {
4273 return rb_big_minus(x, y);
4274 }
4275 return rb_num_coerce_bin(x, y, '-');
4276}
4277
4278
4279#define SQRT_LONG_MAX HALF_LONG_MSB
4280/*tests if N*N would overflow*/
4281#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4282
4283static VALUE
4284fix_mul(VALUE x, VALUE y)
4285{
4286 if (FIXNUM_P(y)) {
4287 return rb_fix_mul_fix(x, y);
4288 }
4289 else if (RB_BIGNUM_TYPE_P(y)) {
4290 switch (x) {
4291 case INT2FIX(0): return x;
4292 case INT2FIX(1): return y;
4293 }
4294 return rb_big_mul(y, x);
4295 }
4296 else if (RB_FLOAT_TYPE_P(y)) {
4297 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4298 }
4299 else if (RB_TYPE_P(y, T_COMPLEX)) {
4300 return rb_complex_mul(y, x);
4301 }
4302 else {
4303 return rb_num_coerce_bin(x, y, '*');
4304 }
4305}
4306
4307/*
4308 * call-seq:
4309 * self * other -> numeric
4310 *
4311 * Returns the numeric product of +self+ and +other+:
4312 *
4313 * 4 * 2 # => 8
4314 * -4 * 2 # => -8
4315 * 4 * -2 # => -8
4316 * 4 * 2.0 # => 8.0
4317 * 4 * Rational(1, 3) # => (4/3)
4318 * 4 * Complex(2, 0) # => (8+0i)
4319 *
4320 */
4321
4322VALUE
4323rb_int_mul(VALUE x, VALUE y)
4324{
4325 if (FIXNUM_P(x)) {
4326 return fix_mul(x, y);
4327 }
4328 else if (RB_BIGNUM_TYPE_P(x)) {
4329 return rb_big_mul(x, y);
4330 }
4331 return rb_num_coerce_bin(x, y, '*');
4332}
4333
4334static bool
4335accurate_in_double(long i)
4336{
4337#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4338 return ((i < 0 ? -i : i) < (1L << DBL_MANT_DIG));
4339#else
4340 return true;
4341#endif
4342}
4343
4344static double
4345fix_fdiv_double(VALUE x, VALUE y)
4346{
4347 if (FIXNUM_P(y)) {
4348 long iy = FIX2LONG(y);
4349 if (!accurate_in_double(iy)) {
4350 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4351 }
4352 return double_div_double(FIX2LONG(x), iy);
4353 }
4354 else if (RB_BIGNUM_TYPE_P(y)) {
4355 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4356 }
4357 else if (RB_FLOAT_TYPE_P(y)) {
4358 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4359 }
4360 else {
4361 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4362 }
4363}
4364
4365static bool
4366int_accurate_in_double(VALUE n)
4367{
4368 if (FIXNUM_P(n)) {
4369 return accurate_in_double(FIX2LONG(n));
4370 }
4372#if SIZEOF_LONG * CHAR_BIT <= DBL_MANT_DIG
4373 int nlz;
4374 size_t size = rb_absint_size(n, &nlz);
4375 const size_t mant_size = roomof(DBL_MANT_DIG, CHAR_BIT);
4376 if (size < mant_size) return true;
4377 if (size > mant_size) return false;
4378 if ((size_t)nlz >= (CHAR_BIT * mant_size - DBL_MANT_DIG)) return true;
4379#endif
4380 return false;
4381}
4382
4383double
4384rb_int_fdiv_double(VALUE x, VALUE y)
4385{
4386 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y) &&
4387 !(int_accurate_in_double(x) && int_accurate_in_double(y))) {
4388 VALUE gcd = rb_gcd(x, y);
4389 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4390 x = rb_int_idiv(x, gcd);
4391 y = rb_int_idiv(y, gcd);
4392 }
4393 }
4394 if (FIXNUM_P(x)) {
4395 return fix_fdiv_double(x, y);
4396 }
4397 else if (RB_BIGNUM_TYPE_P(x)) {
4398 return rb_big_fdiv_double(x, y);
4399 }
4400 else {
4401 return nan("");
4402 }
4403}
4404
4405/*
4406 * call-seq:
4407 * fdiv(numeric) -> float
4408 *
4409 * Returns the Float result of dividing +self+ by +numeric+:
4410 *
4411 * 4.fdiv(2) # => 2.0
4412 * 4.fdiv(-2) # => -2.0
4413 * -4.fdiv(2) # => -2.0
4414 * 4.fdiv(2.0) # => 2.0
4415 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4416 *
4417 * Raises an exception if +numeric+ cannot be converted to a Float.
4418 *
4419 */
4420
4421VALUE
4422rb_int_fdiv(VALUE x, VALUE y)
4423{
4424 if (RB_INTEGER_TYPE_P(x)) {
4425 return DBL2NUM(rb_int_fdiv_double(x, y));
4426 }
4427 return Qnil;
4428}
4429
4430static VALUE
4431fix_divide(VALUE x, VALUE y, ID op)
4432{
4433 if (FIXNUM_P(y)) {
4434 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4435 return rb_fix_div_fix(x, y);
4436 }
4437 else if (RB_BIGNUM_TYPE_P(y)) {
4438 x = rb_int2big(FIX2LONG(x));
4439 return rb_big_div(x, y);
4440 }
4441 else if (RB_FLOAT_TYPE_P(y)) {
4442 if (op == '/') {
4443 double d = FIX2LONG(x);
4444 return rb_flo_div_flo(DBL2NUM(d), y);
4445 }
4446 else {
4447 VALUE v;
4448 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4449 v = fix_divide(x, y, '/');
4450 return flo_floor(0, 0, v);
4451 }
4452 }
4453 else {
4454 if (RB_TYPE_P(y, T_RATIONAL) &&
4455 op == '/' && FIX2LONG(x) == 1)
4456 return rb_rational_reciprocal(y);
4457 return rb_num_coerce_bin(x, y, op);
4458 }
4459}
4460
4461static VALUE
4462fix_div(VALUE x, VALUE y)
4463{
4464 return fix_divide(x, y, '/');
4465}
4466
4467/*
4468 * call-seq:
4469 * self / other -> numeric
4470 *
4471 * Returns the quotient of +self+ and +other+.
4472 *
4473 * For integer +other+, truncates the result to an integer:
4474 *
4475 * 4 / 3 # => 1
4476 * 4 / -3 # => -2
4477 * -4 / 3 # => -2
4478 * -4 / -3 # => 1
4479 *
4480 * For non-integer +other+, returns a non-integer result:
4481 *
4482 * 4 / 3.0 # => 1.3333333333333333
4483 * 4 / Rational(3, 1) # => (4/3)
4484 * 4 / Complex(3, 0) # => ((4/3)+0i)
4485 *
4486 */
4487
4488VALUE
4489rb_int_div(VALUE x, VALUE y)
4490{
4491 if (FIXNUM_P(x)) {
4492 return fix_div(x, y);
4493 }
4494 else if (RB_BIGNUM_TYPE_P(x)) {
4495 return rb_big_div(x, y);
4496 }
4497 return Qnil;
4498}
4499
4500static VALUE
4501fix_idiv(VALUE x, VALUE y)
4502{
4503 return fix_divide(x, y, id_div);
4504}
4505
4506/*
4507 * call-seq:
4508 * div(numeric) -> integer
4509 *
4510 * Performs integer division; returns the integer result of dividing +self+
4511 * by +numeric+:
4512 *
4513 * 4.div(3) # => 1
4514 * 4.div(-3) # => -2
4515 * -4.div(3) # => -2
4516 * -4.div(-3) # => 1
4517 * 4.div(3.0) # => 1
4518 * 4.div(Rational(3, 1)) # => 1
4519 *
4520 * Raises an exception if +numeric+ does not have method +div+.
4521 *
4522 */
4523
4524VALUE
4525rb_int_idiv(VALUE x, VALUE y)
4526{
4527 if (FIXNUM_P(x)) {
4528 return fix_idiv(x, y);
4529 }
4530 else if (RB_BIGNUM_TYPE_P(x)) {
4531 return rb_big_idiv(x, y);
4532 }
4533 return num_div(x, y);
4534}
4535
4536static VALUE
4537fix_mod(VALUE x, VALUE y)
4538{
4539 if (FIXNUM_P(y)) {
4540 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4541 return rb_fix_mod_fix(x, y);
4542 }
4543 else if (RB_BIGNUM_TYPE_P(y)) {
4544 x = rb_int2big(FIX2LONG(x));
4545 return rb_big_modulo(x, y);
4546 }
4547 else if (RB_FLOAT_TYPE_P(y)) {
4548 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4549 }
4550 else {
4551 return rb_num_coerce_bin(x, y, '%');
4552 }
4553}
4554
4555/*
4556 * call-seq:
4557 * self % other -> real_numeric
4558 *
4559 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
4560 *
4561 * For integer +n+ and real number +r+, these expressions are equivalent:
4562 *
4563 * n % r
4564 * n-r*(n/r).floor
4565 * n.divmod(r)[1]
4566 *
4567 * See Numeric#divmod.
4568 *
4569 * Examples:
4570 *
4571 * 10 % 2 # => 0
4572 * 10 % 3 # => 1
4573 * 10 % 4 # => 2
4574 *
4575 * 10 % -2 # => 0
4576 * 10 % -3 # => -2
4577 * 10 % -4 # => -2
4578 *
4579 * 10 % 3.0 # => 1.0
4580 * 10 % Rational(3, 1) # => (1/1)
4581 *
4582 */
4583VALUE
4584rb_int_modulo(VALUE x, VALUE y)
4585{
4586 if (FIXNUM_P(x)) {
4587 return fix_mod(x, y);
4588 }
4589 else if (RB_BIGNUM_TYPE_P(x)) {
4590 return rb_big_modulo(x, y);
4591 }
4592 return num_modulo(x, y);
4593}
4594
4595/*
4596 * call-seq:
4597 * remainder(other) -> real_number
4598 *
4599 * Returns the remainder after dividing +self+ by +other+.
4600 *
4601 * Examples:
4602 *
4603 * 11.remainder(4) # => 3
4604 * 11.remainder(-4) # => 3
4605 * -11.remainder(4) # => -3
4606 * -11.remainder(-4) # => -3
4607 *
4608 * 12.remainder(4) # => 0
4609 * 12.remainder(-4) # => 0
4610 * -12.remainder(4) # => 0
4611 * -12.remainder(-4) # => 0
4612 *
4613 * 13.remainder(4.0) # => 1.0
4614 * 13.remainder(Rational(4, 1)) # => (1/1)
4615 *
4616 */
4617
4618static VALUE
4619int_remainder(VALUE x, VALUE y)
4620{
4621 if (FIXNUM_P(x)) {
4622 if (FIXNUM_P(y)) {
4623 VALUE z = fix_mod(x, y);
4625 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4626 z = fix_minus(z, y);
4627 return z;
4628 }
4629 else if (!RB_BIGNUM_TYPE_P(y)) {
4630 return num_remainder(x, y);
4631 }
4632 x = rb_int2big(FIX2LONG(x));
4633 }
4634 else if (!RB_BIGNUM_TYPE_P(x)) {
4635 return Qnil;
4636 }
4637 return rb_big_remainder(x, y);
4638}
4639
4640static VALUE
4641fix_divmod(VALUE x, VALUE y)
4642{
4643 if (FIXNUM_P(y)) {
4644 VALUE div, mod;
4645 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4646 rb_fix_divmod_fix(x, y, &div, &mod);
4647 return rb_assoc_new(div, mod);
4648 }
4649 else if (RB_BIGNUM_TYPE_P(y)) {
4650 x = rb_int2big(FIX2LONG(x));
4651 return rb_big_divmod(x, y);
4652 }
4653 else if (RB_FLOAT_TYPE_P(y)) {
4654 {
4655 double div, mod;
4656 volatile VALUE a, b;
4657
4658 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4659 a = dbl2ival(div);
4660 b = DBL2NUM(mod);
4661 return rb_assoc_new(a, b);
4662 }
4663 }
4664 else {
4665 return rb_num_coerce_bin(x, y, id_divmod);
4666 }
4667}
4668
4669/*
4670 * call-seq:
4671 * divmod(other) -> array
4672 *
4673 * Returns a 2-element array <tt>[q, r]</tt>, where
4674 *
4675 * q = (self/other).floor # Quotient
4676 * r = self % other # Remainder
4677 *
4678 * Examples:
4679 *
4680 * 11.divmod(4) # => [2, 3]
4681 * 11.divmod(-4) # => [-3, -1]
4682 * -11.divmod(4) # => [-3, 1]
4683 * -11.divmod(-4) # => [2, -3]
4684 *
4685 * 12.divmod(4) # => [3, 0]
4686 * 12.divmod(-4) # => [-3, 0]
4687 * -12.divmod(4) # => [-3, 0]
4688 * -12.divmod(-4) # => [3, 0]
4689 *
4690 * 13.divmod(4.0) # => [3, 1.0]
4691 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4692 *
4693 */
4694VALUE
4695rb_int_divmod(VALUE x, VALUE y)
4696{
4697 if (FIXNUM_P(x)) {
4698 return fix_divmod(x, y);
4699 }
4700 else if (RB_BIGNUM_TYPE_P(x)) {
4701 return rb_big_divmod(x, y);
4702 }
4703 return Qnil;
4704}
4705
4706/*
4707 * call-seq:
4708 * self ** exponent -> numeric
4709 *
4710 * Returns +self+ raised to the power +exponent+:
4711 *
4712 * 2 ** 3 # => 8
4713 * 2 ** -3 # => (1/8)
4714 * -2 ** 3 # => -8
4715 * -2 ** -3 # => (-1/8)
4716 * 2 ** 3.3 # => 9.849155306759329
4717 * 2 ** Rational(3, 1) # => (8/1)
4718 * 2 ** Complex(3, 0) # => (8+0i)
4719 *
4720 */
4721
4722static VALUE
4723int_pow(long x, unsigned long y)
4724{
4725 int neg = x < 0;
4726 long z = 1;
4727
4728 if (y == 0) return INT2FIX(1);
4729 if (y == 1) return LONG2NUM(x);
4730 if (neg) x = -x;
4731 if (y & 1)
4732 z = x;
4733 else
4734 neg = 0;
4735 y &= ~1;
4736 do {
4737 while (y % 2 == 0) {
4738 if (!FIT_SQRT_LONG(x)) {
4739 goto bignum;
4740 }
4741 x = x * x;
4742 y >>= 1;
4743 }
4744 {
4745 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4746 goto bignum;
4747 }
4748 z = x * z;
4749 }
4750 } while (--y);
4751 if (neg) z = -z;
4752 return LONG2NUM(z);
4753
4754 VALUE v;
4755 bignum:
4756 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4757 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4758 return v;
4759 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4760 return v;
4761}
4762
4763VALUE
4764rb_int_positive_pow(long x, unsigned long y)
4765{
4766 return int_pow(x, y);
4767}
4768
4769static VALUE
4770fix_pow_inverted(VALUE x, VALUE minusb)
4771{
4772 if (x == INT2FIX(0)) {
4775 }
4776 else {
4777 VALUE y = rb_int_pow(x, minusb);
4778
4779 if (RB_FLOAT_TYPE_P(y)) {
4780 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4781 return DBL2NUM(1.0 / d);
4782 }
4783 else {
4784 return rb_rational_raw(INT2FIX(1), y);
4785 }
4786 }
4787}
4788
4789static VALUE
4790fix_pow(VALUE x, VALUE y)
4791{
4792 long a = FIX2LONG(x);
4793
4794 if (FIXNUM_P(y)) {
4795 long b = FIX2LONG(y);
4796
4797 if (a == 1) return INT2FIX(1);
4798 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4799 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4800 if (b == 0) return INT2FIX(1);
4801 if (b == 1) return x;
4802 if (a == 0) return INT2FIX(0);
4803 return int_pow(a, b);
4804 }
4805 else if (RB_BIGNUM_TYPE_P(y)) {
4806 if (a == 1) return INT2FIX(1);
4807 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4808 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4809 if (a == 0) return INT2FIX(0);
4810 x = rb_int2big(FIX2LONG(x));
4811 return rb_big_pow(x, y);
4812 }
4813 else if (RB_FLOAT_TYPE_P(y)) {
4814 double dy = RFLOAT_VALUE(y);
4815 if (dy == 0.0) return DBL2NUM(1.0);
4816 if (a == 0) {
4817 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4818 }
4819 if (a == 1) return DBL2NUM(1.0);
4820 if (a < 0 && dy != round(dy))
4821 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4822 return DBL2NUM(pow((double)a, dy));
4823 }
4824 else {
4825 return rb_num_coerce_bin(x, y, idPow);
4826 }
4827}
4828
4829/*
4830 * call-seq:
4831 * self ** exponent -> numeric
4832 *
4833 * Returns +self+ raised to the power +exponent+:
4834 *
4835 * # Result for non-negative Integer exponent is Integer.
4836 * 2 ** 0 # => 1
4837 * 2 ** 1 # => 2
4838 * 2 ** 2 # => 4
4839 * 2 ** 3 # => 8
4840 * -2 ** 3 # => -8
4841 * # Result for negative Integer exponent is Rational, not Float.
4842 * 2 ** -3 # => (1/8)
4843 * -2 ** -3 # => (-1/8)
4844 *
4845 * # Result for Float exponent is Float.
4846 * 2 ** 0.0 # => 1.0
4847 * 2 ** 1.0 # => 2.0
4848 * 2 ** 2.0 # => 4.0
4849 * 2 ** 3.0 # => 8.0
4850 * -2 ** 3.0 # => -8.0
4851 * 2 ** -3.0 # => 0.125
4852 * -2 ** -3.0 # => -0.125
4853 *
4854 * # Result for non-negative Complex exponent is Complex with Integer parts.
4855 * 2 ** Complex(0, 0) # => (1+0i)
4856 * 2 ** Complex(1, 0) # => (2+0i)
4857 * 2 ** Complex(2, 0) # => (4+0i)
4858 * 2 ** Complex(3, 0) # => (8+0i)
4859 * -2 ** Complex(3, 0) # => (-8+0i)
4860 * # Result for negative Complex exponent is Complex with Rational parts.
4861 * 2 ** Complex(-3, 0) # => ((1/8)+(0/1)*i)
4862 * -2 ** Complex(-3, 0) # => ((-1/8)+(0/1)*i)
4863 *
4864 * # Result for Rational exponent is Rational.
4865 * 2 ** Rational(0, 1) # => (1/1)
4866 * 2 ** Rational(1, 1) # => (2/1)
4867 * 2 ** Rational(2, 1) # => (4/1)
4868 * 2 ** Rational(3, 1) # => (8/1)
4869 * -2 ** Rational(3, 1) # => (-8/1)
4870 * 2 ** Rational(-3, 1) # => (1/8)
4871 * -2 ** Rational(-3, 1) # => (-1/8)
4872 *
4873 */
4874VALUE
4875rb_int_pow(VALUE x, VALUE y)
4876{
4877 if (FIXNUM_P(x)) {
4878 return fix_pow(x, y);
4879 }
4880 else if (RB_BIGNUM_TYPE_P(x)) {
4881 return rb_big_pow(x, y);
4882 }
4883 return Qnil;
4884}
4885
4886VALUE
4887rb_num_pow(VALUE x, VALUE y)
4888{
4889 VALUE z = rb_int_pow(x, y);
4890 if (!NIL_P(z)) return z;
4891 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4892 if (SPECIAL_CONST_P(x)) return Qnil;
4893 switch (BUILTIN_TYPE(x)) {
4894 case T_COMPLEX:
4895 return rb_complex_pow(x, y);
4896 case T_RATIONAL:
4897 return rb_rational_pow(x, y);
4898 default:
4899 break;
4900 }
4901 return Qnil;
4902}
4903
4904static VALUE
4905fix_equal(VALUE x, VALUE y)
4906{
4907 if (x == y) return Qtrue;
4908 if (FIXNUM_P(y)) return Qfalse;
4909 else if (RB_BIGNUM_TYPE_P(y)) {
4910 return rb_big_eq(y, x);
4911 }
4912 else if (RB_FLOAT_TYPE_P(y)) {
4913 return rb_integer_float_eq(x, y);
4914 }
4915 else {
4916 return num_equal(x, y);
4917 }
4918}
4919
4920/*
4921 * call-seq:
4922 * self == other -> true or false
4923 *
4924 * Returns whether +self+ is numerically equal to +other+:
4925 *
4926 * 1 == 2 #=> false
4927 * 1 == 1.0 #=> true
4928 *
4929 * Related: Integer#eql? (requires +other+ to be an \Integer).
4930 */
4931
4932VALUE
4933rb_int_equal(VALUE x, VALUE y)
4934{
4935 if (FIXNUM_P(x)) {
4936 return fix_equal(x, y);
4937 }
4938 else if (RB_BIGNUM_TYPE_P(x)) {
4939 return rb_big_eq(x, y);
4940 }
4941 return Qnil;
4942}
4943
4944static VALUE
4945fix_cmp(VALUE x, VALUE y)
4946{
4947 if (x == y) return INT2FIX(0);
4948 if (FIXNUM_P(y)) {
4949 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4950 return INT2FIX(-1);
4951 }
4952 else if (RB_BIGNUM_TYPE_P(y)) {
4953 VALUE cmp = rb_big_cmp(y, x);
4954 switch (cmp) {
4955 case INT2FIX(+1): return INT2FIX(-1);
4956 case INT2FIX(-1): return INT2FIX(+1);
4957 }
4958 return cmp;
4959 }
4960 else if (RB_FLOAT_TYPE_P(y)) {
4961 return rb_integer_float_cmp(x, y);
4962 }
4963 else {
4964 return rb_num_coerce_cmp(x, y, id_cmp);
4965 }
4966}
4967
4968/*
4969 * call-seq:
4970 * self <=> other -> -1, 0, 1, or nil
4971 *
4972 * Compares +self+ and +other+.
4973 *
4974 * Returns:
4975 *
4976 * - +-1+, if +self+ is less than +other+.
4977 * - +0+, if +self+ is equal to +other+.
4978 * - +1+, if +self+ is greater then +other+.
4979 * - +nil+, if +self+ and +other+ are incomparable.
4980 *
4981 * Examples:
4982 *
4983 * 1 <=> 2 # => -1
4984 * 1 <=> 1 # => 0
4985 * 1 <=> 1.0 # => 0
4986 * 1 <=> Rational(1, 1) # => 0
4987 * 1 <=> Complex(1, 0) # => 0
4988 * 1 <=> 0 # => 1
4989 * 1 <=> 'foo' # => nil
4990 *
4991 * \Class \Integer includes module Comparable,
4992 * each of whose methods uses Integer#<=> for comparison.
4993 */
4994
4995VALUE
4996rb_int_cmp(VALUE x, VALUE y)
4997{
4998 if (FIXNUM_P(x)) {
4999 return fix_cmp(x, y);
5000 }
5001 else if (RB_BIGNUM_TYPE_P(x)) {
5002 return rb_big_cmp(x, y);
5003 }
5004 else {
5005 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
5006 }
5007}
5008
5009static VALUE
5010fix_gt(VALUE x, VALUE y)
5011{
5012 if (FIXNUM_P(y)) {
5013 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
5014 }
5015 else if (RB_BIGNUM_TYPE_P(y)) {
5016 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
5017 }
5018 else if (RB_FLOAT_TYPE_P(y)) {
5019 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
5020 }
5021 else {
5022 return rb_num_coerce_relop(x, y, '>');
5023 }
5024}
5025
5026/*
5027 * call-seq:
5028 * self > other -> true or false
5029 *
5030 * Returns whether the value of +self+ is greater than the value of +other+;
5031 * +other+ must be numeric, but may not be Complex:
5032 *
5033 * 1 > 0 # => true
5034 * 1 > 1 # => false
5035 * 1 > 2 # => false
5036 * 1 > 0.5 # => true
5037 * 1 > Rational(1, 2) # => true
5038 *
5039 * Raises an exception if the comparison cannot be made.
5040 *
5041 */
5042
5043VALUE
5044rb_int_gt(VALUE x, VALUE y)
5045{
5046 if (FIXNUM_P(x)) {
5047 return fix_gt(x, y);
5048 }
5049 else if (RB_BIGNUM_TYPE_P(x)) {
5050 return rb_big_gt(x, y);
5051 }
5052 return Qnil;
5053}
5054
5055static VALUE
5056fix_ge(VALUE x, VALUE y)
5057{
5058 if (FIXNUM_P(y)) {
5059 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
5060 }
5061 else if (RB_BIGNUM_TYPE_P(y)) {
5062 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
5063 }
5064 else if (RB_FLOAT_TYPE_P(y)) {
5065 VALUE rel = rb_integer_float_cmp(x, y);
5066 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
5067 }
5068 else {
5069 return rb_num_coerce_relop(x, y, idGE);
5070 }
5071}
5072
5073/*
5074 * call-seq:
5075 * self >= other -> true or false
5076 *
5077 * Returns whether the value of +self+ is greater than or equal to the value of +other+;
5078 * +other+ must be numeric, but may not be Complex:
5079 *
5080 * 1 >= 0 # => true
5081 * 1 >= 1 # => true
5082 * 1 >= 2 # => false
5083 * 1 >= 0.5 # => true
5084 * 1 >= Rational(1, 2) # => true
5085 *
5086 * Raises an exception if the comparison cannot be made.
5087 *
5088 */
5089
5090VALUE
5091rb_int_ge(VALUE x, VALUE y)
5092{
5093 if (FIXNUM_P(x)) {
5094 return fix_ge(x, y);
5095 }
5096 else if (RB_BIGNUM_TYPE_P(x)) {
5097 return rb_big_ge(x, y);
5098 }
5099 return Qnil;
5100}
5101
5102static VALUE
5103fix_lt(VALUE x, VALUE y)
5104{
5105 if (FIXNUM_P(y)) {
5106 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
5107 }
5108 else if (RB_BIGNUM_TYPE_P(y)) {
5109 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
5110 }
5111 else if (RB_FLOAT_TYPE_P(y)) {
5112 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
5113 }
5114 else {
5115 return rb_num_coerce_relop(x, y, '<');
5116 }
5117}
5118
5119/*
5120 * call-seq:
5121 * self < other -> true or false
5122 *
5123 * Returns whether the value of +self+ is less than the value of +other+;
5124 * +other+ must be numeric, but may not be Complex:
5125 *
5126 * 1 < 0 # => false
5127 * 1 < 1 # => false
5128 * 1 < 2 # => true
5129 * 1 < 0.5 # => false
5130 * 1 < Rational(1, 2) # => false
5131 *
5132 */
5133
5134static VALUE
5135int_lt(VALUE x, VALUE y)
5136{
5137 if (FIXNUM_P(x)) {
5138 return fix_lt(x, y);
5139 }
5140 else if (RB_BIGNUM_TYPE_P(x)) {
5141 return rb_big_lt(x, y);
5142 }
5143 return Qnil;
5144}
5145
5146static VALUE
5147fix_le(VALUE x, VALUE y)
5148{
5149 if (FIXNUM_P(y)) {
5150 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
5151 }
5152 else if (RB_BIGNUM_TYPE_P(y)) {
5153 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
5154 }
5155 else if (RB_FLOAT_TYPE_P(y)) {
5156 VALUE rel = rb_integer_float_cmp(x, y);
5157 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
5158 }
5159 else {
5160 return rb_num_coerce_relop(x, y, idLE);
5161 }
5162}
5163
5164/*
5165 * call-seq:
5166 * self <= other -> true or false
5167 *
5168 * Returns whether the value of +self+ is less than or equal to the value of +other+;
5169 * +other+ must be numeric, but may not be Complex:
5170 *
5171 * 1 <= 0 # => false
5172 * 1 <= 1 # => true
5173 * 1 <= 2 # => true
5174 * 1 <= 0.5 # => false
5175 * 1 <= Rational(1, 2) # => false
5176 *
5177 * Raises an exception if the comparison cannot be made.
5178 *
5179 */
5180
5181static VALUE
5182int_le(VALUE x, VALUE y)
5183{
5184 if (FIXNUM_P(x)) {
5185 return fix_le(x, y);
5186 }
5187 else if (RB_BIGNUM_TYPE_P(x)) {
5188 return rb_big_le(x, y);
5189 }
5190 return Qnil;
5191}
5192
5193static VALUE
5194fix_comp(VALUE num)
5195{
5196 return ~num | FIXNUM_FLAG;
5197}
5198
5199VALUE
5200rb_int_comp(VALUE num)
5201{
5202 if (FIXNUM_P(num)) {
5203 return fix_comp(num);
5204 }
5205 else if (RB_BIGNUM_TYPE_P(num)) {
5206 return rb_big_comp(num);
5207 }
5208 return Qnil;
5209}
5210
5211static VALUE
5212num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
5213{
5214 ID func = (ID)((VALUE *)arg)[0];
5215 VALUE x = ((VALUE *)arg)[1];
5216 if (recursive) {
5217 num_funcall_op_1_recursion(x, func, y);
5218 }
5219 return rb_check_funcall(x, func, 1, &y);
5220}
5221
5222VALUE
5224{
5225 VALUE ret, args[3];
5226
5227 args[0] = (VALUE)func;
5228 args[1] = x;
5229 args[2] = y;
5230 do_coerce(&args[1], &args[2], TRUE);
5231 ret = rb_exec_recursive_paired(num_funcall_bit_1,
5232 args[2], args[1], (VALUE)args);
5233 if (UNDEF_P(ret)) {
5234 /* show the original object, not coerced object */
5235 coerce_failed(x, y);
5236 }
5237 return ret;
5238}
5239
5240static VALUE
5241fix_and(VALUE x, VALUE y)
5242{
5243 if (FIXNUM_P(y)) {
5244 long val = FIX2LONG(x) & FIX2LONG(y);
5245 return LONG2NUM(val);
5246 }
5247
5248 if (RB_BIGNUM_TYPE_P(y)) {
5249 return rb_big_and(y, x);
5250 }
5251
5252 return rb_num_coerce_bit(x, y, '&');
5253}
5254
5255/*
5256 * call-seq:
5257 * self & other -> integer
5258 *
5259 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5260 * in +self+ and +other+ are 1, 0 otherwise:
5261 *
5262 * "%04b" % (0b0101 & 0b0110) # => "0100"
5263 *
5264 * Raises an exception if +other+ is not an \Integer.
5265 *
5266 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5267 *
5268 */
5269
5270VALUE
5271rb_int_and(VALUE x, VALUE y)
5272{
5273 if (FIXNUM_P(x)) {
5274 return fix_and(x, y);
5275 }
5276 else if (RB_BIGNUM_TYPE_P(x)) {
5277 return rb_big_and(x, y);
5278 }
5279 return Qnil;
5280}
5281
5282static VALUE
5283fix_or(VALUE x, VALUE y)
5284{
5285 if (FIXNUM_P(y)) {
5286 long val = FIX2LONG(x) | FIX2LONG(y);
5287 return LONG2NUM(val);
5288 }
5289
5290 if (RB_BIGNUM_TYPE_P(y)) {
5291 return rb_big_or(y, x);
5292 }
5293
5294 return rb_num_coerce_bit(x, y, '|');
5295}
5296
5297/*
5298 * call-seq:
5299 * self | other -> integer
5300 *
5301 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5302 * in +self+ or +other+ is 1, 0 otherwise:
5303 *
5304 * "%04b" % (0b0101 | 0b0110) # => "0111"
5305 *
5306 * Raises an exception if +other+ is not an \Integer.
5307 *
5308 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5309 *
5310 */
5311
5312static VALUE
5313int_or(VALUE x, VALUE y)
5314{
5315 if (FIXNUM_P(x)) {
5316 return fix_or(x, y);
5317 }
5318 else if (RB_BIGNUM_TYPE_P(x)) {
5319 return rb_big_or(x, y);
5320 }
5321 return Qnil;
5322}
5323
5324static VALUE
5325fix_xor(VALUE x, VALUE y)
5326{
5327 if (FIXNUM_P(y)) {
5328 long val = FIX2LONG(x) ^ FIX2LONG(y);
5329 return LONG2NUM(val);
5330 }
5331
5332 if (RB_BIGNUM_TYPE_P(y)) {
5333 return rb_big_xor(y, x);
5334 }
5335
5336 return rb_num_coerce_bit(x, y, '^');
5337}
5338
5339/*
5340 * call-seq:
5341 * self ^ other -> integer
5342 *
5343 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5344 * in +self+ and +other+ are different, 0 otherwise:
5345 *
5346 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5347 *
5348 * Raises an exception if +other+ is not an \Integer.
5349 *
5350 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5351 *
5352 */
5353
5354VALUE
5355rb_int_xor(VALUE x, VALUE y)
5356{
5357 if (FIXNUM_P(x)) {
5358 return fix_xor(x, y);
5359 }
5360 else if (RB_BIGNUM_TYPE_P(x)) {
5361 return rb_big_xor(x, y);
5362 }
5363 return Qnil;
5364}
5365
5366static VALUE
5367rb_fix_lshift(VALUE x, VALUE y)
5368{
5369 long val, width;
5370
5371 val = NUM2LONG(x);
5372 if (!val) return (rb_to_int(y), INT2FIX(0));
5373 if (!FIXNUM_P(y))
5374 return rb_big_lshift(rb_int2big(val), y);
5375 width = FIX2LONG(y);
5376 if (width < 0)
5377 return fix_rshift(val, (unsigned long)-width);
5378 return fix_lshift(val, width);
5379}
5380
5381static VALUE
5382fix_lshift(long val, unsigned long width)
5383{
5384 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5385 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5386 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5387 }
5388 val = val << width;
5389 return LONG2NUM(val);
5390}
5391
5392/*
5393 * call-seq:
5394 * self << count -> integer
5395 *
5396 * Returns +self+ with bits shifted +count+ positions to the left,
5397 * or to the right if +count+ is negative:
5398 *
5399 * n = 0b11110000
5400 * "%08b" % (n << 1) # => "111100000"
5401 * "%08b" % (n << 3) # => "11110000000"
5402 * "%08b" % (n << -1) # => "01111000"
5403 * "%08b" % (n << -3) # => "00011110"
5404 *
5405 * Related: Integer#>>.
5406 *
5407 */
5408
5409VALUE
5410rb_int_lshift(VALUE x, VALUE y)
5411{
5412 if (FIXNUM_P(x)) {
5413 return rb_fix_lshift(x, y);
5414 }
5415 else if (RB_BIGNUM_TYPE_P(x)) {
5416 return rb_big_lshift(x, y);
5417 }
5418 return Qnil;
5419}
5420
5421static VALUE
5422rb_fix_rshift(VALUE x, VALUE y)
5423{
5424 long i, val;
5425
5426 val = FIX2LONG(x);
5427 if (!val) return (rb_to_int(y), INT2FIX(0));
5428 if (!FIXNUM_P(y))
5429 return rb_big_rshift(rb_int2big(val), y);
5430 i = FIX2LONG(y);
5431 if (i == 0) return x;
5432 if (i < 0)
5433 return fix_lshift(val, (unsigned long)-i);
5434 return fix_rshift(val, i);
5435}
5436
5437static VALUE
5438fix_rshift(long val, unsigned long i)
5439{
5440 if (i >= sizeof(long)*CHAR_BIT-1) {
5441 if (val < 0) return INT2FIX(-1);
5442 return INT2FIX(0);
5443 }
5444 val = RSHIFT(val, i);
5445 return LONG2FIX(val);
5446}
5447
5448/*
5449 * call-seq:
5450 * self >> count -> integer
5451 *
5452 * Returns +self+ with bits shifted +count+ positions to the right,
5453 * or to the left if +count+ is negative:
5454 *
5455 * n = 0b11110000
5456 * "%08b" % (n >> 1) # => "01111000"
5457 * "%08b" % (n >> 3) # => "00011110"
5458 * "%08b" % (n >> -1) # => "111100000"
5459 * "%08b" % (n >> -3) # => "11110000000"
5460 *
5461 * Related: Integer#<<.
5462 *
5463 */
5464
5465VALUE
5466rb_int_rshift(VALUE x, VALUE y)
5467{
5468 if (FIXNUM_P(x)) {
5469 return rb_fix_rshift(x, y);
5470 }
5471 else if (RB_BIGNUM_TYPE_P(x)) {
5472 return rb_big_rshift(x, y);
5473 }
5474 return Qnil;
5475}
5476
5477VALUE
5478rb_fix_aref(VALUE fix, VALUE idx)
5479{
5480 long val = FIX2LONG(fix);
5481 long i;
5482
5483 idx = rb_to_int(idx);
5484 if (!FIXNUM_P(idx)) {
5485 idx = rb_big_norm(idx);
5486 if (!FIXNUM_P(idx)) {
5487 if (!BIGNUM_SIGN(idx) || val >= 0)
5488 return INT2FIX(0);
5489 return INT2FIX(1);
5490 }
5491 }
5492 i = FIX2LONG(idx);
5493
5494 if (i < 0) return INT2FIX(0);
5495 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5496 if (val < 0) return INT2FIX(1);
5497 return INT2FIX(0);
5498 }
5499 if (val & (1L<<i))
5500 return INT2FIX(1);
5501 return INT2FIX(0);
5502}
5503
5504
5505/* copied from "r_less" in range.c */
5506/* compares _a_ and _b_ and returns:
5507 * < 0: a < b
5508 * = 0: a = b
5509 * > 0: a > b or non-comparable
5510 */
5511static int
5512compare_indexes(VALUE a, VALUE b)
5513{
5514 VALUE r = rb_funcall(a, id_cmp, 1, b);
5515
5516 if (NIL_P(r))
5517 return INT_MAX;
5518 return rb_cmpint(r, a, b);
5519}
5520
5521static VALUE
5522generate_mask(VALUE len)
5523{
5524 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5525}
5526
5527static VALUE
5528int_aref2(VALUE num, VALUE beg, VALUE len)
5529{
5530 if (RB_TYPE_P(num, T_BIGNUM)) {
5531 return rb_big_aref2(num, beg, len);
5532 }
5533 else {
5534 num = rb_int_rshift(num, beg);
5535 VALUE mask = generate_mask(len);
5536 return rb_int_and(num, mask);
5537 }
5538}
5539
5540static VALUE
5541int_aref1(VALUE num, VALUE arg)
5542{
5543 VALUE beg, end;
5544 int excl;
5545
5546 if (rb_range_values(arg, &beg, &end, &excl)) {
5547 if (NIL_P(beg)) {
5548 /* beginless range */
5549 if (!RTEST(num_negative_p(end))) {
5550 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5551 VALUE mask = generate_mask(end);
5552 if (int_zero_p(rb_int_and(num, mask))) {
5553 return INT2FIX(0);
5554 }
5555 else {
5556 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5557 }
5558 }
5559 else {
5560 return INT2FIX(0);
5561 }
5562 }
5563
5564 int cmp = compare_indexes(beg, end);
5565 if (!NIL_P(end) && cmp < 0) {
5566 VALUE len = rb_int_minus(end, beg);
5567 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5568 return int_aref2(num, beg, len);
5569 }
5570 else if (cmp == 0) {
5571 if (excl) return INT2FIX(0);
5572 arg = beg;
5573 goto one_bit;
5574 }
5575 return rb_int_rshift(num, beg);
5576 }
5577
5578one_bit:
5579 if (FIXNUM_P(num)) {
5580 return rb_fix_aref(num, arg);
5581 }
5582 else if (RB_BIGNUM_TYPE_P(num)) {
5583 return rb_big_aref(num, arg);
5584 }
5585 return Qnil;
5586}
5587
5588/*
5589 * call-seq:
5590 * self[offset] -> 0 or 1
5591 * self[offset, size] -> integer
5592 * self[range] -> integer
5593 *
5594 * Returns a slice of bits from +self+.
5595 *
5596 * With argument +offset+, returns the bit at the given offset,
5597 * where offset 0 refers to the least significant bit:
5598 *
5599 * n = 0b10 # => 2
5600 * n[0] # => 0
5601 * n[1] # => 1
5602 * n[2] # => 0
5603 * n[3] # => 0
5604 *
5605 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5606 * Thus, negative index always returns zero:
5607 *
5608 * 255[-1] # => 0
5609 *
5610 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5611 * beginning at +offset+ and including bits of greater significance:
5612 *
5613 * n = 0b111000 # => 56
5614 * "%010b" % n[0, 10] # => "0000111000"
5615 * "%010b" % n[4, 10] # => "0000000011"
5616 *
5617 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5618 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5619 *
5620 * n = 0b111000 # => 56
5621 * "%010b" % n[0..9] # => "0000111000"
5622 * "%010b" % n[4..9] # => "0000000011"
5623 *
5624 * Raises an exception if the slice cannot be constructed.
5625 */
5626
5627static VALUE
5628int_aref(int const argc, VALUE * const argv, VALUE const num)
5629{
5630 rb_check_arity(argc, 1, 2);
5631 if (argc == 2) {
5632 return int_aref2(num, argv[0], argv[1]);
5633 }
5634 return int_aref1(num, argv[0]);
5635
5636 return Qnil;
5637}
5638
5639/*
5640 * call-seq:
5641 * to_f -> float
5642 *
5643 * Converts +self+ to a Float:
5644 *
5645 * 1.to_f # => 1.0
5646 * -1.to_f # => -1.0
5647 *
5648 * If the value of +self+ does not fit in a Float,
5649 * the result is infinity:
5650 *
5651 * (10**400).to_f # => Infinity
5652 * (-10**400).to_f # => -Infinity
5653 *
5654 */
5655
5656static VALUE
5657int_to_f(VALUE num)
5658{
5659 double val;
5660
5661 if (FIXNUM_P(num)) {
5662 val = (double)FIX2LONG(num);
5663 }
5664 else if (RB_BIGNUM_TYPE_P(num)) {
5665 val = rb_big2dbl(num);
5666 }
5667 else {
5668 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5669 }
5670
5671 return DBL2NUM(val);
5672}
5673
5674static VALUE
5675fix_abs(VALUE fix)
5676{
5677 long i = FIX2LONG(fix);
5678
5679 if (i < 0) i = -i;
5680
5681 return LONG2NUM(i);
5682}
5683
5684VALUE
5685rb_int_abs(VALUE num)
5686{
5687 if (FIXNUM_P(num)) {
5688 return fix_abs(num);
5689 }
5690 else if (RB_BIGNUM_TYPE_P(num)) {
5691 return rb_big_abs(num);
5692 }
5693 return Qnil;
5694}
5695
5696static VALUE
5697fix_size(VALUE fix)
5698{
5699 return INT2FIX(sizeof(long));
5700}
5701
5702VALUE
5703rb_int_size(VALUE num)
5704{
5705 if (FIXNUM_P(num)) {
5706 return fix_size(num);
5707 }
5708 else if (RB_BIGNUM_TYPE_P(num)) {
5709 return rb_big_size_m(num);
5710 }
5711 return Qnil;
5712}
5713
5714static VALUE
5715rb_fix_bit_length(VALUE fix)
5716{
5717 long v = FIX2LONG(fix);
5718 if (v < 0)
5719 v = ~v;
5720 return LONG2FIX(bit_length(v));
5721}
5722
5723VALUE
5724rb_int_bit_length(VALUE num)
5725{
5726 if (FIXNUM_P(num)) {
5727 return rb_fix_bit_length(num);
5728 }
5729 else if (RB_BIGNUM_TYPE_P(num)) {
5730 return rb_big_bit_length(num);
5731 }
5732 return Qnil;
5733}
5734
5735static VALUE
5736rb_fix_digits(VALUE fix, long base)
5737{
5738 VALUE digits;
5739 long x = FIX2LONG(fix);
5740
5741 RUBY_ASSERT(x >= 0);
5742
5743 if (base < 2)
5744 rb_raise(rb_eArgError, "invalid radix %ld", base);
5745
5746 if (x == 0)
5747 return rb_ary_new_from_args(1, INT2FIX(0));
5748
5749 digits = rb_ary_new();
5750 while (x >= base) {
5751 long q = x % base;
5752 rb_ary_push(digits, LONG2NUM(q));
5753 x /= base;
5754 }
5755 rb_ary_push(digits, LONG2NUM(x));
5756
5757 return digits;
5758}
5759
5760static VALUE
5761rb_int_digits_bigbase(VALUE num, VALUE base)
5762{
5763 VALUE digits, bases;
5764
5765 RUBY_ASSERT(!rb_num_negative_p(num));
5766
5767 if (RB_BIGNUM_TYPE_P(base))
5768 base = rb_big_norm(base);
5769
5770 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5771 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5772 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5773 rb_raise(rb_eArgError, "negative radix");
5774
5775 if (FIXNUM_P(base) && FIXNUM_P(num))
5776 return rb_fix_digits(num, FIX2LONG(base));
5777
5778 if (FIXNUM_P(num))
5779 return rb_ary_new_from_args(1, num);
5780
5781 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5782 digits = rb_ary_new();
5783 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5784 VALUE qr = rb_int_divmod(num, base);
5785 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5786 num = RARRAY_AREF(qr, 0);
5787 }
5788 return digits;
5789 }
5790
5791 bases = rb_ary_new();
5792 for (VALUE b = base; int_le(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5793 rb_ary_push(bases, b);
5794 }
5795 digits = rb_ary_new_from_args(1, num);
5796 while (RARRAY_LEN(bases)) {
5797 VALUE b = rb_ary_pop(bases);
5798 long i, last_idx = RARRAY_LEN(digits) - 1;
5799 for(i = last_idx; i >= 0; i--) {
5800 VALUE n = RARRAY_AREF(digits, i);
5801 VALUE divmod = rb_int_divmod(n, b);
5802 VALUE div = RARRAY_AREF(divmod, 0);
5803 VALUE mod = RARRAY_AREF(divmod, 1);
5804 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5805 rb_ary_store(digits, 2 * i, mod);
5806 }
5807 }
5808
5809 return digits;
5810}
5811
5812/*
5813 * call-seq:
5814 * digits(base = 10) -> array_of_integers
5815 *
5816 * Returns an array of integers representing the +base+-radix
5817 * digits of +self+;
5818 * the first element of the array represents the least significant digit:
5819 *
5820 * 12345.digits # => [5, 4, 3, 2, 1]
5821 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5822 * 12345.digits(100) # => [45, 23, 1]
5823 *
5824 * Raises an exception if +self+ is negative or +base+ is less than 2.
5825 *
5826 */
5827
5828static VALUE
5829rb_int_digits(int argc, VALUE *argv, VALUE num)
5830{
5831 VALUE base_value;
5832 long base;
5833
5834 if (rb_num_negative_p(num))
5835 rb_raise(rb_eMathDomainError, "out of domain");
5836
5837 if (rb_check_arity(argc, 0, 1)) {
5838 base_value = rb_to_int(argv[0]);
5839 if (!RB_INTEGER_TYPE_P(base_value))
5840 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5841 rb_obj_classname(argv[0]));
5842 if (RB_BIGNUM_TYPE_P(base_value))
5843 return rb_int_digits_bigbase(num, base_value);
5844
5845 base = FIX2LONG(base_value);
5846 if (base < 0)
5847 rb_raise(rb_eArgError, "negative radix");
5848 else if (base < 2)
5849 rb_raise(rb_eArgError, "invalid radix %ld", base);
5850 }
5851 else
5852 base = 10;
5853
5854 if (FIXNUM_P(num))
5855 return rb_fix_digits(num, base);
5856 else if (RB_BIGNUM_TYPE_P(num))
5857 return rb_int_digits_bigbase(num, LONG2FIX(base));
5858
5859 return Qnil;
5860}
5861
5862static VALUE
5863int_upto_size(VALUE from, VALUE args, VALUE eobj)
5864{
5865 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5866}
5867
5868/*
5869 * call-seq:
5870 * upto(limit) {|i| ... } -> self
5871 * upto(limit) -> enumerator
5872 *
5873 * Calls the given block with each integer value from +self+ up to +limit+;
5874 * returns +self+:
5875 *
5876 * a = []
5877 * 5.upto(10) {|i| a << i } # => 5
5878 * a # => [5, 6, 7, 8, 9, 10]
5879 * a = []
5880 * -5.upto(0) {|i| a << i } # => -5
5881 * a # => [-5, -4, -3, -2, -1, 0]
5882 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5883 *
5884 * With no block given, returns an Enumerator.
5885 *
5886 */
5887
5888static VALUE
5889int_upto(VALUE from, VALUE to)
5890{
5891 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5892 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5893 long i, end;
5894
5895 end = FIX2LONG(to);
5896 for (i = FIX2LONG(from); i <= end; i++) {
5897 rb_yield(LONG2FIX(i));
5898 }
5899 }
5900 else {
5901 VALUE i = from, c;
5902
5903 while (!(c = rb_funcall(i, '>', 1, to))) {
5904 rb_yield(i);
5905 i = rb_funcall(i, '+', 1, INT2FIX(1));
5906 }
5907 ensure_cmp(c, i, to);
5908 }
5909 return from;
5910}
5911
5912static VALUE
5913int_downto_size(VALUE from, VALUE args, VALUE eobj)
5914{
5915 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5916}
5917
5918/*
5919 * call-seq:
5920 * downto(limit) {|i| ... } -> self
5921 * downto(limit) -> enumerator
5922 *
5923 * Calls the given block with each integer value from +self+ down to +limit+;
5924 * returns +self+:
5925 *
5926 * a = []
5927 * 10.downto(5) {|i| a << i } # => 10
5928 * a # => [10, 9, 8, 7, 6, 5]
5929 * a = []
5930 * 0.downto(-5) {|i| a << i } # => 0
5931 * a # => [0, -1, -2, -3, -4, -5]
5932 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5933 *
5934 * With no block given, returns an Enumerator.
5935 *
5936 */
5937
5938static VALUE
5939int_downto(VALUE from, VALUE to)
5940{
5941 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5942 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5943 long i, end;
5944
5945 end = FIX2LONG(to);
5946 for (i=FIX2LONG(from); i >= end; i--) {
5947 rb_yield(LONG2FIX(i));
5948 }
5949 }
5950 else {
5951 VALUE i = from, c;
5952
5953 while (!(c = rb_funcall(i, '<', 1, to))) {
5954 rb_yield(i);
5955 i = rb_funcall(i, '-', 1, INT2FIX(1));
5956 }
5957 ensure_cmp(c, i, to);
5958 }
5959 return from;
5960}
5961
5962static VALUE
5963int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5964{
5965 return int_neg_p(num) ? INT2FIX(0) : num;
5966}
5967
5968/*
5969 * call-seq:
5970 * round(ndigits= 0, half: :up) -> integer
5971 *
5972 * Returns +self+ rounded to the nearest value with
5973 * a precision of +ndigits+ decimal digits.
5974 *
5975 * When +ndigits+ is negative, the returned value
5976 * has at least <tt>ndigits.abs</tt> trailing zeros:
5977 *
5978 * 555.round(-1) # => 560
5979 * 555.round(-2) # => 600
5980 * 555.round(-3) # => 1000
5981 * -555.round(-2) # => -600
5982 * 555.round(-4) # => 0
5983 *
5984 * Returns +self+ when +ndigits+ is zero or positive.
5985 *
5986 * 555.round # => 555
5987 * 555.round(1) # => 555
5988 * 555.round(50) # => 555
5989 *
5990 * If keyword argument +half+ is given,
5991 * and +self+ is equidistant from the two candidate values,
5992 * the rounding is according to the given +half+ value:
5993 *
5994 * - +:up+ or +nil+: round away from zero:
5995 *
5996 * 25.round(-1, half: :up) # => 30
5997 * (-25).round(-1, half: :up) # => -30
5998 *
5999 * - +:down+: round toward zero:
6000 *
6001 * 25.round(-1, half: :down) # => 20
6002 * (-25).round(-1, half: :down) # => -20
6003 *
6004 *
6005 * - +:even+: round toward the candidate whose last nonzero digit is even:
6006 *
6007 * 25.round(-1, half: :even) # => 20
6008 * 15.round(-1, half: :even) # => 20
6009 * (-25).round(-1, half: :even) # => -20
6010 *
6011 * Raises and exception if the value for +half+ is invalid.
6012 *
6013 * Related: Integer#truncate.
6014 *
6015 */
6016
6017static VALUE
6018int_round(int argc, VALUE* argv, VALUE num)
6019{
6020 int ndigits;
6021 int mode;
6022 VALUE nd, opt;
6023
6024 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
6025 ndigits = NUM2INT(nd);
6026 mode = rb_num_get_rounding_option(opt);
6027 if (ndigits >= 0) {
6028 return num;
6029 }
6030 return rb_int_round(num, ndigits, mode);
6031}
6032
6033/*
6034 * :markup: markdown
6035 *
6036 * call-seq:
6037 * floor(ndigits = 0) -> integer
6038 *
6039 * Returns an integer that is a "floor" value for `self`,
6040 * as specified by the given `ndigits`,
6041 * which must be an
6042 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6043 *
6044 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6045 *
6046 * ```
6047 * 0.floor(2) # => 0
6048 * 0.floor(-2) # => 0
6049 * ```
6050 *
6051 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6052 *
6053 * ```
6054 * 555.floor # => 555
6055 * 555.floor(50) # => 555
6056 * ```
6057 *
6058 * - When `self` is non-zero and `ndigits` is negative,
6059 * returns a value based on a computed granularity:
6060 *
6061 * - The granularity is `10 ** ndigits.abs`.
6062 * - The returned value is the largest multiple of the granularity
6063 * that is less than or equal to `self`.
6064 *
6065 * Examples with positive `self`:
6066 *
6067 * | ndigits | Granularity | 1234.floor(ndigits) |
6068 * |--------:|------------:|--------------------:|
6069 * | -1 | 10 | 1230 |
6070 * | -2 | 100 | 1200 |
6071 * | -3 | 1000 | 1000 |
6072 * | -4 | 10000 | 0 |
6073 * | -5 | 100000 | 0 |
6074 *
6075 * Examples with negative `self`:
6076 *
6077 * | ndigits | Granularity | -1234.floor(ndigits) |
6078 * |--------:|------------:|---------------------:|
6079 * | -1 | 10 | -1240 |
6080 * | -2 | 100 | -1300 |
6081 * | -3 | 1000 | -2000 |
6082 * | -4 | 10000 | -10000 |
6083 * | -5 | 100000 | -100000 |
6084 *
6085 * Related: Integer#ceil.
6086 *
6087 */
6088
6089static VALUE
6090int_floor(int argc, VALUE* argv, VALUE num)
6091{
6092 int ndigits;
6093
6094 if (!rb_check_arity(argc, 0, 1)) return num;
6095 ndigits = NUM2INT(argv[0]);
6096 if (ndigits >= 0) {
6097 return num;
6098 }
6099 return rb_int_floor(num, ndigits);
6100}
6101
6102/*
6103 * :markup: markdown
6104 *
6105 * call-seq:
6106 * ceil(ndigits = 0) -> integer
6107 *
6108 * Returns an integer that is a "ceiling" value for `self`,
6109 * as specified by the given `ndigits`,
6110 * which must be an
6111 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6112 *
6113 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6114 *
6115 * ```
6116 * 0.ceil(2) # => 0
6117 * 0.ceil(-2) # => 0
6118 * ```
6119 *
6120 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6121 *
6122 * ```
6123 * 555.ceil # => 555
6124 * 555.ceil(50) # => 555
6125 * ```
6126 *
6127 * - When `self` is non-zero and `ndigits` is negative,
6128 * returns a value based on a computed granularity:
6129 *
6130 * - The granularity is `10 ** ndigits.abs`.
6131 * - The returned value is the smallest multiple of the granularity
6132 * that is greater than or equal to `self`.
6133 *
6134 * Examples with positive `self`:
6135 *
6136 * | ndigits | Granularity | 1234.ceil(ndigits) |
6137 * |--------:|------------:|-------------------:|
6138 * | -1 | 10 | 1240 |
6139 * | -2 | 100 | 1300 |
6140 * | -3 | 1000 | 2000 |
6141 * | -4 | 10000 | 10000 |
6142 * | -5 | 100000 | 100000 |
6143 *
6144 * Examples with negative `self`:
6145 *
6146 * | ndigits | Granularity | -1234.ceil(ndigits) |
6147 * |--------:|------------:|--------------------:|
6148 * | -1 | 10 | -1230 |
6149 * | -2 | 100 | -1200 |
6150 * | -3 | 1000 | -1000 |
6151 * | -4 | 10000 | 0 |
6152 * | -5 | 100000 | 0 |
6153 *
6154 * Related: Integer#floor.
6155 */
6156
6157static VALUE
6158int_ceil(int argc, VALUE* argv, VALUE num)
6159{
6160 int ndigits;
6161
6162 if (!rb_check_arity(argc, 0, 1)) return num;
6163 ndigits = NUM2INT(argv[0]);
6164 if (ndigits >= 0) {
6165 return num;
6166 }
6167 return rb_int_ceil(num, ndigits);
6168}
6169
6170/*
6171 * call-seq:
6172 * truncate(ndigits = 0) -> integer
6173 *
6174 * Returns +self+ truncated (toward zero) to
6175 * a precision of +ndigits+ decimal digits.
6176 *
6177 * When +ndigits+ is negative, the returned value
6178 * has at least <tt>ndigits.abs</tt> trailing zeros:
6179 *
6180 * 555.truncate(-1) # => 550
6181 * 555.truncate(-2) # => 500
6182 * -555.truncate(-2) # => -500
6183 *
6184 * Returns +self+ when +ndigits+ is zero or positive.
6185 *
6186 * 555.truncate # => 555
6187 * 555.truncate(50) # => 555
6188 *
6189 * Related: Integer#round.
6190 *
6191 */
6192
6193static VALUE
6194int_truncate(int argc, VALUE* argv, VALUE num)
6195{
6196 int ndigits;
6197
6198 if (!rb_check_arity(argc, 0, 1)) return num;
6199 ndigits = NUM2INT(argv[0]);
6200 if (ndigits >= 0) {
6201 return num;
6202 }
6203 return rb_int_truncate(num, ndigits);
6204}
6205
6206#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6207rettype \
6208prefix##_isqrt(argtype n) \
6209{ \
6210 if (!argtype##_IN_DOUBLE_P(n)) { \
6211 unsigned int b = bit_length(n); \
6212 argtype t; \
6213 rettype x = (rettype)(n >> (b/2+1)); \
6214 x |= ((rettype)1LU << (b-1)/2); \
6215 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6216 return x; \
6217 } \
6218 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6219 /* libm sqrt may returns a larger approximation than actual. */ \
6220 /* Our isqrt always returns a smaller approximation. */ \
6221 if (x * x > n) x--; \
6222 return x; \
6223}
6224
6225#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6226# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6227#else
6228# define RB_ULONG_IN_DOUBLE_P(n) 1
6229#endif
6230#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6231#define RB_ULONG unsigned long
6232DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
6233
6234#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6235# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6236# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6237# else
6238# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6239# endif
6240# ifdef ULL_TO_DOUBLE
6241# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6242# else
6243# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6244# endif
6245DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6246#endif
6247
6248#define domain_error(msg) \
6249 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6250
6251/*
6252 * call-seq:
6253 * Integer.sqrt(numeric) -> integer
6254 *
6255 * Returns the integer square root of the non-negative integer +n+,
6256 * which is the largest non-negative integer less than or equal to the
6257 * square root of +numeric+.
6258 *
6259 * Integer.sqrt(0) # => 0
6260 * Integer.sqrt(1) # => 1
6261 * Integer.sqrt(24) # => 4
6262 * Integer.sqrt(25) # => 5
6263 * Integer.sqrt(10**400) # => 10**200
6264 *
6265 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6266 *
6267 * Integer.sqrt(Complex(4, 0)) # => 2
6268 * Integer.sqrt(Rational(4, 1)) # => 2
6269 * Integer.sqrt(4.0) # => 2
6270 * Integer.sqrt(3.14159) # => 1
6271 *
6272 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6273 * except that the result of the latter code may differ from the true value
6274 * due to the limited precision of floating point arithmetic.
6275 *
6276 * Integer.sqrt(10**46) # => 100000000000000000000000
6277 * Math.sqrt(10**46).floor # => 99999999999999991611392
6278 *
6279 * Raises an exception if +numeric+ is negative.
6280 *
6281 */
6282
6283static VALUE
6284rb_int_s_isqrt(VALUE self, VALUE num)
6285{
6286 unsigned long n, sq;
6287 num = rb_to_int(num);
6288 if (FIXNUM_P(num)) {
6289 if (FIXNUM_NEGATIVE_P(num)) {
6290 domain_error("isqrt");
6291 }
6292 n = FIX2ULONG(num);
6293 sq = rb_ulong_isqrt(n);
6294 return LONG2FIX(sq);
6295 }
6296 else {
6297 size_t biglen;
6298 if (RBIGNUM_NEGATIVE_P(num)) {
6299 domain_error("isqrt");
6300 }
6301 biglen = BIGNUM_LEN(num);
6302 if (biglen == 0) return INT2FIX(0);
6303#if SIZEOF_BDIGIT <= SIZEOF_LONG
6304 /* short-circuit */
6305 if (biglen == 1) {
6306 n = BIGNUM_DIGITS(num)[0];
6307 sq = rb_ulong_isqrt(n);
6308 return ULONG2NUM(sq);
6309 }
6310#endif
6311 return rb_big_isqrt(num);
6312 }
6313}
6314
6315/*
6316 * call-seq:
6317 * Integer.try_convert(object) -> object, integer, or nil
6318 *
6319 * If +object+ is an \Integer object, returns +object+.
6320 * Integer.try_convert(1) # => 1
6321 *
6322 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6323 * calls <tt>object.to_int</tt> and returns the result.
6324 * Integer.try_convert(1.25) # => 1
6325 *
6326 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6327 * Integer.try_convert([]) # => nil
6328 *
6329 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6330 */
6331static VALUE
6332int_s_try_convert(VALUE self, VALUE num)
6333{
6334 return rb_check_integer_type(num);
6335}
6336
6337/*
6338 * Document-class: ZeroDivisionError
6339 *
6340 * Raised when attempting to divide an integer by 0.
6341 *
6342 * 42 / 0 #=> ZeroDivisionError: divided by 0
6343 *
6344 * Note that only division by an exact 0 will raise the exception:
6345 *
6346 * 42 / 0.0 #=> Float::INFINITY
6347 * 42 / -0.0 #=> -Float::INFINITY
6348 * 0 / 0.0 #=> NaN
6349 */
6350
6351/*
6352 * Document-class: FloatDomainError
6353 *
6354 * Raised when attempting to convert special float values (in particular
6355 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6356 *
6357 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6358 */
6359
6360/*
6361 * Document-class: Numeric
6362 *
6363 * \Numeric is the class from which all higher-level numeric classes should inherit.
6364 *
6365 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6366 * Integer are implemented as immediates, which means that each Integer is a single immutable
6367 * object which is always passed by value.
6368 *
6369 * a = 1
6370 * 1.object_id == a.object_id #=> true
6371 *
6372 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6373 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6374 *
6375 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6376 * 1.dup #=> 1
6377 * 1.object_id == 1.dup.object_id #=> true
6378 *
6379 * For this reason, \Numeric should be used when defining other numeric classes.
6380 *
6381 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6382 * Array containing an object that has been coerced into an instance of the new class
6383 * and +self+ (see #coerce).
6384 *
6385 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6386 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6387 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6388 * instances of other numeric classes.
6389 *
6390 * class Tally < Numeric
6391 * def initialize(string)
6392 * @string = string
6393 * end
6394 *
6395 * def to_s
6396 * @string
6397 * end
6398 *
6399 * def to_i
6400 * @string.size
6401 * end
6402 *
6403 * def coerce(other)
6404 * [self.class.new('|' * other.to_i), self]
6405 * end
6406 *
6407 * def <=>(other)
6408 * to_i <=> other.to_i
6409 * end
6410 *
6411 * def +(other)
6412 * self.class.new('|' * (to_i + other.to_i))
6413 * end
6414 *
6415 * def -(other)
6416 * self.class.new('|' * (to_i - other.to_i))
6417 * end
6418 *
6419 * def *(other)
6420 * self.class.new('|' * (to_i * other.to_i))
6421 * end
6422 *
6423 * def /(other)
6424 * self.class.new('|' * (to_i / other.to_i))
6425 * end
6426 * end
6427 *
6428 * tally = Tally.new('||')
6429 * puts tally * 2 #=> "||||"
6430 * puts tally > 1 #=> true
6431 *
6432 * == What's Here
6433 *
6434 * First, what's elsewhere. Class \Numeric:
6435 *
6436 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
6437 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
6438 *
6439 * Here, class \Numeric provides methods for:
6440 *
6441 * - {Querying}[rdoc-ref:Numeric@Querying]
6442 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6443 * - {Converting}[rdoc-ref:Numeric@Converting]
6444 * - {Other}[rdoc-ref:Numeric@Other]
6445 *
6446 * === Querying
6447 *
6448 * - #finite?: Returns true unless +self+ is infinite or not a number.
6449 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6450 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6451 * - #integer?: Returns whether +self+ is an integer.
6452 * - #negative?: Returns whether +self+ is negative.
6453 * - #nonzero?: Returns whether +self+ is not zero.
6454 * - #positive?: Returns whether +self+ is positive.
6455 * - #real?: Returns whether +self+ is a real value.
6456 * - #zero?: Returns whether +self+ is zero.
6457 *
6458 * === Comparing
6459 *
6460 * - #<=>: Returns:
6461 *
6462 * - -1 if +self+ is less than the given value.
6463 * - 0 if +self+ is equal to the given value.
6464 * - 1 if +self+ is greater than the given value.
6465 * - +nil+ if +self+ and the given value are not comparable.
6466 *
6467 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6468 *
6469 * === Converting
6470 *
6471 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6472 * - #-@: Returns the value of +self+, negated.
6473 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6474 * - #abs2: Returns the square of +self+.
6475 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6476 * Math::PI otherwise.
6477 * - #ceil: Returns the smallest number greater than or equal to +self+,
6478 * to a given precision.
6479 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6480 * for the given other value.
6481 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6482 * - #denominator: Returns the denominator (always positive)
6483 * of the Rational representation of +self+.
6484 * - #div: Returns the value of +self+ divided by the given value
6485 * and converted to an integer.
6486 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6487 * from dividing +self+ the given divisor.
6488 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6489 * - #floor: Returns the largest number less than or equal to +self+,
6490 * to a given precision.
6491 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6492 * the given value.
6493 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6494 * - #numerator: Returns the numerator of the Rational representation of +self+;
6495 * has the same sign as +self+.
6496 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6497 * - #quo: Returns the value of +self+ divided by the given value.
6498 * - #real: Returns the real part of +self+.
6499 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6500 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6501 * - #round: Returns the value of +self+ rounded to the nearest value
6502 * for the given a precision.
6503 * - #to_c: Returns the Complex representation of +self+.
6504 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6505 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6506 *
6507 * === Other
6508 *
6509 * - #clone: Returns +self+; does not allow freezing.
6510 * - #dup (aliased as #+@): Returns +self+.
6511 * - #step: Invokes the given block with the sequence of specified numbers.
6512 *
6513 */
6514void
6515Init_Numeric(void)
6516{
6517#ifdef _UNICOSMP
6518 /* Turn off floating point exceptions for divide by zero, etc. */
6519 _set_Creg(0, 0);
6520#endif
6521 id_coerce = rb_intern_const("coerce");
6522 id_to = rb_intern_const("to");
6523 id_by = rb_intern_const("by");
6524
6525 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6528
6529 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6531 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6532 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6533
6534 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6535 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6536 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6537 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6538 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6539 rb_define_method(rb_cNumeric, "div", num_div, 1);
6540 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6541 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6542 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6543 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6544 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6545 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6546 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6547
6548 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6549 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6550
6551 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6552 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6553 rb_define_method(rb_cNumeric, "round", num_round, -1);
6554 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6555 rb_define_method(rb_cNumeric, "step", num_step, -1);
6556 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6557 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6558
6562 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6563 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6564
6565 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6566 rb_define_alias(rb_cInteger, "inspect", "to_s");
6567 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6568 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6569 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6570 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6571 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6572 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6573 rb_define_method(rb_cInteger, "next", int_succ, 0);
6574 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6575 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6576 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6577 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6578 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6579 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6580 rb_define_method(rb_cInteger, "round", int_round, -1);
6581 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6582
6583 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6584 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6585 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6586 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6587 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6588 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6589 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6590 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6591 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6592 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6593 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6594
6595 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6596
6597 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6598 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6599 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6600 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6601 rb_define_method(rb_cInteger, "<", int_lt, 1);
6602 rb_define_method(rb_cInteger, "<=", int_le, 1);
6603
6604 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6605 rb_define_method(rb_cInteger, "|", int_or, 1);
6606 rb_define_method(rb_cInteger, "^", rb_int_xor, 1);
6607 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6608
6609 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6610 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6611
6612 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6613
6614#define fix_to_s_static(n) do { \
6615 VALUE lit = rb_fstring_literal(#n); \
6616 rb_fix_to_s_static[n] = lit; \
6617 rb_vm_register_global_object(lit); \
6618 RB_GC_GUARD(lit); \
6619 } while (0)
6620
6621 fix_to_s_static(0);
6622 fix_to_s_static(1);
6623 fix_to_s_static(2);
6624 fix_to_s_static(3);
6625 fix_to_s_static(4);
6626 fix_to_s_static(5);
6627 fix_to_s_static(6);
6628 fix_to_s_static(7);
6629 fix_to_s_static(8);
6630 fix_to_s_static(9);
6631
6632#undef fix_to_s_static
6633
6635
6638
6639 /*
6640 * The base of the floating point, or number of unique digits used to
6641 * represent the number.
6642 *
6643 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6644 */
6645 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6646 /*
6647 * The number of base digits for the +double+ data type.
6648 *
6649 * Usually defaults to 53.
6650 */
6651 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6652 /*
6653 * The minimum number of significant decimal digits in a double-precision
6654 * floating point.
6655 *
6656 * Usually defaults to 15.
6657 */
6658 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6659 /*
6660 * The smallest possible exponent value in a double-precision floating
6661 * point.
6662 *
6663 * Usually defaults to -1021.
6664 */
6665 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6666 /*
6667 * The largest possible exponent value in a double-precision floating
6668 * point.
6669 *
6670 * Usually defaults to 1024.
6671 */
6672 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6673 /*
6674 * The smallest negative exponent in a double-precision floating point
6675 * where 10 raised to this power minus 1.
6676 *
6677 * Usually defaults to -307.
6678 */
6679 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6680 /*
6681 * The largest positive exponent in a double-precision floating point where
6682 * 10 raised to this power minus 1.
6683 *
6684 * Usually defaults to 308.
6685 */
6686 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6687 /*
6688 * The smallest positive normalized number in a double-precision floating point.
6689 *
6690 * Usually defaults to 2.2250738585072014e-308.
6691 *
6692 * If the platform supports denormalized numbers,
6693 * there are numbers between zero and Float::MIN.
6694 * +0.0.next_float+ returns the smallest positive floating point number
6695 * including denormalized numbers.
6696 */
6697 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6698 /*
6699 * The largest possible integer in a double-precision floating point number.
6700 *
6701 * Usually defaults to 1.7976931348623157e+308.
6702 */
6703 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6704 /*
6705 * The difference between 1 and the smallest double-precision floating
6706 * point number greater than 1.
6707 *
6708 * Usually defaults to 2.2204460492503131e-16.
6709 */
6710 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6711 /*
6712 * An expression representing positive infinity.
6713 */
6714 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6715 /*
6716 * An expression representing a value which is "not a number".
6717 */
6718 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6719
6720 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6721 rb_define_alias(rb_cFloat, "inspect", "to_s");
6722 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6723 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6724 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6725 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6726 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6727 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6728 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6729 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6730 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6731 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6732 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6733 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6734 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6735 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6736 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6737 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6738 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6739 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6740 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6741 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6742
6743 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6744 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6745 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6746 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6747 rb_define_method(rb_cFloat, "round", flo_round, -1);
6748 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6749
6750 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6751 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6752 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6753 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6754 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6755}
6756
6757#undef rb_float_value
6758double
6759rb_float_value(VALUE v)
6760{
6761 return rb_float_value_inline(v);
6762}
6763
6764#undef rb_float_new
6765VALUE
6766rb_float_new(double d)
6767{
6768 return rb_float_new_inline(d);
6769}
6770
6771#include "numeric.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define LONG_LONG
Definition long_long.h:38
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
VALUE rb_float_new_in_heap(double d)
Identical to rb_float_new(), except it does not generate Flonums.
Definition numeric.c:913
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1611
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1404
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2736
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2779
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2589
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3069
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1018
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2858
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1440
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2344
VALUE rb_eZeroDivError
ZeroDivisionError exception.
Definition numeric.c:203
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1427
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1434
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
VALUE rb_eFloatDomainError
FloatDomainError exception.
Definition numeric.c:204
VALUE rb_eMathDomainError
Math::DomainError exception.
Definition math.c:29
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3739
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:646
VALUE rb_cInteger
Module class.
Definition numeric.c:201
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:199
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:235
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:657
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:141
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:894
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFloat
Float class.
Definition numeric.c:200
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3319
Encoding relates APIs.
#define RUBY_FIXNUM_MAX
Maximum possible value that a fixnum can represent.
Definition fixnum.h:55
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3945
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1121
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
Definition enumerator.h:195
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:209
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3361
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:4056
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4764
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
Definition numeric.c:1563
VALUE rb_num_coerce_bit(VALUE lhs, VALUE rhs, ID op)
This one is optimised for bitwise operations, but the API is identical to rb_num_coerce_bin().
Definition numeric.c:5223
VALUE rb_num_coerce_relop(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_cmp(), except for return values.
Definition numeric.c:502
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:487
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:480
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1861
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1992
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3602
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1568
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2791
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2976
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1789
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:690
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
Definition vm_method.c:2262
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1024
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:12730
int len
Length of the buffer.
Definition io.h:8
unsigned long rb_num2uint(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3275
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3269
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3263
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3281
LONG_LONG rb_num2ll(VALUE num)
Converts an instance of rb_cNumeric into C's long long.
unsigned LONG_LONG rb_num2ull(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long long.
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1376
#define RB_FIX2ULONG
Just another name of rb_fix2ulong.
Definition long.h:54
#define RB_FIX2LONG
Just another name of rb_fix2long.
Definition long.h:53
void rb_out_of_int(SIGNED_VALUE num)
This is an utility function to raise an rb_eRangeError.
Definition numeric.c:3190
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3115
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3184
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:281
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
Definition rbignum.h:74
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
Definition numeric.c:3319
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3337
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3328
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3347
static bool RB_FIXNUM_P(VALUE obj)
Checks if the given object is a so-called Fixnum.
#define RTEST
This is an old name of RB_TEST.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376