Ruby 4.1.0dev (2026-08-15 revision cfb2ed7c723c5435f630fd70897273db032b0bcc)
numeric.c (cfb2ed7c723c5435f630fd70897273db032b0bcc)
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) {
983 long len;
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) {
999 long len;
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
3197#if SIZEOF_INT < SIZEOF_LONG
3198static void
3199check_int(long num)
3200{
3201 if ((long)(int)num != num) {
3202 rb_out_of_int(num);
3203 }
3204}
3205
3206static void
3207check_uint(unsigned long num, int sign)
3208{
3209 if (sign) {
3210 /* minus */
3211 if (num < (unsigned long)INT_MIN)
3212 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3213 }
3214 else {
3215 /* plus */
3216 if (UINT_MAX < num)
3217 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3218 }
3219}
3220
3221long
3222rb_num2int(VALUE val)
3223{
3224 long num = rb_num2long(val);
3225
3226 check_int(num);
3227 return num;
3228}
3229
3230long
3231rb_fix2int(VALUE val)
3232{
3233 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3234
3235 check_int(num);
3236 return num;
3237}
3238
3239unsigned long
3240rb_num2uint(VALUE val)
3241{
3242 int wrap;
3243 unsigned long num = rb_num2ulong_internal(val, &wrap);
3244
3245 check_uint(num, wrap);
3246 return num;
3247}
3248
3249unsigned long
3250rb_fix2uint(VALUE val)
3251{
3252 unsigned long num;
3253
3254 if (!FIXNUM_P(val)) {
3255 return rb_num2uint(val);
3256 }
3257 num = FIX2ULONG(val);
3258
3259 check_uint(num, FIXNUM_NEGATIVE_P(val));
3260 return num;
3261}
3262#else
3263long
3265{
3266 return rb_num2long(val);
3267}
3268
3269long
3271{
3272 return FIX2INT(val);
3273}
3274
3275unsigned long
3277{
3278 return rb_num2ulong(val);
3279}
3280
3281unsigned long
3283{
3284 return RB_FIX2ULONG(val);
3285}
3286#endif
3287
3288NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3289static void
3290rb_out_of_short(SIGNED_VALUE num)
3291{
3292 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3293 num, num < 0 ? "small" : "big");
3294}
3295
3296static void
3297check_short(long num)
3298{
3299 if ((long)(short)num != num) {
3300 rb_out_of_short(num);
3301 }
3302}
3303
3304static void
3305check_ushort(unsigned long num, int sign)
3306{
3307 if (sign) {
3308 /* minus */
3309 if (num < (unsigned long)SHRT_MIN)
3310 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3311 }
3312 else {
3313 /* plus */
3314 if (USHRT_MAX < num)
3315 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3316 }
3317}
3318
3319short
3321{
3322 long num = rb_num2long(val);
3323
3324 check_short(num);
3325 return num;
3326}
3327
3328short
3330{
3331 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3332
3333 check_short(num);
3334 return num;
3335}
3336
3337unsigned short
3339{
3340 int wrap;
3341 unsigned long num = rb_num2ulong_internal(val, &wrap);
3342
3343 check_ushort(num, wrap);
3344 return num;
3345}
3346
3347unsigned short
3349{
3350 unsigned long num;
3351
3352 if (!FIXNUM_P(val)) {
3353 return rb_num2ushort(val);
3354 }
3355 num = FIX2ULONG(val);
3356
3357 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3358 return num;
3359}
3360
3361VALUE
3363{
3364 long v;
3365
3366 if (FIXNUM_P(val)) return val;
3367
3368 v = rb_num2long(val);
3369 if (!FIXABLE(v))
3370 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3371 return LONG2FIX(v);
3372}
3373
3374#if HAVE_LONG_LONG
3375
3376#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3377#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3378#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3379#ifndef ULLONG_MAX
3380#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3381#endif
3382#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3383 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3384 LLONG_MIN <= (n): \
3385 LLONG_MIN_MINUS_ONE < (n))
3386
3388rb_num2ll(VALUE val)
3389{
3390 if (NIL_P(val)) {
3391 rb_no_implicit_conversion(val, "Integer");
3392 }
3393
3394 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3395
3396 else if (RB_FLOAT_TYPE_P(val)) {
3397 double d = RFLOAT_VALUE(val);
3398 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3399 return (LONG_LONG)d;
3400 }
3401 else {
3402 FLOAT_OUT_OF_RANGE(val, "long long");
3403 }
3404 }
3405 else if (RB_BIGNUM_TYPE_P(val)) {
3406 return rb_big2ll(val);
3407 }
3408 else if (val == Qfalse || val == Qtrue || RB_TYPE_P(val, T_STRING)) {
3409 rb_no_implicit_conversion(val, "Integer");
3410 }
3411
3412 val = rb_to_int(val);
3413 return NUM2LL(val);
3414}
3415
3416unsigned LONG_LONG
3417rb_num2ull(VALUE val)
3418{
3419 if (NIL_P(val)) {
3420 rb_no_implicit_conversion(val, "Integer");
3421 }
3422 else if (FIXNUM_P(val)) {
3423 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3424 }
3425 else if (RB_FLOAT_TYPE_P(val)) {
3426 double d = RFLOAT_VALUE(val);
3427 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3428 if (0 <= d)
3429 return (unsigned LONG_LONG)d;
3430 return (unsigned LONG_LONG)(LONG_LONG)d;
3431 }
3432 else {
3433 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3434 }
3435 }
3436 else if (RB_BIGNUM_TYPE_P(val)) {
3437 return rb_big2ull(val);
3438 }
3439 else {
3440 val = rb_to_int(val);
3441 return NUM2ULL(val);
3442 }
3443}
3444
3445#endif /* HAVE_LONG_LONG */
3446
3447// Conversion functions for unified 128-bit integer structures,
3448// These work with or without native 128-bit integer support.
3449
3450#ifndef HAVE_UINT128_T
3451// Helper function to build 128-bit value from bignum digits (fallback path).
3452static inline void
3453rb_uint128_from_bignum_digits_fallback(rb_uint128_t *result, BDIGIT *digits, size_t length)
3454{
3455 // Build the 128-bit value from bignum digits:
3456 for (long i = length - 1; i >= 0; i--) {
3457 // Shift both low and high parts:
3458 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3459 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3460 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3461 }
3462}
3463
3464// Helper function to convert absolute value of negative bignum to two's complement.
3465// Ruby stores negative bignums as absolute values, so we need to convert to two's complement.
3466static inline void
3467rb_uint128_twos_complement_negate(rb_uint128_t *value)
3468{
3469 if (value->parts.low == 0) {
3470 value->parts.high = ~value->parts.high + 1;
3471 }
3472 else {
3473 value->parts.low = ~value->parts.low + 1;
3474 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3475 }
3476}
3477#endif
3478
3480rb_numeric_to_uint128(VALUE x)
3481{
3482 rb_uint128_t result = {0};
3483 if (RB_FIXNUM_P(x)) {
3484 long value = RB_FIX2LONG(x);
3485 if (value < 0) {
3486 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3487 }
3488#ifdef HAVE_UINT128_T
3489 result.value = (uint128_t)value;
3490#else
3491 result.parts.low = (uint64_t)value;
3492 result.parts.high = 0;
3493#endif
3494 return result;
3495 }
3496 else if (RB_BIGNUM_TYPE_P(x)) {
3497 if (BIGNUM_NEGATIVE_P(x)) {
3498 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3499 }
3500 size_t length = BIGNUM_LEN(x);
3501#ifdef HAVE_UINT128_T
3502 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3503 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3504 }
3505 BDIGIT *digits = BIGNUM_DIGITS(x);
3506 result.value = 0;
3507 for (long i = length - 1; i >= 0; i--) {
3508 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3509 }
3510#else
3511 // Check if bignum fits in 128 bits (16 bytes)
3512 if (length > roomof(16, SIZEOF_BDIGIT)) {
3513 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3514 }
3515 BDIGIT *digits = BIGNUM_DIGITS(x);
3516 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3517#endif
3518 return result;
3519 }
3520 else {
3521 rb_raise(rb_eTypeError, "not an integer");
3522 }
3523}
3524
3526rb_numeric_to_int128(VALUE x)
3527{
3528 rb_int128_t result = {0};
3529 if (RB_FIXNUM_P(x)) {
3530 long value = RB_FIX2LONG(x);
3531#ifdef HAVE_UINT128_T
3532 result.value = (int128_t)value;
3533#else
3534 if (value < 0) {
3535 // Two's complement representation: for negative values, sign extend
3536 // Convert to unsigned: for -1, we want all bits set
3537 result.parts.low = (uint64_t)value; // This will be the two's complement representation
3538 result.parts.high = UINT64_MAX; // Sign extend: all bits set for negative
3539 }
3540 else {
3541 result.parts.low = (uint64_t)value;
3542 result.parts.high = 0;
3543 }
3544#endif
3545 return result;
3546 }
3547 else if (RB_BIGNUM_TYPE_P(x)) {
3548 size_t length = BIGNUM_LEN(x);
3549#ifdef HAVE_UINT128_T
3550 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3551 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3552 }
3553 BDIGIT *digits = BIGNUM_DIGITS(x);
3554 uint128_t unsigned_result = 0;
3555 for (long i = length - 1; i >= 0; i--) {
3556 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3557 }
3558 if (BIGNUM_NEGATIVE_P(x)) {
3559 // Convert from two's complement
3560 // Maximum negative value is 2^127
3561 if (unsigned_result > ((uint128_t)1 << 127)) {
3562 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3563 }
3564 result.value = -(int128_t)(unsigned_result - 1) - 1;
3565 }
3566 else {
3567 // Maximum positive value is 2^127 - 1
3568 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3569 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3570 }
3571 result.value = (int128_t)unsigned_result;
3572 }
3573#else
3574 if (length > roomof(16, SIZEOF_BDIGIT)) {
3575 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3576 }
3577 BDIGIT *digits = BIGNUM_DIGITS(x);
3578 rb_uint128_t unsigned_result = {0};
3579 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3580 if (BIGNUM_NEGATIVE_P(x)) {
3581 // Check if value fits in signed 128-bit (max negative is 2^127)
3582 uint64_t max_neg_high = (uint64_t)1 << 63;
3583 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3584 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3585 }
3586 // Convert from absolute value to two's complement (Ruby stores negative as absolute value)
3587 rb_uint128_twos_complement_negate(&unsigned_result);
3588 result.parts.low = unsigned_result.parts.low;
3589 result.parts.high = (int64_t)unsigned_result.parts.high; // Sign extend
3590 }
3591 else {
3592 // Check if value fits in signed 128-bit (max positive is 2^127 - 1)
3593 // Max positive: high = 0x7FFFFFFFFFFFFFFF, low = 0xFFFFFFFFFFFFFFFF
3594 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3595 if (unsigned_result.parts.high > max_pos_high) {
3596 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3597 }
3598 result.parts.low = unsigned_result.parts.low;
3599 result.parts.high = unsigned_result.parts.high;
3600 }
3601#endif
3602 return result;
3603 }
3604 else {
3605 rb_raise(rb_eTypeError, "not an integer");
3606 }
3607}
3608
3609VALUE
3610rb_uint128_to_numeric(rb_uint128_t n)
3611{
3612#ifdef HAVE_UINT128_T
3613 if (n.value <= (uint128_t)RUBY_FIXNUM_MAX) {
3614 return LONG2FIX((long)n.value);
3615 }
3616 return rb_uint128t2big(n.value);
3617#else
3618 // If high part is zero and low part fits in fixnum
3619 if (n.parts.high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3620 return LONG2FIX((long)n.parts.low);
3621 }
3622 // Convert to bignum by building it from the two 64-bit parts
3623 VALUE bignum = rb_ull2big(n.parts.low);
3624 if (n.parts.high > 0) {
3625 VALUE high_bignum = rb_ull2big(n.parts.high);
3626 // Multiply high part by 2^64 and add to low part
3627 VALUE shifted_value = rb_int_lshift(high_bignum, INT2FIX(64));
3628 bignum = rb_int_plus(bignum, shifted_value);
3629 }
3630 return bignum;
3631#endif
3632}
3633
3634VALUE
3635rb_int128_to_numeric(rb_int128_t n)
3636{
3637#ifdef HAVE_UINT128_T
3638 if (FIXABLE(n.value)) {
3639 return LONG2FIX((long)n.value);
3640 }
3641 return rb_int128t2big(n.value);
3642#else
3643 int64_t high = (int64_t)n.parts.high;
3644 // If it's a small positive value that fits in fixnum
3645 if (high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3646 return LONG2FIX((long)n.parts.low);
3647 }
3648 // Check if it's negative (high bit of high part is set)
3649 if (high < 0) {
3650 // Negative value - convert from two's complement to absolute value
3651 rb_uint128_t unsigned_value = {0};
3652 if (n.parts.low == 0) {
3653 unsigned_value.parts.low = 0;
3654 unsigned_value.parts.high = ~n.parts.high + 1;
3655 }
3656 else {
3657 unsigned_value.parts.low = ~n.parts.low + 1;
3658 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3659 }
3660 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3661 return rb_int_uminus(bignum);
3662 }
3663 else {
3664 // Positive value
3665 union uint128_int128_conversion conversion = {
3666 .int128 = n
3667 };
3668 return rb_uint128_to_numeric(conversion.uint128);
3669 }
3670#endif
3671}
3672
3673/********************************************************************
3674 *
3675 * Document-class: Integer
3676 *
3677 * An \Integer object represents an integer value.
3678 *
3679 * You can create an \Integer object explicitly with:
3680 *
3681 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3682 *
3683 * You can convert certain objects to Integers with:
3684 *
3685 * - Method #Integer.
3686 *
3687 * An attempt to add a singleton method to an instance of this class
3688 * causes an exception to be raised.
3689 *
3690 * == What's Here
3691 *
3692 * First, what's elsewhere. Class \Integer:
3693 *
3694 * - Inherits from
3695 * {class Numeric}[rdoc-ref:Numeric@Whats+Here]
3696 * and {class Object}[rdoc-ref:Object@Whats+Here].
3697 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
3698 *
3699 * Here, class \Integer provides methods for:
3700 *
3701 * - {Querying}[rdoc-ref:Integer@Querying]
3702 * - {Comparing}[rdoc-ref:Integer@Comparing]
3703 * - {Converting}[rdoc-ref:Integer@Converting]
3704 * - {Other}[rdoc-ref:Integer@Other]
3705 *
3706 * === Querying
3707 *
3708 * - #allbits?: Returns whether all bits in +self+ are set.
3709 * - #anybits?: Returns whether any bits in +self+ are set.
3710 * - #nobits?: Returns whether no bits in +self+ are set.
3711 *
3712 * === Comparing
3713 *
3714 * - #<: Returns whether +self+ is less than the given value.
3715 * - #<=: Returns whether +self+ is less than or equal to the given value.
3716 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3717 * to, or greater than the given value.
3718 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3719 * value.
3720 * - #>: Returns whether +self+ is greater than the given value.
3721 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3722 *
3723 * === Converting
3724 *
3725 * - ::sqrt: Returns the integer square root of the given value.
3726 * - ::try_convert: Returns the given value converted to an \Integer.
3727 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3728 * - #&: Returns the bitwise AND of +self+ and the given value.
3729 * - #*: Returns the product of +self+ and the given value.
3730 * - #**: Returns the value of +self+ raised to the power of the given value.
3731 * - #+: Returns the sum of +self+ and the given value.
3732 * - #-: Returns the difference of +self+ and the given value.
3733 * - #/: Returns the quotient of +self+ and the given value.
3734 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3735 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3736 * - #[]: Returns a slice of bits from +self+.
3737 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3738 * - #|: Returns the bitwise OR of +self+ and the given value.
3739 * - #ceil: Returns the smallest number greater than or equal to +self+.
3740 * - #chr: Returns a 1-character string containing the character
3741 * represented by the value of +self+.
3742 * - #digits: Returns an array of integers representing the base-radix digits
3743 * of +self+.
3744 * - #div: Returns the integer result of dividing +self+ by the given value.
3745 * - #divmod: Returns a 2-element array containing the quotient and remainder
3746 * results of dividing +self+ by the given value.
3747 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3748 * - #floor: Returns the greatest number smaller than or equal to +self+.
3749 * - #pow: Returns the modular exponentiation of +self+.
3750 * - #pred: Returns the integer predecessor of +self+.
3751 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3752 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3753 * - #succ (aliased as #next): Returns the integer successor of +self+.
3754 * - #to_f: Returns +self+ converted to a Float.
3755 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3756 * representation of +self+ in the given radix.
3757 * - #truncate: Returns +self+ truncated to the given precision.
3758 *
3759 * === Other
3760 *
3761 * - #downto: Calls the given block with each integer value from +self+
3762 * down to the given value.
3763 * - #times: Calls the given block +self+ times with each integer
3764 * in <tt>(0..self-1)</tt>.
3765 * - #upto: Calls the given block with each integer value from +self+
3766 * up to the given value.
3767 *
3768 */
3769
3770VALUE
3771rb_int_odd_p(VALUE num)
3772{
3773 if (FIXNUM_P(num)) {
3774 return RBOOL(num & 2);
3775 }
3776 else {
3777 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3778 return rb_big_odd_p(num);
3779 }
3780}
3781
3782static VALUE
3783int_even_p(VALUE num)
3784{
3785 if (FIXNUM_P(num)) {
3786 return RBOOL((num & 2) == 0);
3787 }
3788 else {
3789 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3790 return rb_big_even_p(num);
3791 }
3792}
3793
3794VALUE
3795rb_int_even_p(VALUE num)
3796{
3797 return int_even_p(num);
3798}
3799
3800/*
3801 * call-seq:
3802 * allbits?(mask) -> true or false
3803 *
3804 * Returns +true+ if all bits that are set (=1) in +mask+
3805 * are also set in +self+; returns +false+ otherwise.
3806 *
3807 * Example values:
3808 *
3809 * 0b1010101 self
3810 * 0b1010100 mask
3811 * 0b1010100 self & mask
3812 * true self.allbits?(mask)
3813 *
3814 * 0b1010100 self
3815 * 0b1010101 mask
3816 * 0b1010100 self & mask
3817 * false self.allbits?(mask)
3818 *
3819 * Related: Integer#anybits?, Integer#nobits?.
3820 *
3821 */
3822
3823static VALUE
3824int_allbits_p(VALUE num, VALUE mask)
3825{
3826 mask = rb_to_int(mask);
3827 return rb_int_equal(rb_int_and(num, mask), mask);
3828}
3829
3830/*
3831 * call-seq:
3832 * anybits?(mask) -> true or false
3833 *
3834 * Returns +true+ if any bit that is set (=1) in +mask+
3835 * is also set in +self+; returns +false+ otherwise.
3836 *
3837 * Example values:
3838 *
3839 * 0b10000010 self
3840 * 0b11111111 mask
3841 * 0b10000010 self & mask
3842 * true self.anybits?(mask)
3843 *
3844 * 0b00000000 self
3845 * 0b11111111 mask
3846 * 0b00000000 self & mask
3847 * false self.anybits?(mask)
3848 *
3849 * Related: Integer#allbits?, Integer#nobits?.
3850 *
3851 */
3852
3853static VALUE
3854int_anybits_p(VALUE num, VALUE mask)
3855{
3856 mask = rb_to_int(mask);
3857 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3858}
3859
3860/*
3861 * call-seq:
3862 * nobits?(mask) -> true or false
3863 *
3864 * Returns +true+ if no bit that is set (=1) in +mask+
3865 * is also set in +self+; returns +false+ otherwise.
3866 *
3867 * Example values:
3868 *
3869 * 0b11110000 self
3870 * 0b00001111 mask
3871 * 0b00000000 self & mask
3872 * true self.nobits?(mask)
3873 *
3874 * 0b00000001 self
3875 * 0b11111111 mask
3876 * 0b00000001 self & mask
3877 * false self.nobits?(mask)
3878 *
3879 * Related: Integer#allbits?, Integer#anybits?.
3880 *
3881 */
3882
3883static VALUE
3884int_nobits_p(VALUE num, VALUE mask)
3885{
3886 mask = rb_to_int(mask);
3887 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3888}
3889
3890/*
3891 * call-seq:
3892 * succ -> next_integer
3893 *
3894 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3895 *
3896 * 1.succ #=> 2
3897 * -1.succ #=> 0
3898 *
3899 * Related: Integer#pred (predecessor value).
3900 */
3901
3902VALUE
3903rb_int_succ(VALUE num)
3904{
3905 if (FIXNUM_P(num)) {
3906 long i = FIX2LONG(num) + 1;
3907 return LONG2NUM(i);
3908 }
3909 if (RB_BIGNUM_TYPE_P(num)) {
3910 return rb_big_plus(num, INT2FIX(1));
3911 }
3912 return num_funcall1(num, '+', INT2FIX(1));
3913}
3914
3915#define int_succ rb_int_succ
3916
3917/*
3918 * call-seq:
3919 * pred -> next_integer
3920 *
3921 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3922 *
3923 * 1.pred #=> 0
3924 * -1.pred #=> -2
3925 *
3926 * Related: Integer#succ (successor value).
3927 *
3928 */
3929
3930static VALUE
3931rb_int_pred(VALUE num)
3932{
3933 if (FIXNUM_P(num)) {
3934 long i = FIX2LONG(num) - 1;
3935 return LONG2NUM(i);
3936 }
3937 if (RB_BIGNUM_TYPE_P(num)) {
3938 return rb_big_minus(num, INT2FIX(1));
3939 }
3940 return num_funcall1(num, '-', INT2FIX(1));
3941}
3942
3943#define int_pred rb_int_pred
3944
3945VALUE
3946rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3947{
3948 int n;
3949 VALUE str;
3950 switch (n = rb_enc_codelen(code, enc)) {
3951 case ONIGERR_INVALID_CODE_POINT_VALUE:
3952 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3953 break;
3954 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3955 case 0:
3956 rb_raise(rb_eRangeError, "%u out of char range", code);
3957 break;
3958 }
3959 str = rb_enc_str_new(0, n, enc);
3960 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3961 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3962 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3963 }
3964 return str;
3965}
3966
3967/* call-seq:
3968 * chr -> string
3969 * chr(encoding) -> string
3970 *
3971 * Returns a 1-character string containing the character
3972 * represented by the value of +self+, according to the given +encoding+.
3973 *
3974 * 65.chr # => "A"
3975 * 0.chr # => "\x00"
3976 * 255.chr # => "\xFF"
3977 * string = 255.chr(Encoding::UTF_8)
3978 * string.encoding # => Encoding::UTF_8
3979 *
3980 * Raises an exception if +self+ is negative.
3981 *
3982 * Related: Integer#ord.
3983 *
3984 */
3985
3986static VALUE
3987int_chr(int argc, VALUE *argv, VALUE num)
3988{
3989 char c;
3990 unsigned int i;
3991 rb_encoding *enc;
3992
3993 if (rb_num_to_uint(num, &i) == 0) {
3994 }
3995 else if (FIXNUM_P(num)) {
3996 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3997 }
3998 else {
3999 rb_raise(rb_eRangeError, "bignum out of char range");
4000 }
4001
4002 switch (argc) {
4003 case 0:
4004 if (0xff < i) {
4005 enc = rb_default_internal_encoding();
4006 if (!enc) {
4007 rb_raise(rb_eRangeError, "%u out of char range", i);
4008 }
4009 goto decode;
4010 }
4011 c = (char)i;
4012 if (i < 0x80) {
4013 return rb_usascii_str_new(&c, 1);
4014 }
4015 else {
4016 return rb_str_new(&c, 1);
4017 }
4018 case 1:
4019 break;
4020 default:
4021 rb_error_arity(argc, 0, 1);
4022 }
4023 enc = rb_to_encoding(argv[0]);
4024 if (!enc) enc = rb_ascii8bit_encoding();
4025 decode:
4026 return rb_enc_uint_chr(i, enc);
4027}
4028
4029/*
4030 * Fixnum
4031 */
4032
4033static VALUE
4034fix_uminus(VALUE num)
4035{
4036 return LONG2NUM(-FIX2LONG(num));
4037}
4038
4039VALUE
4040rb_int_uminus(VALUE num)
4041{
4042 if (FIXNUM_P(num)) {
4043 return fix_uminus(num);
4044 }
4045 else {
4046 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
4047 return rb_big_uminus(num);
4048 }
4049}
4050
4051/* ruby_decimal_digit_pairs is defined in bignum.c and declared in
4052 * internal/bignum.h. See there for the rationale of the 2-digit
4053 * lookup-table itoa optimisation; both rb_fix2str here and big2str_2bdigits
4054 * in bignum.c consume it. */
4055
4056VALUE
4057rb_fix2str(VALUE x, int base)
4058{
4059 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
4060 long val = FIX2LONG(x);
4061 unsigned long u;
4062 int neg = 0;
4063
4064 if (base < 2 || 36 < base) {
4065 rb_raise(rb_eArgError, "invalid radix %d", base);
4066 }
4067#if SIZEOF_LONG < SIZEOF_VOIDP
4068# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4069 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4070 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4071 rb_bug("Unnormalized Fixnum value %p", (void *)x);
4072 }
4073# else
4074 /* should do something like above code, but currently ruby does not know */
4075 /* such platforms */
4076# endif
4077#endif
4078 if (val == 0) {
4079 return rb_usascii_str_new2("0");
4080 }
4081 if (val < 0) {
4082 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
4083 neg = 1;
4084 }
4085 else {
4086 u = val;
4087 }
4088 if (base == 10) {
4089 /* Emit two digits per iteration from a precomputed table. The
4090 * compiler lowers `u % 100` and `u / 100` to a single multiply +
4091 * shift, so each iteration costs roughly one multiply, one shift,
4092 * and two stores. About 2x fewer iterations than the classic
4093 * per-digit loop for multi-digit inputs. */
4094 while (u >= 100) {
4095 unsigned long idx = (u % 100) * 2;
4096 u /= 100;
4097 b -= 2;
4098 b[0] = ruby_decimal_digit_pairs[idx];
4099 b[1] = ruby_decimal_digit_pairs[idx + 1];
4100 }
4101 if (u >= 10) {
4102 unsigned long idx = u * 2;
4103 b -= 2;
4104 b[0] = ruby_decimal_digit_pairs[idx];
4105 b[1] = ruby_decimal_digit_pairs[idx + 1];
4106 }
4107 else {
4108 *--b = (char)('0' + u);
4109 }
4110 }
4111 else {
4112 do {
4113 *--b = ruby_digitmap[(int)(u % base)];
4114 } while (u /= base);
4115 }
4116 if (neg) {
4117 *--b = '-';
4118 }
4119
4120 return rb_usascii_str_new(b, e - b);
4121}
4122
4123static VALUE rb_fix_to_s_static[10];
4124
4125VALUE
4126rb_fix_to_s(VALUE x)
4127{
4128 long i = FIX2LONG(x);
4129 if (i >= 0 && i < 10) {
4130 return rb_fix_to_s_static[i];
4131 }
4132 return rb_fix2str(x, 10);
4133}
4134
4135/*
4136 * call-seq:
4137 * to_s(base = 10) -> string
4138 *
4139 * Returns a string containing the place-value representation of +self+
4140 * in radix +base+ (in 2..36).
4141 *
4142 * 12345.to_s # => "12345"
4143 * 12345.to_s(2) # => "11000000111001"
4144 * 12345.to_s(8) # => "30071"
4145 * 12345.to_s(10) # => "12345"
4146 * 12345.to_s(16) # => "3039"
4147 * 12345.to_s(36) # => "9ix"
4148 * 78546939656932.to_s(36) # => "rubyrules"
4149 *
4150 * Raises an exception if +base+ is out of range.
4151 */
4152
4153VALUE
4154rb_int_to_s(int argc, VALUE *argv, VALUE x)
4155{
4156 int base;
4157
4158 if (rb_check_arity(argc, 0, 1))
4159 base = NUM2INT(argv[0]);
4160 else
4161 base = 10;
4162 return rb_int2str(x, base);
4163}
4164
4165VALUE
4166rb_int2str(VALUE x, int base)
4167{
4168 if (FIXNUM_P(x)) {
4169 return rb_fix2str(x, base);
4170 }
4171 else if (RB_BIGNUM_TYPE_P(x)) {
4172 return rb_big2str(x, base);
4173 }
4174
4175 return rb_any_to_s(x);
4176}
4177
4178static VALUE
4179fix_plus(VALUE x, VALUE y)
4180{
4181 if (FIXNUM_P(y)) {
4182 return rb_fix_plus_fix(x, y);
4183 }
4184 else if (RB_BIGNUM_TYPE_P(y)) {
4185 return rb_big_plus(y, x);
4186 }
4187 else if (RB_FLOAT_TYPE_P(y)) {
4188 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4189 }
4190 else if (RB_TYPE_P(y, T_COMPLEX)) {
4191 return rb_complex_plus(y, x);
4192 }
4193 else {
4194 return rb_num_coerce_bin(x, y, '+');
4195 }
4196}
4197
4198VALUE
4199rb_fix_plus(VALUE x, VALUE y)
4200{
4201 return fix_plus(x, y);
4202}
4203
4204/*
4205 * call-seq:
4206 * self + other -> numeric
4207 *
4208 * Returns the sum of +self+ and +other+:
4209 *
4210 * 1 + 1 # => 2
4211 * 1 + -1 # => 0
4212 * 1 + 0 # => 1
4213 * 1 + -2 # => -1
4214 * 1 + Complex(1, 0) # => (2+0i)
4215 * 1 + Rational(1, 1) # => (2/1)
4216 *
4217 * For a computation involving Floats, the result may be inexact (see Float#+):
4218 *
4219 * 1 + 3.14 # => 4.140000000000001
4220 */
4221
4222VALUE
4223rb_int_plus(VALUE x, VALUE y)
4224{
4225 if (FIXNUM_P(x)) {
4226 return fix_plus(x, y);
4227 }
4228 else if (RB_BIGNUM_TYPE_P(x)) {
4229 return rb_big_plus(x, y);
4230 }
4231 return rb_num_coerce_bin(x, y, '+');
4232}
4233
4234static VALUE
4235fix_minus(VALUE x, VALUE y)
4236{
4237 if (FIXNUM_P(y)) {
4238 return rb_fix_minus_fix(x, y);
4239 }
4240 else if (RB_BIGNUM_TYPE_P(y)) {
4241 x = rb_int2big(FIX2LONG(x));
4242 return rb_big_minus(x, y);
4243 }
4244 else if (RB_FLOAT_TYPE_P(y)) {
4245 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4246 }
4247 else {
4248 return rb_num_coerce_bin(x, y, '-');
4249 }
4250}
4251
4252/*
4253 * call-seq:
4254 * self - other -> numeric
4255 *
4256 * Returns the difference of +self+ and +other+:
4257 *
4258 * 4 - 2 # => 2
4259 * -4 - 2 # => -6
4260 * -4 - -2 # => -2
4261 * 4 - 2.0 # => 2.0
4262 * 4 - Rational(2, 1) # => (2/1)
4263 * 4 - Complex(2, 0) # => (2+0i)
4264 *
4265 */
4266
4267VALUE
4268rb_int_minus(VALUE x, VALUE y)
4269{
4270 if (FIXNUM_P(x)) {
4271 return fix_minus(x, y);
4272 }
4273 else if (RB_BIGNUM_TYPE_P(x)) {
4274 return rb_big_minus(x, y);
4275 }
4276 return rb_num_coerce_bin(x, y, '-');
4277}
4278
4279
4280#define SQRT_LONG_MAX HALF_LONG_MSB
4281/*tests if N*N would overflow*/
4282#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4283
4284static VALUE
4285fix_mul(VALUE x, VALUE y)
4286{
4287 if (FIXNUM_P(y)) {
4288 return rb_fix_mul_fix(x, y);
4289 }
4290 else if (RB_BIGNUM_TYPE_P(y)) {
4291 switch (x) {
4292 case INT2FIX(0): return x;
4293 case INT2FIX(1): return y;
4294 }
4295 return rb_big_mul(y, x);
4296 }
4297 else if (RB_FLOAT_TYPE_P(y)) {
4298 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4299 }
4300 else if (RB_TYPE_P(y, T_COMPLEX)) {
4301 return rb_complex_mul(y, x);
4302 }
4303 else {
4304 return rb_num_coerce_bin(x, y, '*');
4305 }
4306}
4307
4308/*
4309 * call-seq:
4310 * self * other -> numeric
4311 *
4312 * Returns the numeric product of +self+ and +other+:
4313 *
4314 * 4 * 2 # => 8
4315 * -4 * 2 # => -8
4316 * 4 * -2 # => -8
4317 * 4 * 2.0 # => 8.0
4318 * 4 * Rational(1, 3) # => (4/3)
4319 * 4 * Complex(2, 0) # => (8+0i)
4320 *
4321 */
4322
4323VALUE
4324rb_int_mul(VALUE x, VALUE y)
4325{
4326 if (FIXNUM_P(x)) {
4327 return fix_mul(x, y);
4328 }
4329 else if (RB_BIGNUM_TYPE_P(x)) {
4330 return rb_big_mul(x, y);
4331 }
4332 return rb_num_coerce_bin(x, y, '*');
4333}
4334
4335static bool
4336accurate_in_double(long i)
4337{
4338#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4339 return ((i < 0 ? -i : i) < (1L << DBL_MANT_DIG));
4340#else
4341 return true;
4342#endif
4343}
4344
4345static double
4346fix_fdiv_double(VALUE x, VALUE y)
4347{
4348 if (FIXNUM_P(y)) {
4349 long iy = FIX2LONG(y);
4350 if (!accurate_in_double(iy)) {
4351 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4352 }
4353 return double_div_double(FIX2LONG(x), iy);
4354 }
4355 else if (RB_BIGNUM_TYPE_P(y)) {
4356 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4357 }
4358 else if (RB_FLOAT_TYPE_P(y)) {
4359 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4360 }
4361 else {
4362 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4363 }
4364}
4365
4366static bool
4367int_accurate_in_double(VALUE n)
4368{
4369 if (FIXNUM_P(n)) {
4370 return accurate_in_double(FIX2LONG(n));
4371 }
4373#if SIZEOF_LONG * CHAR_BIT <= DBL_MANT_DIG
4374 int nlz;
4375 size_t size = rb_absint_size(n, &nlz);
4376 const size_t mant_size = roomof(DBL_MANT_DIG, CHAR_BIT);
4377 if (size < mant_size) return true;
4378 if (size > mant_size) return false;
4379 if ((size_t)nlz >= (CHAR_BIT * mant_size - DBL_MANT_DIG)) return true;
4380#endif
4381 return false;
4382}
4383
4384double
4385rb_int_fdiv_double(VALUE x, VALUE y)
4386{
4387 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y) &&
4388 !(int_accurate_in_double(x) && int_accurate_in_double(y))) {
4389 VALUE gcd = rb_gcd(x, y);
4390 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4391 x = rb_int_idiv(x, gcd);
4392 y = rb_int_idiv(y, gcd);
4393 }
4394 }
4395 if (FIXNUM_P(x)) {
4396 return fix_fdiv_double(x, y);
4397 }
4398 else if (RB_BIGNUM_TYPE_P(x)) {
4399 return rb_big_fdiv_double(x, y);
4400 }
4401 else {
4402 return nan("");
4403 }
4404}
4405
4406/*
4407 * call-seq:
4408 * fdiv(numeric) -> float
4409 *
4410 * Returns the Float result of dividing +self+ by +numeric+:
4411 *
4412 * 4.fdiv(2) # => 2.0
4413 * 4.fdiv(-2) # => -2.0
4414 * -4.fdiv(2) # => -2.0
4415 * 4.fdiv(2.0) # => 2.0
4416 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4417 *
4418 * Raises an exception if +numeric+ cannot be converted to a Float.
4419 *
4420 */
4421
4422VALUE
4423rb_int_fdiv(VALUE x, VALUE y)
4424{
4425 if (RB_INTEGER_TYPE_P(x)) {
4426 return DBL2NUM(rb_int_fdiv_double(x, y));
4427 }
4428 return Qnil;
4429}
4430
4431static VALUE
4432fix_divide(VALUE x, VALUE y, ID op)
4433{
4434 if (FIXNUM_P(y)) {
4435 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4436 return rb_fix_div_fix(x, y);
4437 }
4438 else if (RB_BIGNUM_TYPE_P(y)) {
4439 x = rb_int2big(FIX2LONG(x));
4440 return rb_big_div(x, y);
4441 }
4442 else if (RB_FLOAT_TYPE_P(y)) {
4443 if (op == '/') {
4444 double d = FIX2LONG(x);
4445 return rb_flo_div_flo(DBL2NUM(d), y);
4446 }
4447 else {
4448 VALUE v;
4449 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4450 v = fix_divide(x, y, '/');
4451 return flo_floor(0, 0, v);
4452 }
4453 }
4454 else {
4455 if (RB_TYPE_P(y, T_RATIONAL) &&
4456 op == '/' && FIX2LONG(x) == 1)
4457 return rb_rational_reciprocal(y);
4458 return rb_num_coerce_bin(x, y, op);
4459 }
4460}
4461
4462static VALUE
4463fix_div(VALUE x, VALUE y)
4464{
4465 return fix_divide(x, y, '/');
4466}
4467
4468/*
4469 * call-seq:
4470 * self / other -> numeric
4471 *
4472 * Returns the quotient of +self+ and +other+.
4473 *
4474 * For integer +other+, returns the largest integer less than or equal to
4475 * the mathematical quotient:
4476 *
4477 * 4 / 3 # => 1
4478 * 4 / -3 # => -2
4479 * -4 / 3 # => -2
4480 * -4 / -3 # => 1
4481 *
4482 * For non-integer +other+, returns a non-integer result:
4483 *
4484 * 4 / 3.0 # => 1.3333333333333333
4485 * 4 / Rational(3, 1) # => (4/3)
4486 * 4 / Complex(3, 0) # => ((4/3)+0i)
4487 *
4488 */
4489
4490VALUE
4491rb_int_div(VALUE x, VALUE y)
4492{
4493 if (FIXNUM_P(x)) {
4494 return fix_div(x, y);
4495 }
4496 else if (RB_BIGNUM_TYPE_P(x)) {
4497 return rb_big_div(x, y);
4498 }
4499 return Qnil;
4500}
4501
4502static VALUE
4503fix_idiv(VALUE x, VALUE y)
4504{
4505 return fix_divide(x, y, id_div);
4506}
4507
4508/*
4509 * call-seq:
4510 * div(numeric) -> integer
4511 *
4512 * Performs integer division; returns the integer result of dividing +self+
4513 * by +numeric+:
4514 *
4515 * 4.div(3) # => 1
4516 * 4.div(-3) # => -2
4517 * -4.div(3) # => -2
4518 * -4.div(-3) # => 1
4519 * 4.div(3.0) # => 1
4520 * 4.div(Rational(3, 1)) # => 1
4521 *
4522 * Raises an exception if +numeric+ does not have method +div+.
4523 *
4524 */
4525
4526VALUE
4527rb_int_idiv(VALUE x, VALUE y)
4528{
4529 if (FIXNUM_P(x)) {
4530 return fix_idiv(x, y);
4531 }
4532 else if (RB_BIGNUM_TYPE_P(x)) {
4533 return rb_big_idiv(x, y);
4534 }
4535 return num_div(x, y);
4536}
4537
4538static VALUE
4539fix_mod(VALUE x, VALUE y)
4540{
4541 if (FIXNUM_P(y)) {
4542 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4543 return rb_fix_mod_fix(x, y);
4544 }
4545 else if (RB_BIGNUM_TYPE_P(y)) {
4546 x = rb_int2big(FIX2LONG(x));
4547 return rb_big_modulo(x, y);
4548 }
4549 else if (RB_FLOAT_TYPE_P(y)) {
4550 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4551 }
4552 else {
4553 return rb_num_coerce_bin(x, y, '%');
4554 }
4555}
4556
4557/*
4558 * call-seq:
4559 * self % other -> real_numeric
4560 *
4561 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
4562 *
4563 * For integer +n+ and real number +r+, these expressions are equivalent:
4564 *
4565 * n % r
4566 * n-r*(n/r).floor
4567 * n.divmod(r)[1]
4568 *
4569 * See Numeric#divmod.
4570 *
4571 * Examples:
4572 *
4573 * 10 % 2 # => 0
4574 * 10 % 3 # => 1
4575 * 10 % 4 # => 2
4576 *
4577 * 10 % -2 # => 0
4578 * 10 % -3 # => -2
4579 * 10 % -4 # => -2
4580 *
4581 * 10 % 3.0 # => 1.0
4582 * 10 % Rational(3, 1) # => (1/1)
4583 *
4584 */
4585VALUE
4586rb_int_modulo(VALUE x, VALUE y)
4587{
4588 if (FIXNUM_P(x)) {
4589 return fix_mod(x, y);
4590 }
4591 else if (RB_BIGNUM_TYPE_P(x)) {
4592 return rb_big_modulo(x, y);
4593 }
4594 return num_modulo(x, y);
4595}
4596
4597/*
4598 * call-seq:
4599 * remainder(other) -> real_number
4600 *
4601 * Returns the remainder after dividing +self+ by +other+.
4602 *
4603 * Examples:
4604 *
4605 * 11.remainder(4) # => 3
4606 * 11.remainder(-4) # => 3
4607 * -11.remainder(4) # => -3
4608 * -11.remainder(-4) # => -3
4609 *
4610 * 12.remainder(4) # => 0
4611 * 12.remainder(-4) # => 0
4612 * -12.remainder(4) # => 0
4613 * -12.remainder(-4) # => 0
4614 *
4615 * 13.remainder(4.0) # => 1.0
4616 * 13.remainder(Rational(4, 1)) # => (1/1)
4617 *
4618 */
4619
4620static VALUE
4621int_remainder(VALUE x, VALUE y)
4622{
4623 if (FIXNUM_P(x)) {
4624 if (FIXNUM_P(y)) {
4625 VALUE z = fix_mod(x, y);
4627 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4628 z = fix_minus(z, y);
4629 return z;
4630 }
4631 else if (!RB_BIGNUM_TYPE_P(y)) {
4632 return num_remainder(x, y);
4633 }
4634 x = rb_int2big(FIX2LONG(x));
4635 }
4636 else if (!RB_BIGNUM_TYPE_P(x)) {
4637 return Qnil;
4638 }
4639 return rb_big_remainder(x, y);
4640}
4641
4642static VALUE
4643fix_divmod(VALUE x, VALUE y)
4644{
4645 if (FIXNUM_P(y)) {
4646 VALUE div, mod;
4647 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4648 rb_fix_divmod_fix(x, y, &div, &mod);
4649 return rb_assoc_new(div, mod);
4650 }
4651 else if (RB_BIGNUM_TYPE_P(y)) {
4652 x = rb_int2big(FIX2LONG(x));
4653 return rb_big_divmod(x, y);
4654 }
4655 else if (RB_FLOAT_TYPE_P(y)) {
4656 {
4657 double div, mod;
4658 volatile VALUE a, b;
4659
4660 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4661 a = dbl2ival(div);
4662 b = DBL2NUM(mod);
4663 return rb_assoc_new(a, b);
4664 }
4665 }
4666 else {
4667 return rb_num_coerce_bin(x, y, id_divmod);
4668 }
4669}
4670
4671/*
4672 * call-seq:
4673 * divmod(other) -> array
4674 *
4675 * Returns a 2-element array <tt>[q, r]</tt>, where
4676 *
4677 * q = (self/other).floor # Quotient
4678 * r = self % other # Remainder
4679 *
4680 * Examples:
4681 *
4682 * 11.divmod(4) # => [2, 3]
4683 * 11.divmod(-4) # => [-3, -1]
4684 * -11.divmod(4) # => [-3, 1]
4685 * -11.divmod(-4) # => [2, -3]
4686 *
4687 * 12.divmod(4) # => [3, 0]
4688 * 12.divmod(-4) # => [-3, 0]
4689 * -12.divmod(4) # => [-3, 0]
4690 * -12.divmod(-4) # => [3, 0]
4691 *
4692 * 13.divmod(4.0) # => [3, 1.0]
4693 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4694 *
4695 */
4696VALUE
4697rb_int_divmod(VALUE x, VALUE y)
4698{
4699 if (FIXNUM_P(x)) {
4700 return fix_divmod(x, y);
4701 }
4702 else if (RB_BIGNUM_TYPE_P(x)) {
4703 return rb_big_divmod(x, y);
4704 }
4705 return Qnil;
4706}
4707
4708/*
4709 * call-seq:
4710 * self ** exponent -> numeric
4711 *
4712 * Returns +self+ raised to the power +exponent+:
4713 *
4714 * 2 ** 3 # => 8
4715 * 2 ** -3 # => (1/8)
4716 * -2 ** 3 # => -8
4717 * -2 ** -3 # => (-1/8)
4718 * 2 ** 3.3 # => 9.849155306759329
4719 * 2 ** Rational(3, 1) # => (8/1)
4720 * 2 ** Complex(3, 0) # => (8+0i)
4721 *
4722 */
4723
4724static VALUE
4725int_pow(long x, unsigned long y)
4726{
4727 int neg = x < 0;
4728 long z = 1;
4729
4730 if (y == 0) return INT2FIX(1);
4731 if (y == 1) return LONG2NUM(x);
4732 if (neg) x = -x;
4733 if (y & 1)
4734 z = x;
4735 else
4736 neg = 0;
4737 y &= ~1;
4738 do {
4739 while (y % 2 == 0) {
4740 if (!FIT_SQRT_LONG(x)) {
4741 goto bignum;
4742 }
4743 x = x * x;
4744 y >>= 1;
4745 }
4746 {
4747 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4748 goto bignum;
4749 }
4750 z = x * z;
4751 }
4752 } while (--y);
4753 if (neg) z = -z;
4754 return LONG2NUM(z);
4755
4756 VALUE v;
4757 bignum:
4758 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4759 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4760 return v;
4761 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4762 return v;
4763}
4764
4765VALUE
4766rb_int_positive_pow(long x, unsigned long y)
4767{
4768 return int_pow(x, y);
4769}
4770
4771static VALUE
4772fix_pow_inverted(VALUE x, VALUE minusb)
4773{
4774 if (x == INT2FIX(0)) {
4777 }
4778 else {
4779 VALUE y = rb_int_pow(x, minusb);
4780
4781 if (RB_FLOAT_TYPE_P(y)) {
4782 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4783 return DBL2NUM(1.0 / d);
4784 }
4785 else {
4786 return rb_rational_raw(INT2FIX(1), y);
4787 }
4788 }
4789}
4790
4791static VALUE
4792fix_pow(VALUE x, VALUE y)
4793{
4794 long a = FIX2LONG(x);
4795
4796 if (FIXNUM_P(y)) {
4797 long b = FIX2LONG(y);
4798
4799 if (a == 1) return INT2FIX(1);
4800 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4801 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4802 if (b == 0) return INT2FIX(1);
4803 if (b == 1) return x;
4804 if (a == 0) return INT2FIX(0);
4805 return int_pow(a, b);
4806 }
4807 else if (RB_BIGNUM_TYPE_P(y)) {
4808 if (a == 1) return INT2FIX(1);
4809 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4810 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4811 if (a == 0) return INT2FIX(0);
4812 x = rb_int2big(FIX2LONG(x));
4813 return rb_big_pow(x, y);
4814 }
4815 else if (RB_FLOAT_TYPE_P(y)) {
4816 double dy = RFLOAT_VALUE(y);
4817 if (dy == 0.0) return DBL2NUM(1.0);
4818 if (a == 0) {
4819 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4820 }
4821 if (a == 1) return DBL2NUM(1.0);
4822 if (a < 0 && dy != round(dy))
4823 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4824 return DBL2NUM(pow((double)a, dy));
4825 }
4826 else {
4827 return rb_num_coerce_bin(x, y, idPow);
4828 }
4829}
4830
4831/*
4832 * call-seq:
4833 * self ** exponent -> numeric
4834 *
4835 * Returns +self+ raised to the power +exponent+:
4836 *
4837 * # Result for non-negative Integer exponent is Integer.
4838 * 2 ** 0 # => 1
4839 * 2 ** 1 # => 2
4840 * 2 ** 2 # => 4
4841 * 2 ** 3 # => 8
4842 * -2 ** 3 # => -8
4843 * # Result for negative Integer exponent is Rational, not Float.
4844 * 2 ** -3 # => (1/8)
4845 * -2 ** -3 # => (-1/8)
4846 *
4847 * # Result for Float exponent is Float.
4848 * 2 ** 0.0 # => 1.0
4849 * 2 ** 1.0 # => 2.0
4850 * 2 ** 2.0 # => 4.0
4851 * 2 ** 3.0 # => 8.0
4852 * -2 ** 3.0 # => -8.0
4853 * 2 ** -3.0 # => 0.125
4854 * -2 ** -3.0 # => -0.125
4855 *
4856 * # Result for non-negative Complex exponent is Complex with Integer parts.
4857 * 2 ** Complex(0, 0) # => (1+0i)
4858 * 2 ** Complex(1, 0) # => (2+0i)
4859 * 2 ** Complex(2, 0) # => (4+0i)
4860 * 2 ** Complex(3, 0) # => (8+0i)
4861 * -2 ** Complex(3, 0) # => (-8+0i)
4862 * # Result for negative Complex exponent is Complex with Rational parts.
4863 * 2 ** Complex(-3, 0) # => ((1/8)+(0/1)*i)
4864 * -2 ** Complex(-3, 0) # => ((-1/8)+(0/1)*i)
4865 *
4866 * # Result for Rational exponent is Rational.
4867 * 2 ** Rational(0, 1) # => (1/1)
4868 * 2 ** Rational(1, 1) # => (2/1)
4869 * 2 ** Rational(2, 1) # => (4/1)
4870 * 2 ** Rational(3, 1) # => (8/1)
4871 * -2 ** Rational(3, 1) # => (-8/1)
4872 * 2 ** Rational(-3, 1) # => (1/8)
4873 * -2 ** Rational(-3, 1) # => (-1/8)
4874 *
4875 */
4876VALUE
4877rb_int_pow(VALUE x, VALUE y)
4878{
4879 if (FIXNUM_P(x)) {
4880 return fix_pow(x, y);
4881 }
4882 else if (RB_BIGNUM_TYPE_P(x)) {
4883 return rb_big_pow(x, y);
4884 }
4885 return Qnil;
4886}
4887
4888VALUE
4889rb_num_pow(VALUE x, VALUE y)
4890{
4891 VALUE z = rb_int_pow(x, y);
4892 if (!NIL_P(z)) return z;
4893 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4894 if (SPECIAL_CONST_P(x)) return Qnil;
4895 switch (BUILTIN_TYPE(x)) {
4896 case T_COMPLEX:
4897 return rb_complex_pow(x, y);
4898 case T_RATIONAL:
4899 return rb_rational_pow(x, y);
4900 default:
4901 break;
4902 }
4903 return Qnil;
4904}
4905
4906static VALUE
4907fix_equal(VALUE x, VALUE y)
4908{
4909 if (x == y) return Qtrue;
4910 if (FIXNUM_P(y)) return Qfalse;
4911 else if (RB_BIGNUM_TYPE_P(y)) {
4912 return rb_big_eq(y, x);
4913 }
4914 else if (RB_FLOAT_TYPE_P(y)) {
4915 return rb_integer_float_eq(x, y);
4916 }
4917 else {
4918 return num_equal(x, y);
4919 }
4920}
4921
4922/*
4923 * call-seq:
4924 * self == other -> true or false
4925 *
4926 * Returns whether +self+ is numerically equal to +other+:
4927 *
4928 * 1 == 2 #=> false
4929 * 1 == 1.0 #=> true
4930 *
4931 * Related: Integer#eql? (requires +other+ to be an \Integer).
4932 */
4933
4934VALUE
4935rb_int_equal(VALUE x, VALUE y)
4936{
4937 if (FIXNUM_P(x)) {
4938 return fix_equal(x, y);
4939 }
4940 else if (RB_BIGNUM_TYPE_P(x)) {
4941 return rb_big_eq(x, y);
4942 }
4943 return Qnil;
4944}
4945
4946static VALUE
4947fix_cmp(VALUE x, VALUE y)
4948{
4949 if (x == y) return INT2FIX(0);
4950 if (FIXNUM_P(y)) {
4951 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4952 return INT2FIX(-1);
4953 }
4954 else if (RB_BIGNUM_TYPE_P(y)) {
4955 VALUE cmp = rb_big_cmp(y, x);
4956 switch (cmp) {
4957 case INT2FIX(+1): return INT2FIX(-1);
4958 case INT2FIX(-1): return INT2FIX(+1);
4959 }
4960 return cmp;
4961 }
4962 else if (RB_FLOAT_TYPE_P(y)) {
4963 return rb_integer_float_cmp(x, y);
4964 }
4965 else {
4966 return rb_num_coerce_cmp(x, y, id_cmp);
4967 }
4968}
4969
4970/*
4971 * call-seq:
4972 * self <=> other -> -1, 0, 1, or nil
4973 *
4974 * Compares +self+ and +other+.
4975 *
4976 * Returns:
4977 *
4978 * - +-1+, if +self+ is less than +other+.
4979 * - +0+, if +self+ is equal to +other+.
4980 * - +1+, if +self+ is greater then +other+.
4981 * - +nil+, if +self+ and +other+ are incomparable.
4982 *
4983 * Examples:
4984 *
4985 * 1 <=> 2 # => -1
4986 * 1 <=> 1 # => 0
4987 * 1 <=> 1.0 # => 0
4988 * 1 <=> Rational(1, 1) # => 0
4989 * 1 <=> Complex(1, 0) # => 0
4990 * 1 <=> 0 # => 1
4991 * 1 <=> 'foo' # => nil
4992 *
4993 * \Class \Integer includes module Comparable,
4994 * each of whose methods uses Integer#<=> for comparison.
4995 */
4996
4997VALUE
4998rb_int_cmp(VALUE x, VALUE y)
4999{
5000 if (FIXNUM_P(x)) {
5001 return fix_cmp(x, y);
5002 }
5003 else if (RB_BIGNUM_TYPE_P(x)) {
5004 return rb_big_cmp(x, y);
5005 }
5006 else {
5007 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
5008 }
5009}
5010
5011static VALUE
5012fix_gt(VALUE x, VALUE y)
5013{
5014 if (FIXNUM_P(y)) {
5015 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
5016 }
5017 else if (RB_BIGNUM_TYPE_P(y)) {
5018 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
5019 }
5020 else if (RB_FLOAT_TYPE_P(y)) {
5021 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
5022 }
5023 else {
5024 return rb_num_coerce_relop(x, y, '>');
5025 }
5026}
5027
5028/*
5029 * call-seq:
5030 * self > other -> true or false
5031 *
5032 * Returns whether the value of +self+ is greater than the value of +other+;
5033 * +other+ must be numeric, but may not be Complex:
5034 *
5035 * 1 > 0 # => true
5036 * 1 > 1 # => false
5037 * 1 > 2 # => false
5038 * 1 > 0.5 # => true
5039 * 1 > Rational(1, 2) # => true
5040 *
5041 * Raises an exception if the comparison cannot be made.
5042 *
5043 */
5044
5045VALUE
5046rb_int_gt(VALUE x, VALUE y)
5047{
5048 if (FIXNUM_P(x)) {
5049 return fix_gt(x, y);
5050 }
5051 else if (RB_BIGNUM_TYPE_P(x)) {
5052 return rb_big_gt(x, y);
5053 }
5054 return Qnil;
5055}
5056
5057static VALUE
5058fix_ge(VALUE x, VALUE y)
5059{
5060 if (FIXNUM_P(y)) {
5061 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
5062 }
5063 else if (RB_BIGNUM_TYPE_P(y)) {
5064 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
5065 }
5066 else if (RB_FLOAT_TYPE_P(y)) {
5067 VALUE rel = rb_integer_float_cmp(x, y);
5068 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
5069 }
5070 else {
5071 return rb_num_coerce_relop(x, y, idGE);
5072 }
5073}
5074
5075/*
5076 * call-seq:
5077 * self >= other -> true or false
5078 *
5079 * Returns whether the value of +self+ is greater than or equal to the value of +other+;
5080 * +other+ must be numeric, but may not be Complex:
5081 *
5082 * 1 >= 0 # => true
5083 * 1 >= 1 # => true
5084 * 1 >= 2 # => false
5085 * 1 >= 0.5 # => true
5086 * 1 >= Rational(1, 2) # => true
5087 *
5088 * Raises an exception if the comparison cannot be made.
5089 *
5090 */
5091
5092VALUE
5093rb_int_ge(VALUE x, VALUE y)
5094{
5095 if (FIXNUM_P(x)) {
5096 return fix_ge(x, y);
5097 }
5098 else if (RB_BIGNUM_TYPE_P(x)) {
5099 return rb_big_ge(x, y);
5100 }
5101 return Qnil;
5102}
5103
5104static VALUE
5105fix_lt(VALUE x, VALUE y)
5106{
5107 if (FIXNUM_P(y)) {
5108 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
5109 }
5110 else if (RB_BIGNUM_TYPE_P(y)) {
5111 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
5112 }
5113 else if (RB_FLOAT_TYPE_P(y)) {
5114 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
5115 }
5116 else {
5117 return rb_num_coerce_relop(x, y, '<');
5118 }
5119}
5120
5121/*
5122 * call-seq:
5123 * self < other -> true or false
5124 *
5125 * Returns whether the value of +self+ is less than the value of +other+;
5126 * +other+ must be numeric, but may not be Complex:
5127 *
5128 * 1 < 0 # => false
5129 * 1 < 1 # => false
5130 * 1 < 2 # => true
5131 * 1 < 0.5 # => false
5132 * 1 < Rational(1, 2) # => false
5133 *
5134 */
5135
5136static VALUE
5137int_lt(VALUE x, VALUE y)
5138{
5139 if (FIXNUM_P(x)) {
5140 return fix_lt(x, y);
5141 }
5142 else if (RB_BIGNUM_TYPE_P(x)) {
5143 return rb_big_lt(x, y);
5144 }
5145 return Qnil;
5146}
5147
5148static VALUE
5149fix_le(VALUE x, VALUE y)
5150{
5151 if (FIXNUM_P(y)) {
5152 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
5153 }
5154 else if (RB_BIGNUM_TYPE_P(y)) {
5155 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
5156 }
5157 else if (RB_FLOAT_TYPE_P(y)) {
5158 VALUE rel = rb_integer_float_cmp(x, y);
5159 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
5160 }
5161 else {
5162 return rb_num_coerce_relop(x, y, idLE);
5163 }
5164}
5165
5166/*
5167 * call-seq:
5168 * self <= other -> true or false
5169 *
5170 * Returns whether the value of +self+ is less than or equal to the value of +other+;
5171 * +other+ must be numeric, but may not be Complex:
5172 *
5173 * 1 <= 0 # => false
5174 * 1 <= 1 # => true
5175 * 1 <= 2 # => true
5176 * 1 <= 0.5 # => false
5177 * 1 <= Rational(1, 2) # => false
5178 *
5179 * Raises an exception if the comparison cannot be made.
5180 *
5181 */
5182
5183static VALUE
5184int_le(VALUE x, VALUE y)
5185{
5186 if (FIXNUM_P(x)) {
5187 return fix_le(x, y);
5188 }
5189 else if (RB_BIGNUM_TYPE_P(x)) {
5190 return rb_big_le(x, y);
5191 }
5192 return Qnil;
5193}
5194
5195static VALUE
5196fix_comp(VALUE num)
5197{
5198 return ~num | FIXNUM_FLAG;
5199}
5200
5201VALUE
5202rb_int_comp(VALUE num)
5203{
5204 if (FIXNUM_P(num)) {
5205 return fix_comp(num);
5206 }
5207 else if (RB_BIGNUM_TYPE_P(num)) {
5208 return rb_big_comp(num);
5209 }
5210 return Qnil;
5211}
5212
5213static VALUE
5214num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
5215{
5216 ID func = (ID)((VALUE *)arg)[0];
5217 VALUE x = ((VALUE *)arg)[1];
5218 if (recursive) {
5219 num_funcall_op_1_recursion(x, func, y);
5220 }
5221 return rb_check_funcall(x, func, 1, &y);
5222}
5223
5224VALUE
5226{
5227 VALUE ret, args[3];
5228
5229 args[0] = (VALUE)func;
5230 args[1] = x;
5231 args[2] = y;
5232 do_coerce(&args[1], &args[2], TRUE);
5233 ret = rb_exec_recursive_paired(num_funcall_bit_1,
5234 args[2], args[1], (VALUE)args);
5235 if (UNDEF_P(ret)) {
5236 /* show the original object, not coerced object */
5237 coerce_failed(x, y);
5238 }
5239 return ret;
5240}
5241
5242static VALUE
5243fix_and(VALUE x, VALUE y)
5244{
5245 if (FIXNUM_P(y)) {
5246 long val = FIX2LONG(x) & FIX2LONG(y);
5247 return LONG2NUM(val);
5248 }
5249
5250 if (RB_BIGNUM_TYPE_P(y)) {
5251 return rb_big_and(y, x);
5252 }
5253
5254 return rb_num_coerce_bit(x, y, '&');
5255}
5256
5257/*
5258 * call-seq:
5259 * self & other -> integer
5260 *
5261 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5262 * in +self+ and +other+ are 1, 0 otherwise:
5263 *
5264 * "%04b" % (0b0101 & 0b0110) # => "0100"
5265 *
5266 * Raises an exception if +other+ is not an \Integer.
5267 *
5268 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5269 *
5270 */
5271
5272VALUE
5273rb_int_and(VALUE x, VALUE y)
5274{
5275 if (FIXNUM_P(x)) {
5276 return fix_and(x, y);
5277 }
5278 else if (RB_BIGNUM_TYPE_P(x)) {
5279 return rb_big_and(x, y);
5280 }
5281 return Qnil;
5282}
5283
5284static VALUE
5285fix_or(VALUE x, VALUE y)
5286{
5287 if (FIXNUM_P(y)) {
5288 long val = FIX2LONG(x) | FIX2LONG(y);
5289 return LONG2NUM(val);
5290 }
5291
5292 if (RB_BIGNUM_TYPE_P(y)) {
5293 return rb_big_or(y, x);
5294 }
5295
5296 return rb_num_coerce_bit(x, y, '|');
5297}
5298
5299/*
5300 * call-seq:
5301 * self | other -> integer
5302 *
5303 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5304 * in +self+ or +other+ is 1, 0 otherwise:
5305 *
5306 * "%04b" % (0b0101 | 0b0110) # => "0111"
5307 *
5308 * Raises an exception if +other+ is not an \Integer.
5309 *
5310 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5311 *
5312 */
5313
5314static VALUE
5315int_or(VALUE x, VALUE y)
5316{
5317 if (FIXNUM_P(x)) {
5318 return fix_or(x, y);
5319 }
5320 else if (RB_BIGNUM_TYPE_P(x)) {
5321 return rb_big_or(x, y);
5322 }
5323 return Qnil;
5324}
5325
5326static VALUE
5327fix_xor(VALUE x, VALUE y)
5328{
5329 if (FIXNUM_P(y)) {
5330 long val = FIX2LONG(x) ^ FIX2LONG(y);
5331 return LONG2NUM(val);
5332 }
5333
5334 if (RB_BIGNUM_TYPE_P(y)) {
5335 return rb_big_xor(y, x);
5336 }
5337
5338 return rb_num_coerce_bit(x, y, '^');
5339}
5340
5341/*
5342 * call-seq:
5343 * self ^ other -> integer
5344 *
5345 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5346 * in +self+ and +other+ are different, 0 otherwise:
5347 *
5348 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5349 *
5350 * Raises an exception if +other+ is not an \Integer.
5351 *
5352 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5353 *
5354 */
5355
5356VALUE
5357rb_int_xor(VALUE x, VALUE y)
5358{
5359 if (FIXNUM_P(x)) {
5360 return fix_xor(x, y);
5361 }
5362 else if (RB_BIGNUM_TYPE_P(x)) {
5363 return rb_big_xor(x, y);
5364 }
5365 return Qnil;
5366}
5367
5368static VALUE
5369rb_fix_lshift(VALUE x, VALUE y)
5370{
5371 long val, width;
5372
5373 val = NUM2LONG(x);
5374 if (!val) return (rb_to_int(y), INT2FIX(0));
5375 if (!FIXNUM_P(y))
5376 return rb_big_lshift(rb_int2big(val), y);
5377 width = FIX2LONG(y);
5378 if (width < 0)
5379 return fix_rshift(val, (unsigned long)-width);
5380 return fix_lshift(val, width);
5381}
5382
5383static VALUE
5384fix_lshift(long val, unsigned long width)
5385{
5386 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5387 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5388 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5389 }
5390 val = val << width;
5391 return LONG2NUM(val);
5392}
5393
5394/*
5395 * call-seq:
5396 * self << count -> integer
5397 *
5398 * Returns +self+ with bits shifted +count+ positions to the left,
5399 * or to the right if +count+ is negative:
5400 *
5401 * n = 0b11110000
5402 * "%08b" % (n << 1) # => "111100000"
5403 * "%08b" % (n << 3) # => "11110000000"
5404 * "%08b" % (n << -1) # => "01111000"
5405 * "%08b" % (n << -3) # => "00011110"
5406 *
5407 * Related: Integer#>>.
5408 *
5409 */
5410
5411VALUE
5412rb_int_lshift(VALUE x, VALUE y)
5413{
5414 if (FIXNUM_P(x)) {
5415 return rb_fix_lshift(x, y);
5416 }
5417 else if (RB_BIGNUM_TYPE_P(x)) {
5418 return rb_big_lshift(x, y);
5419 }
5420 return Qnil;
5421}
5422
5423static VALUE
5424rb_fix_rshift(VALUE x, VALUE y)
5425{
5426 long i, val;
5427
5428 val = FIX2LONG(x);
5429 if (!val) return (rb_to_int(y), INT2FIX(0));
5430 if (!FIXNUM_P(y))
5431 return rb_big_rshift(rb_int2big(val), y);
5432 i = FIX2LONG(y);
5433 if (i == 0) return x;
5434 if (i < 0)
5435 return fix_lshift(val, (unsigned long)-i);
5436 return fix_rshift(val, i);
5437}
5438
5439static VALUE
5440fix_rshift(long val, unsigned long i)
5441{
5442 if (i >= sizeof(long)*CHAR_BIT-1) {
5443 if (val < 0) return INT2FIX(-1);
5444 return INT2FIX(0);
5445 }
5446 val = RSHIFT(val, i);
5447 return LONG2FIX(val);
5448}
5449
5450/*
5451 * call-seq:
5452 * self >> count -> integer
5453 *
5454 * Returns +self+ with bits shifted +count+ positions to the right,
5455 * or to the left if +count+ is negative:
5456 *
5457 * n = 0b11110000
5458 * "%08b" % (n >> 1) # => "01111000"
5459 * "%08b" % (n >> 3) # => "00011110"
5460 * "%08b" % (n >> -1) # => "111100000"
5461 * "%08b" % (n >> -3) # => "11110000000"
5462 *
5463 * Related: Integer#<<.
5464 *
5465 */
5466
5467VALUE
5468rb_int_rshift(VALUE x, VALUE y)
5469{
5470 if (FIXNUM_P(x)) {
5471 return rb_fix_rshift(x, y);
5472 }
5473 else if (RB_BIGNUM_TYPE_P(x)) {
5474 return rb_big_rshift(x, y);
5475 }
5476 return Qnil;
5477}
5478
5479VALUE
5480rb_fix_aref(VALUE fix, VALUE idx)
5481{
5482 long val = FIX2LONG(fix);
5483 long i;
5484
5485 idx = rb_to_int(idx);
5486 if (!FIXNUM_P(idx)) {
5487 idx = rb_big_norm(idx);
5488 if (!FIXNUM_P(idx)) {
5489 if (!BIGNUM_SIGN(idx) || val >= 0)
5490 return INT2FIX(0);
5491 return INT2FIX(1);
5492 }
5493 }
5494 i = FIX2LONG(idx);
5495
5496 if (i < 0) return INT2FIX(0);
5497 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5498 if (val < 0) return INT2FIX(1);
5499 return INT2FIX(0);
5500 }
5501 if (val & (1L<<i))
5502 return INT2FIX(1);
5503 return INT2FIX(0);
5504}
5505
5506
5507/* copied from "r_less" in range.c */
5508/* compares _a_ and _b_ and returns:
5509 * < 0: a < b
5510 * = 0: a = b
5511 * > 0: a > b or non-comparable
5512 */
5513static int
5514compare_indexes(VALUE a, VALUE b)
5515{
5516 VALUE r = rb_funcall(a, id_cmp, 1, b);
5517
5518 if (NIL_P(r))
5519 return INT_MAX;
5520 return rb_cmpint(r, a, b);
5521}
5522
5523static VALUE
5524generate_mask(VALUE len)
5525{
5526 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5527}
5528
5529static VALUE
5530int_aref2(VALUE num, VALUE beg, VALUE len)
5531{
5532 if (RB_TYPE_P(num, T_BIGNUM)) {
5533 return rb_big_aref2(num, beg, len);
5534 }
5535 else {
5536 num = rb_int_rshift(num, beg);
5537 VALUE mask = generate_mask(len);
5538 return rb_int_and(num, mask);
5539 }
5540}
5541
5542static VALUE
5543int_aref1(VALUE num, VALUE arg)
5544{
5545 VALUE beg, end;
5546 int excl;
5547
5548 if (rb_range_values(arg, &beg, &end, &excl)) {
5549 if (NIL_P(beg)) {
5550 /* beginless range */
5551 if (!RTEST(num_negative_p(end))) {
5552 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5553 VALUE mask = generate_mask(end);
5554 if (int_zero_p(rb_int_and(num, mask))) {
5555 return INT2FIX(0);
5556 }
5557 else {
5558 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5559 }
5560 }
5561 else {
5562 return INT2FIX(0);
5563 }
5564 }
5565
5566 int cmp = compare_indexes(beg, end);
5567 if (!NIL_P(end) && cmp < 0) {
5568 VALUE len = rb_int_minus(end, beg);
5569 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5570 return int_aref2(num, beg, len);
5571 }
5572 else if (cmp == 0) {
5573 if (excl) return INT2FIX(0);
5574 arg = beg;
5575 goto one_bit;
5576 }
5577 return rb_int_rshift(num, beg);
5578 }
5579
5580one_bit:
5581 if (FIXNUM_P(num)) {
5582 return rb_fix_aref(num, arg);
5583 }
5584 else if (RB_BIGNUM_TYPE_P(num)) {
5585 return rb_big_aref(num, arg);
5586 }
5587 return Qnil;
5588}
5589
5590/*
5591 * call-seq:
5592 * self[offset] -> 0 or 1
5593 * self[offset, size] -> integer
5594 * self[range] -> integer
5595 *
5596 * Returns a slice of bits from +self+.
5597 *
5598 * With argument +offset+, returns the bit at the given offset,
5599 * where offset 0 refers to the least significant bit:
5600 *
5601 * n = 0b10 # => 2
5602 * n[0] # => 0
5603 * n[1] # => 1
5604 * n[2] # => 0
5605 * n[3] # => 0
5606 *
5607 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5608 * Thus, negative index always returns zero:
5609 *
5610 * 255[-1] # => 0
5611 *
5612 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5613 * beginning at +offset+ and including bits of greater significance:
5614 *
5615 * n = 0b111000 # => 56
5616 * "%010b" % n[0, 10] # => "0000111000"
5617 * "%010b" % n[4, 10] # => "0000000011"
5618 *
5619 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5620 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5621 *
5622 * n = 0b111000 # => 56
5623 * "%010b" % n[0..9] # => "0000111000"
5624 * "%010b" % n[4..9] # => "0000000011"
5625 *
5626 * Raises an exception if the slice cannot be constructed.
5627 */
5628
5629static VALUE
5630int_aref(int const argc, VALUE * const argv, VALUE const num)
5631{
5632 rb_check_arity(argc, 1, 2);
5633 if (argc == 2) {
5634 return int_aref2(num, argv[0], argv[1]);
5635 }
5636 return int_aref1(num, argv[0]);
5637
5638 return Qnil;
5639}
5640
5641/*
5642 * call-seq:
5643 * to_f -> float
5644 *
5645 * Converts +self+ to a Float:
5646 *
5647 * 1.to_f # => 1.0
5648 * -1.to_f # => -1.0
5649 *
5650 * If the value of +self+ does not fit in a Float,
5651 * the result is infinity:
5652 *
5653 * (10**400).to_f # => Infinity
5654 * (-10**400).to_f # => -Infinity
5655 *
5656 */
5657
5658static VALUE
5659int_to_f(VALUE num)
5660{
5661 double val;
5662
5663 if (FIXNUM_P(num)) {
5664 val = (double)FIX2LONG(num);
5665 }
5666 else if (RB_BIGNUM_TYPE_P(num)) {
5667 val = rb_big2dbl(num);
5668 }
5669 else {
5670 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5671 }
5672
5673 return DBL2NUM(val);
5674}
5675
5676static VALUE
5677fix_abs(VALUE fix)
5678{
5679 long i = FIX2LONG(fix);
5680
5681 if (i < 0) i = -i;
5682
5683 return LONG2NUM(i);
5684}
5685
5686VALUE
5687rb_int_abs(VALUE num)
5688{
5689 if (FIXNUM_P(num)) {
5690 return fix_abs(num);
5691 }
5692 else if (RB_BIGNUM_TYPE_P(num)) {
5693 return rb_big_abs(num);
5694 }
5695 return Qnil;
5696}
5697
5698static VALUE
5699fix_size(VALUE fix)
5700{
5701 return INT2FIX(sizeof(long));
5702}
5703
5704VALUE
5705rb_int_size(VALUE num)
5706{
5707 if (FIXNUM_P(num)) {
5708 return fix_size(num);
5709 }
5710 else if (RB_BIGNUM_TYPE_P(num)) {
5711 return rb_big_size_m(num);
5712 }
5713 return Qnil;
5714}
5715
5716static VALUE
5717rb_fix_bit_length(VALUE fix)
5718{
5719 long v = FIX2LONG(fix);
5720 if (v < 0)
5721 v = ~v;
5722 return LONG2FIX(bit_length(v));
5723}
5724
5725VALUE
5726rb_int_bit_length(VALUE num)
5727{
5728 if (FIXNUM_P(num)) {
5729 return rb_fix_bit_length(num);
5730 }
5731 else if (RB_BIGNUM_TYPE_P(num)) {
5732 return rb_big_bit_length(num);
5733 }
5734 return Qnil;
5735}
5736
5737static VALUE
5738rb_fix_bit_count(VALUE fix)
5739{
5740 long v = FIX2LONG(fix);
5741 if (v < 0)
5742 rb_raise(rb_eArgError, "bit_count is undefined for negative integers");
5743 return LONG2FIX(rb_popcount_intptr((uintptr_t)v));
5744}
5745
5746/*
5747 * call-seq:
5748 * bit_count -> integer
5749 *
5750 * Returns the number of set bits (bits equal to 1) in the binary
5751 * representation of +self+, also known as the population count or
5752 * Hamming weight.
5753 *
5754 * 0.bit_count # => 0
5755 * 1.bit_count # => 1
5756 * 7.bit_count # => 3
5757 * 0b10101.bit_count # => 3
5758 * 255.bit_count # => 8
5759 * (2**1000).bit_count # => 1
5760 * (2**1000-1).bit_count # => 1000
5761 *
5762 * Raises an exception if +self+ is negative.
5763 *
5764 * (-1).bit_count # Raises ArgumentError
5765 *
5766 */
5767
5768VALUE
5769rb_int_bit_count(VALUE num)
5770{
5771 if (FIXNUM_P(num)) {
5772 return rb_fix_bit_count(num);
5773 }
5774 else if (RB_BIGNUM_TYPE_P(num)) {
5775 return rb_big_bit_count(num);
5776 }
5778}
5779
5780static VALUE
5781rb_fix_digits(VALUE fix, long base)
5782{
5783 VALUE digits;
5784 long x = FIX2LONG(fix);
5785
5786 RUBY_ASSERT(x >= 0);
5787
5788 if (base < 2)
5789 rb_raise(rb_eArgError, "invalid radix %ld", base);
5790
5791 if (x == 0)
5792 return rb_ary_new_from_args(1, INT2FIX(0));
5793
5794 digits = rb_ary_new();
5795 while (x >= base) {
5796 long q = x % base;
5797 rb_ary_push(digits, LONG2NUM(q));
5798 x /= base;
5799 }
5800 rb_ary_push(digits, LONG2NUM(x));
5801
5802 return digits;
5803}
5804
5805static VALUE
5806rb_int_digits_bigbase(VALUE num, VALUE base)
5807{
5808 VALUE digits, bases;
5809
5810 RUBY_ASSERT(!rb_num_negative_p(num));
5811
5812 if (RB_BIGNUM_TYPE_P(base))
5813 base = rb_big_norm(base);
5814
5815 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5816 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5817 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5818 rb_raise(rb_eArgError, "negative radix");
5819
5820 if (FIXNUM_P(base) && FIXNUM_P(num))
5821 return rb_fix_digits(num, FIX2LONG(base));
5822
5823 if (FIXNUM_P(num))
5824 return rb_ary_new_from_args(1, num);
5825
5826 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5827 digits = rb_ary_new();
5828 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5829 VALUE qr = rb_int_divmod(num, base);
5830 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5831 num = RARRAY_AREF(qr, 0);
5832 }
5833 return digits;
5834 }
5835
5836 bases = rb_ary_new();
5837 for (VALUE b = base; int_le(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5838 rb_ary_push(bases, b);
5839 }
5840 digits = rb_ary_new_from_args(1, num);
5841 while (RARRAY_LEN(bases)) {
5842 VALUE b = rb_ary_pop(bases);
5843 long i, last_idx = RARRAY_LEN(digits) - 1;
5844 for(i = last_idx; i >= 0; i--) {
5845 VALUE n = RARRAY_AREF(digits, i);
5846 VALUE divmod = rb_int_divmod(n, b);
5847 VALUE div = RARRAY_AREF(divmod, 0);
5848 VALUE mod = RARRAY_AREF(divmod, 1);
5849 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5850 rb_ary_store(digits, 2 * i, mod);
5851 }
5852 }
5853
5854 return digits;
5855}
5856
5857/*
5858 * call-seq:
5859 * digits(base = 10) -> array_of_integers
5860 *
5861 * Returns an array of integers representing the +base+-radix
5862 * digits of +self+;
5863 * the first element of the array represents the least significant digit:
5864 *
5865 * 12345.digits # => [5, 4, 3, 2, 1]
5866 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5867 * 12345.digits(100) # => [45, 23, 1]
5868 *
5869 * Raises an exception if +self+ is negative or +base+ is less than 2.
5870 *
5871 */
5872
5873static VALUE
5874rb_int_digits(int argc, VALUE *argv, VALUE num)
5875{
5876 VALUE base_value;
5877 long base;
5878
5879 if (rb_num_negative_p(num))
5880 rb_raise(rb_eMathDomainError, "out of domain");
5881
5882 if (rb_check_arity(argc, 0, 1)) {
5883 base_value = rb_to_int(argv[0]);
5884 if (!RB_INTEGER_TYPE_P(base_value))
5885 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5886 rb_obj_classname(argv[0]));
5887 if (RB_BIGNUM_TYPE_P(base_value))
5888 return rb_int_digits_bigbase(num, base_value);
5889
5890 base = FIX2LONG(base_value);
5891 if (base < 0)
5892 rb_raise(rb_eArgError, "negative radix");
5893 else if (base < 2)
5894 rb_raise(rb_eArgError, "invalid radix %ld", base);
5895 }
5896 else
5897 base = 10;
5898
5899 if (FIXNUM_P(num))
5900 return rb_fix_digits(num, base);
5901 else if (RB_BIGNUM_TYPE_P(num))
5902 return rb_int_digits_bigbase(num, LONG2FIX(base));
5903
5904 return Qnil;
5905}
5906
5907static VALUE
5908int_upto_size(VALUE from, VALUE args, VALUE eobj)
5909{
5910 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5911}
5912
5913/*
5914 * call-seq:
5915 * upto(limit) {|i| ... } -> self
5916 * upto(limit) -> enumerator
5917 *
5918 * Calls the given block with each integer value from +self+ up to +limit+;
5919 * returns +self+:
5920 *
5921 * a = []
5922 * 5.upto(10) {|i| a << i } # => 5
5923 * a # => [5, 6, 7, 8, 9, 10]
5924 * a = []
5925 * -5.upto(0) {|i| a << i } # => -5
5926 * a # => [-5, -4, -3, -2, -1, 0]
5927 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5928 *
5929 * With no block given, returns an Enumerator.
5930 *
5931 */
5932
5933static VALUE
5934int_upto(VALUE from, VALUE to)
5935{
5936 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5937 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5938 long i, end;
5939
5940 end = FIX2LONG(to);
5941 for (i = FIX2LONG(from); i <= end; i++) {
5942 rb_yield(LONG2FIX(i));
5943 }
5944 }
5945 else {
5946 VALUE i = from, c;
5947
5948 while (!(c = rb_funcall(i, '>', 1, to))) {
5949 rb_yield(i);
5950 i = rb_funcall(i, '+', 1, INT2FIX(1));
5951 }
5952 ensure_cmp(c, i, to);
5953 }
5954 return from;
5955}
5956
5957static VALUE
5958int_downto_size(VALUE from, VALUE args, VALUE eobj)
5959{
5960 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5961}
5962
5963/*
5964 * call-seq:
5965 * downto(limit) {|i| ... } -> self
5966 * downto(limit) -> enumerator
5967 *
5968 * Calls the given block with each integer value from +self+ down to +limit+;
5969 * returns +self+:
5970 *
5971 * a = []
5972 * 10.downto(5) {|i| a << i } # => 10
5973 * a # => [10, 9, 8, 7, 6, 5]
5974 * a = []
5975 * 0.downto(-5) {|i| a << i } # => 0
5976 * a # => [0, -1, -2, -3, -4, -5]
5977 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5978 *
5979 * With no block given, returns an Enumerator.
5980 *
5981 */
5982
5983static VALUE
5984int_downto(VALUE from, VALUE to)
5985{
5986 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5987 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5988 long i, end;
5989
5990 end = FIX2LONG(to);
5991 for (i=FIX2LONG(from); i >= end; i--) {
5992 rb_yield(LONG2FIX(i));
5993 }
5994 }
5995 else {
5996 VALUE i = from, c;
5997
5998 while (!(c = rb_funcall(i, '<', 1, to))) {
5999 rb_yield(i);
6000 i = rb_funcall(i, '-', 1, INT2FIX(1));
6001 }
6002 ensure_cmp(c, i, to);
6003 }
6004 return from;
6005}
6006
6007static VALUE
6008int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
6009{
6010 return int_neg_p(num) ? INT2FIX(0) : num;
6011}
6012
6013/*
6014 * call-seq:
6015 * round(ndigits= 0, half: :up) -> integer
6016 *
6017 * Returns +self+ rounded to the nearest value with
6018 * a precision of +ndigits+ decimal digits.
6019 *
6020 * When +ndigits+ is negative, the returned value
6021 * has at least <tt>ndigits.abs</tt> trailing zeros:
6022 *
6023 * 555.round(-1) # => 560
6024 * 555.round(-2) # => 600
6025 * 555.round(-3) # => 1000
6026 * -555.round(-2) # => -600
6027 * 555.round(-4) # => 0
6028 *
6029 * Returns +self+ when +ndigits+ is zero or positive.
6030 *
6031 * 555.round # => 555
6032 * 555.round(1) # => 555
6033 * 555.round(50) # => 555
6034 *
6035 * If keyword argument +half+ is given,
6036 * and +self+ is equidistant from the two candidate values,
6037 * the rounding is according to the given +half+ value:
6038 *
6039 * - +:up+ or +nil+: round away from zero:
6040 *
6041 * 25.round(-1, half: :up) # => 30
6042 * (-25).round(-1, half: :up) # => -30
6043 *
6044 * - +:down+: round toward zero:
6045 *
6046 * 25.round(-1, half: :down) # => 20
6047 * (-25).round(-1, half: :down) # => -20
6048 *
6049 *
6050 * - +:even+: round toward the candidate whose last nonzero digit is even:
6051 *
6052 * 25.round(-1, half: :even) # => 20
6053 * 15.round(-1, half: :even) # => 20
6054 * (-25).round(-1, half: :even) # => -20
6055 *
6056 * Raises and exception if the value for +half+ is invalid.
6057 *
6058 * Related: Integer#truncate.
6059 *
6060 */
6061
6062static VALUE
6063int_round(int argc, VALUE* argv, VALUE num)
6064{
6065 int ndigits;
6066 int mode;
6067 VALUE nd, opt;
6068
6069 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
6070 ndigits = NUM2INT(nd);
6071 mode = rb_num_get_rounding_option(opt);
6072 if (ndigits >= 0) {
6073 return num;
6074 }
6075 return rb_int_round(num, ndigits, mode);
6076}
6077
6078/*
6079 * :markup: markdown
6080 *
6081 * call-seq:
6082 * floor(ndigits = 0) -> integer
6083 *
6084 * Returns an integer that is a "floor" value for `self`,
6085 * as specified by the given `ndigits`,
6086 * which must be an
6087 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6088 *
6089 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6090 *
6091 * ```
6092 * 0.floor(2) # => 0
6093 * 0.floor(-2) # => 0
6094 * ```
6095 *
6096 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6097 *
6098 * ```
6099 * 555.floor # => 555
6100 * 555.floor(50) # => 555
6101 * ```
6102 *
6103 * - When `self` is non-zero and `ndigits` is negative,
6104 * returns a value based on a computed granularity:
6105 *
6106 * - The granularity is `10 ** ndigits.abs`.
6107 * - The returned value is the largest multiple of the granularity
6108 * that is less than or equal to `self`.
6109 *
6110 * Examples with positive `self`:
6111 *
6112 * | ndigits | Granularity | 1234.floor(ndigits) |
6113 * |--------:|------------:|--------------------:|
6114 * | -1 | 10 | 1230 |
6115 * | -2 | 100 | 1200 |
6116 * | -3 | 1000 | 1000 |
6117 * | -4 | 10000 | 0 |
6118 * | -5 | 100000 | 0 |
6119 *
6120 * Examples with negative `self`:
6121 *
6122 * | ndigits | Granularity | -1234.floor(ndigits) |
6123 * |--------:|------------:|---------------------:|
6124 * | -1 | 10 | -1240 |
6125 * | -2 | 100 | -1300 |
6126 * | -3 | 1000 | -2000 |
6127 * | -4 | 10000 | -10000 |
6128 * | -5 | 100000 | -100000 |
6129 *
6130 * Related: Integer#ceil.
6131 *
6132 */
6133
6134static VALUE
6135int_floor(int argc, VALUE* argv, VALUE num)
6136{
6137 int ndigits;
6138
6139 if (!rb_check_arity(argc, 0, 1)) return num;
6140 ndigits = NUM2INT(argv[0]);
6141 if (ndigits >= 0) {
6142 return num;
6143 }
6144 return rb_int_floor(num, ndigits);
6145}
6146
6147/*
6148 * :markup: markdown
6149 *
6150 * call-seq:
6151 * ceil(ndigits = 0) -> integer
6152 *
6153 * Returns an integer that is a "ceiling" value for `self`,
6154 * as specified by the given `ndigits`,
6155 * which must be an
6156 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6157 *
6158 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6159 *
6160 * ```
6161 * 0.ceil(2) # => 0
6162 * 0.ceil(-2) # => 0
6163 * ```
6164 *
6165 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6166 *
6167 * ```
6168 * 555.ceil # => 555
6169 * 555.ceil(50) # => 555
6170 * ```
6171 *
6172 * - When `self` is non-zero and `ndigits` is negative,
6173 * returns a value based on a computed granularity:
6174 *
6175 * - The granularity is `10 ** ndigits.abs`.
6176 * - The returned value is the smallest multiple of the granularity
6177 * that is greater than or equal to `self`.
6178 *
6179 * Examples with positive `self`:
6180 *
6181 * | ndigits | Granularity | 1234.ceil(ndigits) |
6182 * |--------:|------------:|-------------------:|
6183 * | -1 | 10 | 1240 |
6184 * | -2 | 100 | 1300 |
6185 * | -3 | 1000 | 2000 |
6186 * | -4 | 10000 | 10000 |
6187 * | -5 | 100000 | 100000 |
6188 *
6189 * Examples with negative `self`:
6190 *
6191 * | ndigits | Granularity | -1234.ceil(ndigits) |
6192 * |--------:|------------:|--------------------:|
6193 * | -1 | 10 | -1230 |
6194 * | -2 | 100 | -1200 |
6195 * | -3 | 1000 | -1000 |
6196 * | -4 | 10000 | 0 |
6197 * | -5 | 100000 | 0 |
6198 *
6199 * Related: Integer#floor.
6200 */
6201
6202static VALUE
6203int_ceil(int argc, VALUE* argv, VALUE num)
6204{
6205 int ndigits;
6206
6207 if (!rb_check_arity(argc, 0, 1)) return num;
6208 ndigits = NUM2INT(argv[0]);
6209 if (ndigits >= 0) {
6210 return num;
6211 }
6212 return rb_int_ceil(num, ndigits);
6213}
6214
6215/*
6216 * call-seq:
6217 * truncate(ndigits = 0) -> integer
6218 *
6219 * Returns +self+ truncated (toward zero) to
6220 * a precision of +ndigits+ decimal digits.
6221 *
6222 * When +ndigits+ is negative, the returned value
6223 * has at least <tt>ndigits.abs</tt> trailing zeros:
6224 *
6225 * 555.truncate(-1) # => 550
6226 * 555.truncate(-2) # => 500
6227 * -555.truncate(-2) # => -500
6228 *
6229 * Returns +self+ when +ndigits+ is zero or positive.
6230 *
6231 * 555.truncate # => 555
6232 * 555.truncate(50) # => 555
6233 *
6234 * Related: Integer#round.
6235 *
6236 */
6237
6238static VALUE
6239int_truncate(int argc, VALUE* argv, VALUE num)
6240{
6241 int ndigits;
6242
6243 if (!rb_check_arity(argc, 0, 1)) return num;
6244 ndigits = NUM2INT(argv[0]);
6245 if (ndigits >= 0) {
6246 return num;
6247 }
6248 return rb_int_truncate(num, ndigits);
6249}
6250
6251#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6252rettype \
6253prefix##_isqrt(argtype n) \
6254{ \
6255 if (!argtype##_IN_DOUBLE_P(n)) { \
6256 unsigned int b = bit_length(n); \
6257 argtype t; \
6258 rettype x = (rettype)(n >> (b/2+1)); \
6259 x |= ((rettype)1LU << (b-1)/2); \
6260 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6261 return x; \
6262 } \
6263 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6264 /* libm sqrt may returns a larger approximation than actual. */ \
6265 /* Our isqrt always returns a smaller approximation. */ \
6266 if (x * x > n) x--; \
6267 return x; \
6268}
6269
6270#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6271# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6272#else
6273# define RB_ULONG_IN_DOUBLE_P(n) 1
6274#endif
6275#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6276#define RB_ULONG unsigned long
6277DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
6278
6279#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6280# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6281# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6282# else
6283# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6284# endif
6285# ifdef ULL_TO_DOUBLE
6286# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6287# else
6288# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6289# endif
6290DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6291#endif
6292
6293#define domain_error(msg) \
6294 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6295
6296/*
6297 * call-seq:
6298 * Integer.sqrt(numeric) -> integer
6299 *
6300 * Returns the integer square root of the non-negative integer +n+,
6301 * which is the largest non-negative integer less than or equal to the
6302 * square root of +numeric+.
6303 *
6304 * Integer.sqrt(0) # => 0
6305 * Integer.sqrt(1) # => 1
6306 * Integer.sqrt(24) # => 4
6307 * Integer.sqrt(25) # => 5
6308 * Integer.sqrt(10**400) # => 10**200
6309 *
6310 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6311 *
6312 * Integer.sqrt(Complex(4, 0)) # => 2
6313 * Integer.sqrt(Rational(4, 1)) # => 2
6314 * Integer.sqrt(4.0) # => 2
6315 * Integer.sqrt(3.14159) # => 1
6316 *
6317 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6318 * except that the result of the latter code may differ from the true value
6319 * due to the limited precision of floating point arithmetic.
6320 *
6321 * Integer.sqrt(10**46) # => 100000000000000000000000
6322 * Math.sqrt(10**46).floor # => 99999999999999991611392
6323 *
6324 * Raises an exception if +numeric+ is negative.
6325 *
6326 */
6327
6328static VALUE
6329rb_int_s_isqrt(VALUE self, VALUE num)
6330{
6331 unsigned long n, sq;
6332 num = rb_to_int(num);
6333 if (FIXNUM_P(num)) {
6334 if (FIXNUM_NEGATIVE_P(num)) {
6335 domain_error("isqrt");
6336 }
6337 n = FIX2ULONG(num);
6338 sq = rb_ulong_isqrt(n);
6339 return LONG2FIX(sq);
6340 }
6341 else {
6342 size_t biglen;
6343 if (RBIGNUM_NEGATIVE_P(num)) {
6344 domain_error("isqrt");
6345 }
6346 biglen = BIGNUM_LEN(num);
6347 if (biglen == 0) return INT2FIX(0);
6348#if SIZEOF_BDIGIT <= SIZEOF_LONG
6349 /* short-circuit */
6350 if (biglen == 1) {
6351 n = BIGNUM_DIGITS(num)[0];
6352 sq = rb_ulong_isqrt(n);
6353 return ULONG2NUM(sq);
6354 }
6355#endif
6356 return rb_big_isqrt(num);
6357 }
6358}
6359
6360/*
6361 * call-seq:
6362 * Integer.try_convert(object) -> object, integer, or nil
6363 *
6364 * If +object+ is an \Integer object, returns +object+.
6365 * Integer.try_convert(1) # => 1
6366 *
6367 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6368 * calls <tt>object.to_int</tt> and returns the result.
6369 * Integer.try_convert(1.25) # => 1
6370 *
6371 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6372 * Integer.try_convert([]) # => nil
6373 *
6374 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6375 */
6376static VALUE
6377int_s_try_convert(VALUE self, VALUE num)
6378{
6379 return rb_check_integer_type(num);
6380}
6381
6382/*
6383 * Document-class: ZeroDivisionError
6384 *
6385 * Raised when attempting to divide an integer by 0.
6386 *
6387 * 42 / 0 #=> ZeroDivisionError: divided by 0
6388 *
6389 * Note that only division by an exact 0 will raise the exception:
6390 *
6391 * 42 / 0.0 #=> Float::INFINITY
6392 * 42 / -0.0 #=> -Float::INFINITY
6393 * 0 / 0.0 #=> NaN
6394 */
6395
6396/*
6397 * Document-class: FloatDomainError
6398 *
6399 * Raised when attempting to convert special float values (in particular
6400 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6401 *
6402 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6403 */
6404
6405/*
6406 * Document-class: Numeric
6407 *
6408 * \Numeric is the class from which all higher-level numeric classes should inherit.
6409 *
6410 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6411 * Integer are implemented as immediates, which means that each Integer is a single immutable
6412 * object which is always passed by value.
6413 *
6414 * a = 1
6415 * 1.object_id == a.object_id #=> true
6416 *
6417 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6418 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6419 *
6420 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6421 * 1.dup #=> 1
6422 * 1.object_id == 1.dup.object_id #=> true
6423 *
6424 * For this reason, \Numeric should be used when defining other numeric classes.
6425 *
6426 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6427 * Array containing an object that has been coerced into an instance of the new class
6428 * and +self+ (see #coerce).
6429 *
6430 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6431 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6432 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6433 * instances of other numeric classes.
6434 *
6435 * class Tally < Numeric
6436 * def initialize(string)
6437 * @string = string
6438 * end
6439 *
6440 * def to_s
6441 * @string
6442 * end
6443 *
6444 * def to_i
6445 * @string.size
6446 * end
6447 *
6448 * def coerce(other)
6449 * [self.class.new('|' * other.to_i), self]
6450 * end
6451 *
6452 * def <=>(other)
6453 * to_i <=> other.to_i
6454 * end
6455 *
6456 * def +(other)
6457 * self.class.new('|' * (to_i + other.to_i))
6458 * end
6459 *
6460 * def -(other)
6461 * self.class.new('|' * (to_i - other.to_i))
6462 * end
6463 *
6464 * def *(other)
6465 * self.class.new('|' * (to_i * other.to_i))
6466 * end
6467 *
6468 * def /(other)
6469 * self.class.new('|' * (to_i / other.to_i))
6470 * end
6471 * end
6472 *
6473 * tally = Tally.new('||')
6474 * puts tally * 2 #=> "||||"
6475 * puts tally > 1 #=> true
6476 *
6477 * == What's Here
6478 *
6479 * First, what's elsewhere. Class \Numeric:
6480 *
6481 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
6482 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
6483 *
6484 * Here, class \Numeric provides methods for:
6485 *
6486 * - {Querying}[rdoc-ref:Numeric@Querying]
6487 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6488 * - {Converting}[rdoc-ref:Numeric@Converting]
6489 * - {Other}[rdoc-ref:Numeric@Other]
6490 *
6491 * === Querying
6492 *
6493 * - #finite?: Returns true unless +self+ is infinite or not a number.
6494 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6495 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6496 * - #integer?: Returns whether +self+ is an integer.
6497 * - #negative?: Returns whether +self+ is negative.
6498 * - #nonzero?: Returns whether +self+ is not zero.
6499 * - #positive?: Returns whether +self+ is positive.
6500 * - #real?: Returns whether +self+ is a real value.
6501 * - #zero?: Returns whether +self+ is zero.
6502 *
6503 * === Comparing
6504 *
6505 * - #<=>: Returns:
6506 *
6507 * - -1 if +self+ is less than the given value.
6508 * - 0 if +self+ is equal to the given value.
6509 * - 1 if +self+ is greater than the given value.
6510 * - +nil+ if +self+ and the given value are not comparable.
6511 *
6512 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6513 *
6514 * === Converting
6515 *
6516 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6517 * - #-@: Returns the value of +self+, negated.
6518 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6519 * - #abs2: Returns the square of +self+.
6520 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6521 * Math::PI otherwise.
6522 * - #ceil: Returns the smallest number greater than or equal to +self+,
6523 * to a given precision.
6524 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6525 * for the given other value.
6526 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6527 * - #denominator: Returns the denominator (always positive)
6528 * of the Rational representation of +self+.
6529 * - #div: Returns the value of +self+ divided by the given value
6530 * and converted to an integer.
6531 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6532 * from dividing +self+ the given divisor.
6533 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6534 * - #floor: Returns the largest number less than or equal to +self+,
6535 * to a given precision.
6536 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6537 * the given value.
6538 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6539 * - #numerator: Returns the numerator of the Rational representation of +self+;
6540 * has the same sign as +self+.
6541 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6542 * - #quo: Returns the value of +self+ divided by the given value.
6543 * - #real: Returns the real part of +self+.
6544 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6545 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6546 * - #round: Returns the value of +self+ rounded to the nearest value
6547 * for the given a precision.
6548 * - #to_c: Returns the Complex representation of +self+.
6549 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6550 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6551 *
6552 * === Other
6553 *
6554 * - #clone: Returns +self+; does not allow freezing.
6555 * - #dup (aliased as #+@): Returns +self+.
6556 * - #step: Invokes the given block with the sequence of specified numbers.
6557 *
6558 */
6559void
6560Init_Numeric(void)
6561{
6562#ifdef _UNICOSMP
6563 /* Turn off floating point exceptions for divide by zero, etc. */
6564 _set_Creg(0, 0);
6565#endif
6566 id_coerce = rb_intern_const("coerce");
6567 id_to = rb_intern_const("to");
6568 id_by = rb_intern_const("by");
6569
6570 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6571 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6572 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6573
6574 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6576 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6577 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6578
6579 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6580 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6581 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6582 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6583 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6584 rb_define_method(rb_cNumeric, "div", num_div, 1);
6585 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6586 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6587 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6588 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6589 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6590 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6591 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6592
6593 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6594 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6595
6596 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6597 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6598 rb_define_method(rb_cNumeric, "round", num_round, -1);
6599 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6600 rb_define_method(rb_cNumeric, "step", num_step, -1);
6601 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6602 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6603
6604 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6607 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6608 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6609
6610 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6611 rb_define_alias(rb_cInteger, "inspect", "to_s");
6612 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6613 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6614 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6615 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6616 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6617 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6618 rb_define_method(rb_cInteger, "next", int_succ, 0);
6619 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6620 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6621 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6622 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6623 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6624 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6625 rb_define_method(rb_cInteger, "round", int_round, -1);
6626 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6627
6628 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6629 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6630 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6631 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6632 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6633 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6634 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6635 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6636 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6637 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6638 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6639
6640 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6641
6642 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6643 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6644 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6645 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6646 rb_define_method(rb_cInteger, "<", int_lt, 1);
6647 rb_define_method(rb_cInteger, "<=", int_le, 1);
6648
6649 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6650 rb_define_method(rb_cInteger, "|", int_or, 1);
6651 rb_define_method(rb_cInteger, "^", rb_int_xor, 1);
6652 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6653
6654 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6655 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6656
6657 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6658 rb_define_method(rb_cInteger, "bit_count", rb_int_bit_count, 0);
6659
6660#define fix_to_s_static(n) do { \
6661 VALUE lit = rb_fstring_literal(#n); \
6662 rb_fix_to_s_static[n] = lit; \
6663 rb_vm_register_global_object(lit); \
6664 RB_GC_GUARD(lit); \
6665 } while (0)
6666
6667 fix_to_s_static(0);
6668 fix_to_s_static(1);
6669 fix_to_s_static(2);
6670 fix_to_s_static(3);
6671 fix_to_s_static(4);
6672 fix_to_s_static(5);
6673 fix_to_s_static(6);
6674 fix_to_s_static(7);
6675 fix_to_s_static(8);
6676 fix_to_s_static(9);
6677
6678#undef fix_to_s_static
6679
6680 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6681
6684
6685 /*
6686 * The base of the floating point, or number of unique digits used to
6687 * represent the number.
6688 *
6689 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6690 */
6691 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6692 /*
6693 * The number of base digits for the +double+ data type.
6694 *
6695 * Usually defaults to 53.
6696 */
6697 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6698 /*
6699 * The minimum number of significant decimal digits in a double-precision
6700 * floating point.
6701 *
6702 * Usually defaults to 15.
6703 */
6704 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6705 /*
6706 * The smallest possible exponent value in a double-precision floating
6707 * point.
6708 *
6709 * Usually defaults to -1021.
6710 */
6711 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6712 /*
6713 * The largest possible exponent value in a double-precision floating
6714 * point.
6715 *
6716 * Usually defaults to 1024.
6717 */
6718 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6719 /*
6720 * The smallest negative exponent in a double-precision floating point
6721 * where 10 raised to this power minus 1.
6722 *
6723 * Usually defaults to -307.
6724 */
6725 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6726 /*
6727 * The largest positive exponent in a double-precision floating point where
6728 * 10 raised to this power minus 1.
6729 *
6730 * Usually defaults to 308.
6731 */
6732 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6733 /*
6734 * The smallest positive normalized number in a double-precision floating point.
6735 *
6736 * Usually defaults to 2.2250738585072014e-308.
6737 *
6738 * If the platform supports denormalized numbers,
6739 * there are numbers between zero and Float::MIN.
6740 * +0.0.next_float+ returns the smallest positive floating point number
6741 * including denormalized numbers.
6742 */
6743 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6744 /*
6745 * The largest possible integer in a double-precision floating point number.
6746 *
6747 * Usually defaults to 1.7976931348623157e+308.
6748 */
6749 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6750 /*
6751 * The difference between 1 and the smallest double-precision floating
6752 * point number greater than 1.
6753 *
6754 * Usually defaults to 2.2204460492503131e-16.
6755 */
6756 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6757 /*
6758 * An expression representing positive infinity.
6759 */
6760 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6761 /*
6762 * An expression representing a value which is "not a number".
6763 */
6764 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6765
6766 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6767 rb_define_alias(rb_cFloat, "inspect", "to_s");
6768 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6769 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6770 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6771 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6772 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6773 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6774 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6775 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6776 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6777 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6778 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6779 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6780 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6781 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6782 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6783 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6784 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6785 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6786 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6787 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6788
6789 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6790 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6791 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6792 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6793 rb_define_method(rb_cFloat, "round", flo_round, -1);
6794 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6795
6796 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6797 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6798 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6799 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6800 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6801}
6802
6803#undef rb_float_value
6804double
6805rb_float_value(VALUE v)
6806{
6807 return rb_float_value_inline(v);
6808}
6809
6810#undef rb_float_new
6811VALUE
6812rb_float_new(double d)
6813{
6814 return rb_float_new_inline(d);
6815}
6816
6817#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:1608
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2854
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2897
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2707
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:3187
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1029
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2976
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2414
VALUE rb_eZeroDivError
ZeroDivisionError exception.
Definition numeric.c:204
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1428
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1435
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
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:3733
VALUE rb_cObject
Object class.
Definition object.c:58
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:646
VALUE rb_cInteger
Module class.
Definition numeric.c: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:232
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:657
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:138
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:894
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFloat
Float class.
Definition numeric.c:201
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3315
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:3946
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.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
Definition enumerator.h:195
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:210
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3362
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:4057
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4766
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:5225
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:1882
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1992
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3648
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1568
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2829
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3014
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:1799
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:2272
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:1147
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:13261
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:3276
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3270
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3264
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3282
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
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:529
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
Definition numeric.c:3320
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3338
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3329
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3348
static bool RB_FIXNUM_P(VALUE obj)
Checks if the given object is a so-called Fixnum.
#define RTEST
This is an old name of RB_TEST.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376