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