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