Ruby 4.0.0dev (2025-12-16 revision 85b40c5ea8f606cf34cab8a5b1277033bede2457)
numeric.c (85b40c5ea8f606cf34cab8a5b1277033bede2457)
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 a new \Float which is the result of dividing +self+ by +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 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1472 *
1473 * No subclass in the Ruby Core or Standard Library uses this implementation.
1474 *
1475 */
1476
1477static VALUE
1478num_cmp(VALUE x, VALUE y)
1479{
1480 if (x == y) return INT2FIX(0);
1481 return Qnil;
1482}
1483
1484static VALUE
1485num_equal(VALUE x, VALUE y)
1486{
1487 VALUE result;
1488 if (x == y) return Qtrue;
1489 result = num_funcall1(y, id_eq, x);
1490 return RBOOL(RTEST(result));
1491}
1492
1493/*
1494 * call-seq:
1495 * self == other -> true or false
1496 *
1497 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1498 *
1499 * 2.0 == 2 # => true
1500 * 2.0 == 2.0 # => true
1501 * 2.0 == Rational(2, 1) # => true
1502 * 2.0 == Complex(2, 0) # => true
1503 *
1504 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1505 *
1506 * Related: Float#eql? (requires +other+ to be a \Float).
1507 *
1508 */
1509
1510VALUE
1511rb_float_equal(VALUE x, VALUE y)
1512{
1513 volatile double a, b;
1514
1515 if (RB_INTEGER_TYPE_P(y)) {
1516 return rb_integer_float_eq(y, x);
1517 }
1518 else if (RB_FLOAT_TYPE_P(y)) {
1519 b = RFLOAT_VALUE(y);
1520 }
1521 else {
1522 return num_equal(x, y);
1523 }
1524 a = RFLOAT_VALUE(x);
1525 return RBOOL(a == b);
1526}
1527
1528#define flo_eq rb_float_equal
1529static VALUE rb_dbl_hash(double d);
1530
1531/*
1532 * call-seq:
1533 * hash -> integer
1534 *
1535 * Returns the integer hash value for +self+.
1536 *
1537 * See also Object#hash.
1538 */
1539
1540static VALUE
1541flo_hash(VALUE num)
1542{
1543 return rb_dbl_hash(RFLOAT_VALUE(num));
1544}
1545
1546static VALUE
1547rb_dbl_hash(double d)
1548{
1549 return ST2FIX(rb_dbl_long_hash(d));
1550}
1551
1552VALUE
1553rb_dbl_cmp(double a, double b)
1554{
1555 if (isnan(a) || isnan(b)) return Qnil;
1556 if (a == b) return INT2FIX(0);
1557 if (a > b) return INT2FIX(1);
1558 if (a < b) return INT2FIX(-1);
1559 return Qnil;
1560}
1561
1562/*
1563 * call-seq:
1564 * self <=> other -> -1, 0, +1, or nil
1565 *
1566 * Returns a value that depends on the numeric relation
1567 * between +self+ and +other+:
1568 *
1569 * - -1, if +self+ is less than +other+.
1570 * - 0, if +self+ is equal to +other+.
1571 * - 1, if +self+ is greater than +other+.
1572 * - +nil+, if the two values are incommensurate.
1573 *
1574 * Examples:
1575 *
1576 * 2.0 <=> 2 # => 0
1577 * 2.0 <=> 2.0 # => 0
1578 * 2.0 <=> Rational(2, 1) # => 0
1579 * 2.0 <=> Complex(2, 0) # => 0
1580 * 2.0 <=> 1.9 # => 1
1581 * 2.0 <=> 2.1 # => -1
1582 * 2.0 <=> 'foo' # => nil
1583 *
1584 * This is the basis for the tests in the Comparable module.
1585 *
1586 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1587 *
1588 */
1589
1590static VALUE
1591flo_cmp(VALUE x, VALUE y)
1592{
1593 double a, b;
1594 VALUE i;
1595
1596 a = RFLOAT_VALUE(x);
1597 if (isnan(a)) return Qnil;
1598 if (RB_INTEGER_TYPE_P(y)) {
1599 VALUE rel = rb_integer_float_cmp(y, x);
1600 if (FIXNUM_P(rel))
1601 return LONG2FIX(-FIX2LONG(rel));
1602 return rel;
1603 }
1604 else if (RB_FLOAT_TYPE_P(y)) {
1605 b = RFLOAT_VALUE(y);
1606 }
1607 else {
1608 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1609 if (RTEST(i)) {
1610 int j = rb_cmpint(i, x, y);
1611 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1612 return INT2FIX(j);
1613 }
1614 if (a > 0.0) return INT2FIX(1);
1615 return INT2FIX(-1);
1616 }
1617 return rb_num_coerce_cmp(x, y, id_cmp);
1618 }
1619 return rb_dbl_cmp(a, b);
1620}
1621
1622int
1623rb_float_cmp(VALUE x, VALUE y)
1624{
1625 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1626}
1627
1628/*
1629 * call-seq:
1630 * self > other -> true or false
1631 *
1632 * Returns +true+ if +self+ is numerically greater than +other+:
1633 *
1634 * 2.0 > 1 # => true
1635 * 2.0 > 1.0 # => true
1636 * 2.0 > Rational(1, 2) # => true
1637 * 2.0 > 2.0 # => false
1638 *
1639 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1640 *
1641 */
1642
1643VALUE
1644rb_float_gt(VALUE x, VALUE y)
1645{
1646 double a, b;
1647
1648 a = RFLOAT_VALUE(x);
1649 if (RB_INTEGER_TYPE_P(y)) {
1650 VALUE rel = rb_integer_float_cmp(y, x);
1651 if (FIXNUM_P(rel))
1652 return RBOOL(-FIX2LONG(rel) > 0);
1653 return Qfalse;
1654 }
1655 else if (RB_FLOAT_TYPE_P(y)) {
1656 b = RFLOAT_VALUE(y);
1657 }
1658 else {
1659 return rb_num_coerce_relop(x, y, '>');
1660 }
1661 return RBOOL(a > b);
1662}
1663
1664/*
1665 * call-seq:
1666 * self >= other -> true or false
1667 *
1668 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1669 *
1670 * 2.0 >= 1 # => true
1671 * 2.0 >= 1.0 # => true
1672 * 2.0 >= Rational(1, 2) # => true
1673 * 2.0 >= 2.0 # => true
1674 * 2.0 >= 2.1 # => false
1675 *
1676 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1677 *
1678 */
1679
1680static VALUE
1681flo_ge(VALUE x, VALUE y)
1682{
1683 double a, b;
1684
1685 a = RFLOAT_VALUE(x);
1686 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1687 VALUE rel = rb_integer_float_cmp(y, x);
1688 if (FIXNUM_P(rel))
1689 return RBOOL(-FIX2LONG(rel) >= 0);
1690 return Qfalse;
1691 }
1692 else if (RB_FLOAT_TYPE_P(y)) {
1693 b = RFLOAT_VALUE(y);
1694 }
1695 else {
1696 return rb_num_coerce_relop(x, y, idGE);
1697 }
1698 return RBOOL(a >= b);
1699}
1700
1701/*
1702 * call-seq:
1703 * self < other -> true or false
1704 *
1705 * Returns +true+ if +self+ is numerically less than +other+:
1706 *
1707 * 2.0 < 3 # => true
1708 * 2.0 < 3.0 # => true
1709 * 2.0 < Rational(3, 1) # => true
1710 * 2.0 < 2.0 # => false
1711 *
1712 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1713 *
1714 */
1715
1716static VALUE
1717flo_lt(VALUE x, VALUE y)
1718{
1719 double a, b;
1720
1721 a = RFLOAT_VALUE(x);
1722 if (RB_INTEGER_TYPE_P(y)) {
1723 VALUE rel = rb_integer_float_cmp(y, x);
1724 if (FIXNUM_P(rel))
1725 return RBOOL(-FIX2LONG(rel) < 0);
1726 return Qfalse;
1727 }
1728 else if (RB_FLOAT_TYPE_P(y)) {
1729 b = RFLOAT_VALUE(y);
1730 }
1731 else {
1732 return rb_num_coerce_relop(x, y, '<');
1733 }
1734 return RBOOL(a < b);
1735}
1736
1737/*
1738 * call-seq:
1739 * self <= other -> true or false
1740 *
1741 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1742 *
1743 * 2.0 <= 3 # => true
1744 * 2.0 <= 3.0 # => true
1745 * 2.0 <= Rational(3, 1) # => true
1746 * 2.0 <= 2.0 # => true
1747 * 2.0 <= 1.0 # => false
1748 *
1749 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1750 *
1751 */
1752
1753static VALUE
1754flo_le(VALUE x, VALUE y)
1755{
1756 double a, b;
1757
1758 a = RFLOAT_VALUE(x);
1759 if (RB_INTEGER_TYPE_P(y)) {
1760 VALUE rel = rb_integer_float_cmp(y, x);
1761 if (FIXNUM_P(rel))
1762 return RBOOL(-FIX2LONG(rel) <= 0);
1763 return Qfalse;
1764 }
1765 else if (RB_FLOAT_TYPE_P(y)) {
1766 b = RFLOAT_VALUE(y);
1767 }
1768 else {
1769 return rb_num_coerce_relop(x, y, idLE);
1770 }
1771 return RBOOL(a <= b);
1772}
1773
1774/*
1775 * call-seq:
1776 * eql?(other) -> true or false
1777 *
1778 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1779 * +false+ otherwise:
1780 *
1781 * 2.0.eql?(2.0) # => true
1782 * 2.0.eql?(1.0) # => false
1783 * 2.0.eql?(1) # => false
1784 * 2.0.eql?(Rational(2, 1)) # => false
1785 * 2.0.eql?(Complex(2, 0)) # => false
1786 *
1787 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1788 *
1789 * Related: Float#== (performs type conversions).
1790 */
1791
1792VALUE
1793rb_float_eql(VALUE x, VALUE y)
1794{
1795 if (RB_FLOAT_TYPE_P(y)) {
1796 double a = RFLOAT_VALUE(x);
1797 double b = RFLOAT_VALUE(y);
1798 return RBOOL(a == b);
1799 }
1800 return Qfalse;
1801}
1802
1803#define flo_eql rb_float_eql
1804
1805VALUE
1806rb_float_abs(VALUE flt)
1807{
1808 double val = fabs(RFLOAT_VALUE(flt));
1809 return DBL2NUM(val);
1810}
1811
1812/*
1813 * call-seq:
1814 * nan? -> true or false
1815 *
1816 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1817 *
1818 * f = -1.0 #=> -1.0
1819 * f.nan? #=> false
1820 * f = 0.0/0.0 #=> NaN
1821 * f.nan? #=> true
1822 */
1823
1824static VALUE
1825flo_is_nan_p(VALUE num)
1826{
1827 double value = RFLOAT_VALUE(num);
1828
1829 return RBOOL(isnan(value));
1830}
1831
1832/*
1833 * call-seq:
1834 * infinite? -> -1, 1, or nil
1835 *
1836 * Returns:
1837 *
1838 * - 1, if +self+ is <tt>Infinity</tt>.
1839 * - -1 if +self+ is <tt>-Infinity</tt>.
1840 * - +nil+, otherwise.
1841 *
1842 * Examples:
1843 *
1844 * f = 1.0/0.0 # => Infinity
1845 * f.infinite? # => 1
1846 * f = -1.0/0.0 # => -Infinity
1847 * f.infinite? # => -1
1848 * f = 1.0 # => 1.0
1849 * f.infinite? # => nil
1850 * f = 0.0/0.0 # => NaN
1851 * f.infinite? # => nil
1852 *
1853 */
1854
1855VALUE
1856rb_flo_is_infinite_p(VALUE num)
1857{
1858 double value = RFLOAT_VALUE(num);
1859
1860 if (isinf(value)) {
1861 return INT2FIX( value < 0 ? -1 : 1 );
1862 }
1863
1864 return Qnil;
1865}
1866
1867/*
1868 * call-seq:
1869 * finite? -> true or false
1870 *
1871 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1872 * +false+ otherwise:
1873 *
1874 * f = 2.0 # => 2.0
1875 * f.finite? # => true
1876 * f = 1.0/0.0 # => Infinity
1877 * f.finite? # => false
1878 * f = -1.0/0.0 # => -Infinity
1879 * f.finite? # => false
1880 * f = 0.0/0.0 # => NaN
1881 * f.finite? # => false
1882 *
1883 */
1884
1885VALUE
1886rb_flo_is_finite_p(VALUE num)
1887{
1888 double value = RFLOAT_VALUE(num);
1889
1890 return RBOOL(isfinite(value));
1891}
1892
1893static VALUE
1894flo_nextafter(VALUE flo, double value)
1895{
1896 double x, y;
1897 x = NUM2DBL(flo);
1898 y = nextafter(x, value);
1899 return DBL2NUM(y);
1900}
1901
1902/*
1903 * call-seq:
1904 * next_float -> float
1905 *
1906 * Returns the next-larger representable \Float.
1907 *
1908 * These examples show the internally stored values (64-bit hexadecimal)
1909 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
1910 *
1911 * f = 0.0 # 0x0000000000000000
1912 * f.next_float # 0x0000000000000001
1913 *
1914 * f = 0.01 # 0x3f847ae147ae147b
1915 * f.next_float # 0x3f847ae147ae147c
1916 *
1917 * In the remaining examples here, the output is shown in the usual way
1918 * (result +to_s+):
1919 *
1920 * 0.01.next_float # => 0.010000000000000002
1921 * 1.0.next_float # => 1.0000000000000002
1922 * 100.0.next_float # => 100.00000000000001
1923 *
1924 * f = 0.01
1925 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
1926 *
1927 * Output:
1928 *
1929 * 0 0x1.47ae147ae147bp-7 0.01
1930 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
1931 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
1932 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
1933 *
1934 * f = 0.0; 100.times { f += 0.1 }
1935 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
1936 * 10-f # => 1.9539925233402755e-14 # the floating point error.
1937 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
1938 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
1939 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
1940 * "%a" % 10 # => "0x1.4p+3"
1941 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
1942 *
1943 * Related: Float#prev_float
1944 *
1945 */
1946static VALUE
1947flo_next_float(VALUE vx)
1948{
1949 return flo_nextafter(vx, HUGE_VAL);
1950}
1951
1952/*
1953 * call-seq:
1954 * float.prev_float -> float
1955 *
1956 * Returns the next-smaller representable \Float.
1957 *
1958 * These examples show the internally stored values (64-bit hexadecimal)
1959 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
1960 *
1961 * f = 5e-324 # 0x0000000000000001
1962 * f.prev_float # 0x0000000000000000
1963 *
1964 * f = 0.01 # 0x3f847ae147ae147b
1965 * f.prev_float # 0x3f847ae147ae147a
1966 *
1967 * In the remaining examples here, the output is shown in the usual way
1968 * (result +to_s+):
1969 *
1970 * 0.01.prev_float # => 0.009999999999999998
1971 * 1.0.prev_float # => 0.9999999999999999
1972 * 100.0.prev_float # => 99.99999999999999
1973 *
1974 * f = 0.01
1975 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
1976 *
1977 * Output:
1978 *
1979 * 0 0x1.47ae147ae147bp-7 0.01
1980 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
1981 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
1982 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
1983 *
1984 * Related: Float#next_float.
1985 *
1986 */
1987static VALUE
1988flo_prev_float(VALUE vx)
1989{
1990 return flo_nextafter(vx, -HUGE_VAL);
1991}
1992
1993VALUE
1994rb_float_floor(VALUE num, int ndigits)
1995{
1996 double number;
1997 number = RFLOAT_VALUE(num);
1998 if (number == 0.0) {
1999 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2000 }
2001 if (ndigits > 0) {
2002 int binexp;
2003 double f, mul, res;
2004 frexp(number, &binexp);
2005 if (float_round_overflow(ndigits, binexp)) return num;
2006 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2007 return DBL2NUM(0.0);
2008 f = pow(10, ndigits);
2009 mul = floor(number * f);
2010 res = (mul + 1) / f;
2011 if (res > number)
2012 res = mul / f;
2013 return DBL2NUM(res);
2014 }
2015 else {
2016 num = dbl2ival(floor(number));
2017 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2018 return num;
2019 }
2020}
2021
2022static int
2023flo_ndigits(int argc, VALUE *argv)
2024{
2025 if (rb_check_arity(argc, 0, 1)) {
2026 return NUM2INT(argv[0]);
2027 }
2028 return 0;
2029}
2030
2031/*
2032 * :markup: markdown
2033 *
2034 * call-seq:
2035 * floor(ndigits = 0) -> float or integer
2036 *
2037 * Returns a float or integer that is a "floor" value for `self`,
2038 * as specified by `ndigits`,
2039 * which must be an
2040 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2041 *
2042 * When `self` is zero,
2043 * returns a zero value:
2044 * a float if `ndigits` is positive,
2045 * an integer otherwise:
2046 *
2047 * ```
2048 * f = 0.0 # => 0.0
2049 * f.floor(20) # => 0.0
2050 * f.floor(0) # => 0
2051 * f.floor(-20) # => 0
2052 * ```
2053 *
2054 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2055 * digits after the decimal point (as available):
2056 *
2057 * ```
2058 * f = 12345.6789
2059 * f.floor(1) # => 12345.6
2060 * f.floor(3) # => 12345.678
2061 * f.floor(30) # => 12345.6789
2062 * f = -12345.6789
2063 * f.floor(1) # => -12345.7
2064 * f.floor(3) # => -12345.679
2065 * f.floor(30) # => -12345.6789
2066 * ```
2067 *
2068 * When `self` is non-zero and `ndigits` is non-positive,
2069 * returns an integer value based on a computed granularity:
2070 *
2071 * - The granularity is `10 ** ndigits.abs`.
2072 * - The returned value is the largest multiple of the granularity
2073 * that is less than or equal to `self`.
2074 *
2075 * Examples with positive `self`:
2076 *
2077 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2078 * |--------:|------------:|--------------------------:|
2079 * | 0 | 1 | 12345 |
2080 * | -1 | 10 | 12340 |
2081 * | -2 | 100 | 12300 |
2082 * | -3 | 1000 | 12000 |
2083 * | -4 | 10000 | 10000 |
2084 * | -5 | 100000 | 0 |
2085 *
2086 * Examples with negative `self`:
2087 *
2088 * | ndigits | Granularity | -12345.6789.floor(ndigits) |
2089 * |--------:|------------:|---------------------------:|
2090 * | 0 | 1 | -12346 |
2091 * | -1 | 10 | -12350 |
2092 * | -2 | 100 | -12400 |
2093 * | -3 | 1000 | -13000 |
2094 * | -4 | 10000 | -20000 |
2095 * | -5 | 100000 | -100000 |
2096 * | -6 | 1000000 | -1000000 |
2097 *
2098 * Note that the limited precision of floating-point arithmetic
2099 * may lead to surprising results:
2100 *
2101 * ```
2102 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2103 * ```
2104 *
2105 * Related: Float#ceil.
2106 *
2107 */
2108
2109static VALUE
2110flo_floor(int argc, VALUE *argv, VALUE num)
2111{
2112 int ndigits = flo_ndigits(argc, argv);
2113 return rb_float_floor(num, ndigits);
2114}
2115
2116/*
2117 * :markup: markdown
2118 *
2119 * call-seq:
2120 * ceil(ndigits = 0) -> float or integer
2121 *
2122 * Returns a numeric that is a "ceiling" value for `self`,
2123 * as specified by the given `ndigits`,
2124 * which must be an
2125 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2126 *
2127 * When `ndigits` is positive, returns a Float with `ndigits`
2128 * decimal digits after the decimal point
2129 * (as available, but no fewer than 1):
2130 *
2131 * ```
2132 * f = 12345.6789
2133 * f.ceil(1) # => 12345.7
2134 * f.ceil(3) # => 12345.679
2135 * f.ceil(30) # => 12345.6789
2136 * f = -12345.6789
2137 * f.ceil(1) # => -12345.6
2138 * f.ceil(3) # => -12345.678
2139 * f.ceil(30) # => -12345.6789
2140 * f = 0.0
2141 * f.ceil(1) # => 0.0
2142 * f.ceil(100) # => 0.0
2143 * ```
2144 *
2145 * When `ndigits` is non-positive,
2146 * returns an Integer based on a computed granularity:
2147 *
2148 * - The granularity is `10 ** ndigits.abs`.
2149 * - The returned value is the largest multiple of the granularity
2150 * that is less than or equal to `self`.
2151 *
2152 * Examples with positive `self`:
2153 *
2154 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2155 * |--------:|------------:|-------------------------:|
2156 * | 0 | 1 | 12346 |
2157 * | -1 | 10 | 12350 |
2158 * | -2 | 100 | 12400 |
2159 * | -3 | 1000 | 13000 |
2160 * | -4 | 10000 | 20000 |
2161 * | -5 | 100000 | 100000 |
2162 *
2163 * Examples with negative `self`:
2164 *
2165 * | ndigits | Granularity | -12345.6789.ceil(ndigits) |
2166 * |--------:|------------:|--------------------------:|
2167 * | 0 | 1 | -12345 |
2168 * | -1 | 10 | -12340 |
2169 * | -2 | 100 | -12300 |
2170 * | -3 | 1000 | -12000 |
2171 * | -4 | 10000 | -10000 |
2172 * | -5 | 100000 | 0 |
2173 *
2174 * When `self` is zero and `ndigits` is non-positive,
2175 * returns Integer zero:
2176 *
2177 * ```
2178 * 0.0.ceil(0) # => 0
2179 * 0.0.ceil(-1) # => 0
2180 * 0.0.ceil(-2) # => 0
2181 * ```
2182 *
2183 * Note that the limited precision of floating-point arithmetic
2184 * may lead to surprising results:
2185 *
2186 * ```
2187 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2188 * ```
2189 *
2190 * Related: Float#floor.
2191 *
2192 */
2193
2194static VALUE
2195flo_ceil(int argc, VALUE *argv, VALUE num)
2196{
2197 int ndigits = flo_ndigits(argc, argv);
2198 return rb_float_ceil(num, ndigits);
2199}
2200
2201VALUE
2202rb_float_ceil(VALUE num, int ndigits)
2203{
2204 double number, f;
2205
2206 number = RFLOAT_VALUE(num);
2207 if (number == 0.0) {
2208 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2209 }
2210 if (ndigits > 0) {
2211 int binexp;
2212 frexp(number, &binexp);
2213 if (float_round_overflow(ndigits, binexp)) return num;
2214 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2215 return DBL2NUM(0.0);
2216 f = pow(10, ndigits);
2217 f = ceil(number * f) / f;
2218 return DBL2NUM(f);
2219 }
2220 else {
2221 num = dbl2ival(ceil(number));
2222 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2223 return num;
2224 }
2225}
2226
2227static int
2228int_round_zero_p(VALUE num, int ndigits)
2229{
2230 long bytes;
2231 /* If 10**N / 2 > num, then return 0 */
2232 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2233 if (FIXNUM_P(num)) {
2234 bytes = sizeof(long);
2235 }
2236 else if (RB_BIGNUM_TYPE_P(num)) {
2237 bytes = rb_big_size(num);
2238 }
2239 else {
2240 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2241 }
2242 return (-0.415241 * ndigits - 0.125 > bytes);
2243}
2244
2245static SIGNED_VALUE
2246int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2247{
2248 SIGNED_VALUE z = +(x + y / 2) / y;
2249 if ((z * y - x) * 2 == y) {
2250 z &= ~1;
2251 }
2252 return z * y;
2253}
2254
2255static SIGNED_VALUE
2256int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2257{
2258 return (x + y / 2) / y * y;
2259}
2260
2261static SIGNED_VALUE
2262int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2263{
2264 return (x + y / 2 - 1) / y * y;
2265}
2266
2267static int
2268int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2269{
2270 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2271}
2272
2273static int
2274int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2275{
2276 return int_pos_p(num);
2277}
2278
2279static int
2280int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2281{
2282 return int_neg_p(num);
2283}
2284
2285/*
2286 * Assumes num is an \Integer, ndigits <= 0
2287 */
2288static VALUE
2289rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2290{
2291 VALUE n, f, h, r;
2292
2293 if (int_round_zero_p(num, ndigits)) {
2294 return INT2FIX(0);
2295 }
2296
2297 f = int_pow(10, -ndigits);
2298 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2299 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2300 int neg = x < 0;
2301 if (neg) x = -x;
2302 x = ROUND_CALL(mode, int_round, (x, y));
2303 if (neg) x = -x;
2304 return LONG2NUM(x);
2305 }
2306 if (RB_FLOAT_TYPE_P(f)) {
2307 /* then int_pow overflow */
2308 return INT2FIX(0);
2309 }
2310 h = rb_int_idiv(f, INT2FIX(2));
2311 r = rb_int_modulo(num, f);
2312 n = rb_int_minus(num, r);
2313 r = rb_int_cmp(r, h);
2314 if (FIXNUM_POSITIVE_P(r) ||
2315 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2316 n = rb_int_plus(n, f);
2317 }
2318 return n;
2319}
2320
2321static VALUE
2322rb_int_floor(VALUE num, int ndigits)
2323{
2324 VALUE f = int_pow(10, -ndigits);
2325 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2326 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2327 int neg = x < 0;
2328 if (neg) x = -x + y - 1;
2329 x = x / y * y;
2330 if (neg) x = -x;
2331 return LONG2NUM(x);
2332 }
2333 else {
2334 bool neg = int_neg_p(num);
2335 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2336 num = rb_int_mul(rb_int_div(num, f), f);
2337 if (neg) num = rb_int_uminus(num);
2338 return num;
2339 }
2340}
2341
2342static VALUE
2343rb_int_ceil(VALUE num, int ndigits)
2344{
2345 VALUE f = int_pow(10, -ndigits);
2346 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2347 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2348 int neg = x < 0;
2349 if (neg) x = -x;
2350 else x += y - 1;
2351 x = (x / y) * y;
2352 if (neg) x = -x;
2353 return LONG2NUM(x);
2354 }
2355 else {
2356 bool neg = int_neg_p(num);
2357 if (neg)
2358 num = rb_int_uminus(num);
2359 else
2360 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2361 num = rb_int_mul(rb_int_div(num, f), f);
2362 if (neg) num = rb_int_uminus(num);
2363 return num;
2364 }
2365}
2366
2367VALUE
2368rb_int_truncate(VALUE num, int ndigits)
2369{
2370 VALUE f;
2371 VALUE m;
2372
2373 if (int_round_zero_p(num, ndigits))
2374 return INT2FIX(0);
2375 f = int_pow(10, -ndigits);
2376 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2377 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2378 int neg = x < 0;
2379 if (neg) x = -x;
2380 x = x / y * y;
2381 if (neg) x = -x;
2382 return LONG2NUM(x);
2383 }
2384 if (RB_FLOAT_TYPE_P(f)) {
2385 /* then int_pow overflow */
2386 return INT2FIX(0);
2387 }
2388 m = rb_int_modulo(num, f);
2389 if (int_neg_p(num)) {
2390 return rb_int_plus(num, rb_int_minus(f, m));
2391 }
2392 else {
2393 return rb_int_minus(num, m);
2394 }
2395}
2396
2397/*
2398 * call-seq:
2399 * round(ndigits = 0, half: :up) -> integer or float
2400 *
2401 * Returns +self+ rounded to the nearest value with
2402 * a precision of +ndigits+ decimal digits.
2403 *
2404 * When +ndigits+ is non-negative, returns a float with +ndigits+
2405 * after the decimal point (as available):
2406 *
2407 * f = 12345.6789
2408 * f.round(1) # => 12345.7
2409 * f.round(3) # => 12345.679
2410 * f = -12345.6789
2411 * f.round(1) # => -12345.7
2412 * f.round(3) # => -12345.679
2413 *
2414 * When +ndigits+ is negative, returns an integer
2415 * with at least <tt>ndigits.abs</tt> trailing zeros:
2416 *
2417 * f = 12345.6789
2418 * f.round(0) # => 12346
2419 * f.round(-3) # => 12000
2420 * f = -12345.6789
2421 * f.round(0) # => -12346
2422 * f.round(-3) # => -12000
2423 *
2424 * If keyword argument +half+ is given,
2425 * and +self+ is equidistant from the two candidate values,
2426 * the rounding is according to the given +half+ value:
2427 *
2428 * - +:up+ or +nil+: round away from zero:
2429 *
2430 * 2.5.round(half: :up) # => 3
2431 * 3.5.round(half: :up) # => 4
2432 * (-2.5).round(half: :up) # => -3
2433 *
2434 * - +:down+: round toward zero:
2435 *
2436 * 2.5.round(half: :down) # => 2
2437 * 3.5.round(half: :down) # => 3
2438 * (-2.5).round(half: :down) # => -2
2439 *
2440 * - +:even+: round toward the candidate whose last nonzero digit is even:
2441 *
2442 * 2.5.round(half: :even) # => 2
2443 * 3.5.round(half: :even) # => 4
2444 * (-2.5).round(half: :even) # => -2
2445 *
2446 * Raises and exception if the value for +half+ is invalid.
2447 *
2448 * Related: Float#truncate.
2449 *
2450 */
2451
2452static VALUE
2453flo_round(int argc, VALUE *argv, VALUE num)
2454{
2455 double number, f, x;
2456 VALUE nd, opt;
2457 int ndigits = 0;
2458 enum ruby_num_rounding_mode mode;
2459
2460 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2461 ndigits = NUM2INT(nd);
2462 }
2463 mode = rb_num_get_rounding_option(opt);
2464 number = RFLOAT_VALUE(num);
2465 if (number == 0.0) {
2466 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2467 }
2468 if (ndigits < 0) {
2469 return rb_int_round(flo_to_i(num), ndigits, mode);
2470 }
2471 if (ndigits == 0) {
2472 x = ROUND_CALL(mode, round, (number, 1.0));
2473 return dbl2ival(x);
2474 }
2475 if (isfinite(number)) {
2476 int binexp;
2477 frexp(number, &binexp);
2478 if (float_round_overflow(ndigits, binexp)) return num;
2479 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2480 if (ndigits > 14) {
2481 /* In this case, pow(10, ndigits) may not be accurate. */
2482 return rb_flo_round_by_rational(argc, argv, num);
2483 }
2484 f = pow(10, ndigits);
2485 x = ROUND_CALL(mode, round, (number, f));
2486 return DBL2NUM(x / f);
2487 }
2488 return num;
2489}
2490
2491static int
2492float_round_overflow(int ndigits, int binexp)
2493{
2494 enum {float_dig = DBL_DIG+2};
2495
2496/* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2497 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2498 Recall that up to float_dig digits can be needed to represent a double,
2499 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2500 will be an integer and thus the result is the original number.
2501 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2502 if ndigits + exp < 0, the result is 0.
2503 We have:
2504 2 ** (binexp-1) <= |number| < 2 ** binexp
2505 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2506 If binexp >= 0, and since log_2(10) = 3.322259:
2507 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2508 floor(binexp/4) <= exp <= ceil(binexp/3)
2509 If binexp <= 0, swap the /4 and the /3
2510 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2511 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2512*/
2513 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2514 return TRUE;
2515 }
2516 return FALSE;
2517}
2518
2519static int
2520float_round_underflow(int ndigits, int binexp)
2521{
2522 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2523 return TRUE;
2524 }
2525 return FALSE;
2526}
2527
2528/*
2529 * call-seq:
2530 * to_i -> integer
2531 *
2532 * Returns +self+ truncated to an Integer.
2533 *
2534 * 1.2.to_i # => 1
2535 * (-1.2).to_i # => -1
2536 *
2537 * Note that the limited precision of floating-point arithmetic
2538 * may lead to surprising results:
2539 *
2540 * (0.3 / 0.1).to_i # => 2 (!)
2541 *
2542 */
2543
2544static VALUE
2545flo_to_i(VALUE num)
2546{
2547 double f = RFLOAT_VALUE(num);
2548
2549 if (f > 0.0) f = floor(f);
2550 if (f < 0.0) f = ceil(f);
2551
2552 return dbl2ival(f);
2553}
2554
2555/*
2556 * call-seq:
2557 * truncate(ndigits = 0) -> float or integer
2558 *
2559 * Returns +self+ truncated (toward zero) to
2560 * a precision of +ndigits+ decimal digits.
2561 *
2562 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2563 * after the decimal point (as available):
2564 *
2565 * f = 12345.6789
2566 * f.truncate(1) # => 12345.6
2567 * f.truncate(3) # => 12345.678
2568 * f = -12345.6789
2569 * f.truncate(1) # => -12345.6
2570 * f.truncate(3) # => -12345.678
2571 *
2572 * When +ndigits+ is negative, returns an integer
2573 * with at least <tt>ndigits.abs</tt> trailing zeros:
2574 *
2575 * f = 12345.6789
2576 * f.truncate(0) # => 12345
2577 * f.truncate(-3) # => 12000
2578 * f = -12345.6789
2579 * f.truncate(0) # => -12345
2580 * f.truncate(-3) # => -12000
2581 *
2582 * Note that the limited precision of floating-point arithmetic
2583 * may lead to surprising results:
2584 *
2585 * (0.3 / 0.1).truncate #=> 2 (!)
2586 *
2587 * Related: Float#round.
2588 *
2589 */
2590static VALUE
2591flo_truncate(int argc, VALUE *argv, VALUE num)
2592{
2593 if (signbit(RFLOAT_VALUE(num)))
2594 return flo_ceil(argc, argv, num);
2595 else
2596 return flo_floor(argc, argv, num);
2597}
2598
2599/*
2600 * call-seq:
2601 * floor(ndigits = 0) -> float or integer
2602 *
2603 * Returns the largest float or integer that is less than or equal to +self+,
2604 * as specified by the given +ndigits+,
2605 * which must be an
2606 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2607 *
2608 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2609 *
2610 * Related: #ceil, Float#floor.
2611 */
2612
2613static VALUE
2614num_floor(int argc, VALUE *argv, VALUE num)
2615{
2616 return flo_floor(argc, argv, rb_Float(num));
2617}
2618
2619/*
2620 * call-seq:
2621 * ceil(ndigits = 0) -> float or integer
2622 *
2623 * Returns the smallest float or integer that is greater than or equal to +self+,
2624 * as specified by the given +ndigits+,
2625 * which must be an
2626 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2627 *
2628 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2629 *
2630 * Related: #floor, Float#ceil.
2631 */
2632
2633static VALUE
2634num_ceil(int argc, VALUE *argv, VALUE num)
2635{
2636 return flo_ceil(argc, argv, rb_Float(num));
2637}
2638
2639/*
2640 * call-seq:
2641 * round(digits = 0) -> integer or float
2642 *
2643 * Returns +self+ rounded to the nearest value with
2644 * a precision of +digits+ decimal digits.
2645 *
2646 * \Numeric implements this by converting +self+ to a Float and
2647 * invoking Float#round.
2648 */
2649
2650static VALUE
2651num_round(int argc, VALUE* argv, VALUE num)
2652{
2653 return flo_round(argc, argv, rb_Float(num));
2654}
2655
2656/*
2657 * call-seq:
2658 * truncate(digits = 0) -> integer or float
2659 *
2660 * Returns +self+ truncated (toward zero) to
2661 * a precision of +digits+ decimal digits.
2662 *
2663 * \Numeric implements this by converting +self+ to a Float and
2664 * invoking Float#truncate.
2665 */
2666
2667static VALUE
2668num_truncate(int argc, VALUE *argv, VALUE num)
2669{
2670 return flo_truncate(argc, argv, rb_Float(num));
2671}
2672
2673double
2674ruby_float_step_size(double beg, double end, double unit, int excl)
2675{
2676 const double epsilon = DBL_EPSILON;
2677 double d, n, err;
2678
2679 if (unit == 0) {
2680 return HUGE_VAL;
2681 }
2682 if (isinf(unit)) {
2683 return unit > 0 ? beg <= end : beg >= end;
2684 }
2685 n= (end - beg)/unit;
2686 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2687 if (err>0.5) err=0.5;
2688 if (excl) {
2689 if (n<=0) return 0;
2690 if (n<1)
2691 n = 0;
2692 else
2693 n = floor(n - err);
2694 d = +((n + 1) * unit) + beg;
2695 if (beg < end) {
2696 if (d < end)
2697 n++;
2698 }
2699 else if (beg > end) {
2700 if (d > end)
2701 n++;
2702 }
2703 }
2704 else {
2705 if (n<0) return 0;
2706 n = floor(n + err);
2707 d = +((n + 1) * unit) + beg;
2708 if (beg < end) {
2709 if (d <= end)
2710 n++;
2711 }
2712 else if (beg > end) {
2713 if (d >= end)
2714 n++;
2715 }
2716 }
2717 return n+1;
2718}
2719
2720int
2721ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2722{
2723 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2724 double unit = NUM2DBL(step);
2725 double beg = NUM2DBL(from);
2726 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2727 double n = ruby_float_step_size(beg, end, unit, excl);
2728 long i;
2729
2730 if (isinf(unit)) {
2731 /* if unit is infinity, i*unit+beg is NaN */
2732 if (n) rb_yield(DBL2NUM(beg));
2733 }
2734 else if (unit == 0) {
2735 VALUE val = DBL2NUM(beg);
2736 for (;;)
2737 rb_yield(val);
2738 }
2739 else {
2740 for (i=0; i<n; i++) {
2741 double d = i*unit+beg;
2742 if (unit >= 0 ? end < d : d < end) d = end;
2743 rb_yield(DBL2NUM(d));
2744 }
2745 }
2746 return TRUE;
2747 }
2748 return FALSE;
2749}
2750
2751VALUE
2752ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2753{
2754 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2755 long delta, diff;
2756
2757 diff = FIX2LONG(step);
2758 if (diff == 0) {
2759 return DBL2NUM(HUGE_VAL);
2760 }
2761 delta = FIX2LONG(to) - FIX2LONG(from);
2762 if (diff < 0) {
2763 diff = -diff;
2764 delta = -delta;
2765 }
2766 if (excl) {
2767 delta--;
2768 }
2769 if (delta < 0) {
2770 return INT2FIX(0);
2771 }
2772 return ULONG2NUM(delta / diff + 1UL);
2773 }
2774 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2775 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2776
2777 if (isinf(n)) return DBL2NUM(n);
2778 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2779 return rb_dbl2big(n);
2780 }
2781 else {
2782 VALUE result;
2783 ID cmp = '>';
2784 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2785 case 0: return DBL2NUM(HUGE_VAL);
2786 case -1: cmp = '<'; break;
2787 }
2788 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2789 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2790 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2791 result = rb_funcall(result, '+', 1, INT2FIX(1));
2792 }
2793 return result;
2794 }
2795}
2796
2797static int
2798num_step_negative_p(VALUE num)
2799{
2800 const ID mid = '<';
2801 VALUE zero = INT2FIX(0);
2802 VALUE r;
2803
2804 if (FIXNUM_P(num)) {
2805 if (method_basic_p(rb_cInteger))
2806 return (SIGNED_VALUE)num < 0;
2807 }
2808 else if (RB_BIGNUM_TYPE_P(num)) {
2809 if (method_basic_p(rb_cInteger))
2810 return BIGNUM_NEGATIVE_P(num);
2811 }
2812
2813 r = rb_check_funcall(num, '>', 1, &zero);
2814 if (UNDEF_P(r)) {
2815 coerce_failed(num, INT2FIX(0));
2816 }
2817 return !RTEST(r);
2818}
2819
2820static int
2821num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2822{
2823 VALUE hash;
2824
2825 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2826 if (!NIL_P(hash)) {
2827 ID keys[2];
2828 VALUE values[2];
2829 keys[0] = id_to;
2830 keys[1] = id_by;
2831 rb_get_kwargs(hash, keys, 0, 2, values);
2832 if (!UNDEF_P(values[0])) {
2833 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2834 *to = values[0];
2835 }
2836 if (!UNDEF_P(values[1])) {
2837 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2838 *by = values[1];
2839 }
2840 }
2841
2842 return argc;
2843}
2844
2845static int
2846num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2847{
2848 int desc;
2849 if (!UNDEF_P(by)) {
2850 *step = by;
2851 }
2852 else {
2853 /* compatibility */
2854 if (argc > 1 && NIL_P(*step)) {
2855 rb_raise(rb_eTypeError, "step must be numeric");
2856 }
2857 }
2858 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2859 rb_raise(rb_eArgError, "step can't be 0");
2860 }
2861 if (NIL_P(*step)) {
2862 *step = INT2FIX(1);
2863 }
2864 desc = num_step_negative_p(*step);
2865 if (fix_nil && NIL_P(*to)) {
2866 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2867 }
2868 return desc;
2869}
2870
2871static int
2872num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2873{
2874 VALUE by = Qundef;
2875 argc = num_step_extract_args(argc, argv, to, step, &by);
2876 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2877}
2878
2879static VALUE
2880num_step_size(VALUE from, VALUE args, VALUE eobj)
2881{
2882 VALUE to, step;
2883 int argc = args ? RARRAY_LENINT(args) : 0;
2884 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2885
2886 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2887
2888 return ruby_num_interval_step_size(from, to, step, FALSE);
2889}
2890
2891/*
2892 * call-seq:
2893 * step(to = nil, by = 1) {|n| ... } -> self
2894 * step(to = nil, by = 1) -> enumerator
2895 * step(to = nil, by: 1) {|n| ... } -> self
2896 * step(to = nil, by: 1) -> enumerator
2897 * step(by: 1, to: ) {|n| ... } -> self
2898 * step(by: 1, to: ) -> enumerator
2899 * step(by: , to: nil) {|n| ... } -> self
2900 * step(by: , to: nil) -> enumerator
2901 *
2902 * Generates a sequence of numbers; with a block given, traverses the sequence.
2903 *
2904 * Of the Core and Standard Library classes,
2905 * Integer, Float, and Rational use this implementation.
2906 *
2907 * A quick example:
2908 *
2909 * squares = []
2910 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2911 * squares # => [1, 9, 25, 49, 81]
2912 *
2913 * The generated sequence:
2914 *
2915 * - Begins with +self+.
2916 * - Continues at intervals of +by+ (which may not be zero).
2917 * - Ends with the last number that is within or equal to +to+;
2918 * that is, less than or equal to +to+ if +by+ is positive,
2919 * greater than or equal to +to+ if +by+ is negative.
2920 * If +to+ is +nil+, the sequence is of infinite length.
2921 *
2922 * If a block is given, calls the block with each number in the sequence;
2923 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2924 *
2925 * <b>Keyword Arguments</b>
2926 *
2927 * With keyword arguments +by+ and +to+,
2928 * their values (or defaults) determine the step and limit:
2929 *
2930 * # Both keywords given.
2931 * squares = []
2932 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2933 * squares # => [16, 36, 64, 100]
2934 * cubes = []
2935 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2936 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2937 * squares = []
2938 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2939 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2940 *
2941 * squares = []
2942 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2943 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2944 *
2945 * # Only keyword to given.
2946 * squares = []
2947 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
2948 * squares # => [16, 25, 36, 49, 64, 81, 100]
2949 * # Only by given.
2950 *
2951 * # Only keyword by given
2952 * squares = []
2953 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
2954 * squares # => [16, 36, 64, 100, 144]
2955 *
2956 * # No block given.
2957 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
2958 * e.class # => Enumerator::ArithmeticSequence
2959 *
2960 * <b>Positional Arguments</b>
2961 *
2962 * With optional positional arguments +to+ and +by+,
2963 * their values (or defaults) determine the step and limit:
2964 *
2965 * squares = []
2966 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
2967 * squares # => [16, 36, 64, 100]
2968 * squares = []
2969 * 4.step(10) {|i| squares.push(i*i) }
2970 * squares # => [16, 25, 36, 49, 64, 81, 100]
2971 * squares = []
2972 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
2973 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
2974 *
2975 * <b>Implementation Notes</b>
2976 *
2977 * If all the arguments are integers, the loop operates using an integer
2978 * counter.
2979 *
2980 * If any of the arguments are floating point numbers, all are converted
2981 * to floats, and the loop is executed
2982 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
2983 * where <i>n = (limit - self)/step</i>.
2984 *
2985 */
2986
2987static VALUE
2988num_step(int argc, VALUE *argv, VALUE from)
2989{
2990 VALUE to, step;
2991 int desc, inf;
2992
2993 if (!rb_block_given_p()) {
2994 VALUE by = Qundef;
2995
2996 num_step_extract_args(argc, argv, &to, &step, &by);
2997 if (!UNDEF_P(by)) {
2998 step = by;
2999 }
3000 if (NIL_P(step)) {
3001 step = INT2FIX(1);
3002 }
3003 else if (rb_equal(step, INT2FIX(0))) {
3004 rb_raise(rb_eArgError, "step can't be 0");
3005 }
3006 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3008 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3009 num_step_size, from, to, step, FALSE);
3010 }
3011
3012 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3013 }
3014
3015 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3016 if (rb_equal(step, INT2FIX(0))) {
3017 inf = 1;
3018 }
3019 else if (RB_FLOAT_TYPE_P(to)) {
3020 double f = RFLOAT_VALUE(to);
3021 inf = isinf(f) && (signbit(f) ? desc : !desc);
3022 }
3023 else inf = 0;
3024
3025 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3026 long i = FIX2LONG(from);
3027 long diff = FIX2LONG(step);
3028
3029 if (inf) {
3030 for (;; i += diff)
3031 rb_yield(LONG2FIX(i));
3032 }
3033 else {
3034 long end = FIX2LONG(to);
3035
3036 if (desc) {
3037 for (; i >= end; i += diff)
3038 rb_yield(LONG2FIX(i));
3039 }
3040 else {
3041 for (; i <= end; i += diff)
3042 rb_yield(LONG2FIX(i));
3043 }
3044 }
3045 }
3046 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3047 VALUE i = from;
3048
3049 if (inf) {
3050 for (;; i = rb_funcall(i, '+', 1, step))
3051 rb_yield(i);
3052 }
3053 else {
3054 ID cmp = desc ? '<' : '>';
3055
3056 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3057 rb_yield(i);
3058 }
3059 }
3060 return from;
3061}
3062
3063static char *
3064out_of_range_float(char (*pbuf)[24], VALUE val)
3065{
3066 char *const buf = *pbuf;
3067 char *s;
3068
3069 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3070 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3071 return buf;
3072}
3073
3074#define FLOAT_OUT_OF_RANGE(val, type) do { \
3075 char buf[24]; \
3076 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3077 out_of_range_float(&buf, (val))); \
3078} while (0)
3079
3080#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3081#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3082#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3083#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3084 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3085 LONG_MIN <= (n): \
3086 LONG_MIN_MINUS_ONE < (n))
3087
3088long
3090{
3091 again:
3092 if (NIL_P(val)) {
3093 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3094 }
3095
3096 if (FIXNUM_P(val)) return FIX2LONG(val);
3097
3098 else if (RB_FLOAT_TYPE_P(val)) {
3099 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3100 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3101 return (long)RFLOAT_VALUE(val);
3102 }
3103 else {
3104 FLOAT_OUT_OF_RANGE(val, "integer");
3105 }
3106 }
3107 else if (RB_BIGNUM_TYPE_P(val)) {
3108 return rb_big2long(val);
3109 }
3110 else {
3111 val = rb_to_int(val);
3112 goto again;
3113 }
3114}
3115
3116static unsigned long
3117rb_num2ulong_internal(VALUE val, int *wrap_p)
3118{
3119 again:
3120 if (NIL_P(val)) {
3121 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3122 }
3123
3124 if (FIXNUM_P(val)) {
3125 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3126 if (wrap_p)
3127 *wrap_p = l < 0;
3128 return (unsigned long)l;
3129 }
3130 else if (RB_FLOAT_TYPE_P(val)) {
3131 double d = RFLOAT_VALUE(val);
3132 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3133 if (wrap_p)
3134 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3135 if (0 <= d)
3136 return (unsigned long)d;
3137 return (unsigned long)(long)d;
3138 }
3139 else {
3140 FLOAT_OUT_OF_RANGE(val, "integer");
3141 }
3142 }
3143 else if (RB_BIGNUM_TYPE_P(val)) {
3144 {
3145 unsigned long ul = rb_big2ulong(val);
3146 if (wrap_p)
3147 *wrap_p = BIGNUM_NEGATIVE_P(val);
3148 return ul;
3149 }
3150 }
3151 else {
3152 val = rb_to_int(val);
3153 goto again;
3154 }
3155}
3156
3157unsigned long
3159{
3160 return rb_num2ulong_internal(val, NULL);
3161}
3162
3163void
3165{
3166 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3167 num, num < 0 ? "small" : "big");
3168}
3169
3170#if SIZEOF_INT < SIZEOF_LONG
3171static void
3172check_int(long num)
3173{
3174 if ((long)(int)num != num) {
3175 rb_out_of_int(num);
3176 }
3177}
3178
3179static void
3180check_uint(unsigned long num, int sign)
3181{
3182 if (sign) {
3183 /* minus */
3184 if (num < (unsigned long)INT_MIN)
3185 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3186 }
3187 else {
3188 /* plus */
3189 if (UINT_MAX < num)
3190 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3191 }
3192}
3193
3194long
3195rb_num2int(VALUE val)
3196{
3197 long num = rb_num2long(val);
3198
3199 check_int(num);
3200 return num;
3201}
3202
3203long
3204rb_fix2int(VALUE val)
3205{
3206 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3207
3208 check_int(num);
3209 return num;
3210}
3211
3212unsigned long
3213rb_num2uint(VALUE val)
3214{
3215 int wrap;
3216 unsigned long num = rb_num2ulong_internal(val, &wrap);
3217
3218 check_uint(num, wrap);
3219 return num;
3220}
3221
3222unsigned long
3223rb_fix2uint(VALUE val)
3224{
3225 unsigned long num;
3226
3227 if (!FIXNUM_P(val)) {
3228 return rb_num2uint(val);
3229 }
3230 num = FIX2ULONG(val);
3231
3232 check_uint(num, FIXNUM_NEGATIVE_P(val));
3233 return num;
3234}
3235#else
3236long
3238{
3239 return rb_num2long(val);
3240}
3241
3242long
3244{
3245 return FIX2INT(val);
3246}
3247
3248unsigned long
3250{
3251 return rb_num2ulong(val);
3252}
3253
3254unsigned long
3256{
3257 return RB_FIX2ULONG(val);
3258}
3259#endif
3260
3261NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3262static void
3263rb_out_of_short(SIGNED_VALUE num)
3264{
3265 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3266 num, num < 0 ? "small" : "big");
3267}
3268
3269static void
3270check_short(long num)
3271{
3272 if ((long)(short)num != num) {
3273 rb_out_of_short(num);
3274 }
3275}
3276
3277static void
3278check_ushort(unsigned long num, int sign)
3279{
3280 if (sign) {
3281 /* minus */
3282 if (num < (unsigned long)SHRT_MIN)
3283 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3284 }
3285 else {
3286 /* plus */
3287 if (USHRT_MAX < num)
3288 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3289 }
3290}
3291
3292short
3294{
3295 long num = rb_num2long(val);
3296
3297 check_short(num);
3298 return num;
3299}
3300
3301short
3303{
3304 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3305
3306 check_short(num);
3307 return num;
3308}
3309
3310unsigned short
3312{
3313 int wrap;
3314 unsigned long num = rb_num2ulong_internal(val, &wrap);
3315
3316 check_ushort(num, wrap);
3317 return num;
3318}
3319
3320unsigned short
3322{
3323 unsigned long num;
3324
3325 if (!FIXNUM_P(val)) {
3326 return rb_num2ushort(val);
3327 }
3328 num = FIX2ULONG(val);
3329
3330 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3331 return num;
3332}
3333
3334VALUE
3336{
3337 long v;
3338
3339 if (FIXNUM_P(val)) return val;
3340
3341 v = rb_num2long(val);
3342 if (!FIXABLE(v))
3343 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3344 return LONG2FIX(v);
3345}
3346
3347#if HAVE_LONG_LONG
3348
3349#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3350#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3351#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3352#ifndef ULLONG_MAX
3353#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3354#endif
3355#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3356 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3357 LLONG_MIN <= (n): \
3358 LLONG_MIN_MINUS_ONE < (n))
3359
3361rb_num2ll(VALUE val)
3362{
3363 if (NIL_P(val)) {
3364 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3365 }
3366
3367 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3368
3369 else if (RB_FLOAT_TYPE_P(val)) {
3370 double d = RFLOAT_VALUE(val);
3371 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3372 return (LONG_LONG)d;
3373 }
3374 else {
3375 FLOAT_OUT_OF_RANGE(val, "long long");
3376 }
3377 }
3378 else if (RB_BIGNUM_TYPE_P(val)) {
3379 return rb_big2ll(val);
3380 }
3381 else if (RB_TYPE_P(val, T_STRING)) {
3382 rb_raise(rb_eTypeError, "no implicit conversion from string");
3383 }
3384 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3385 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3386 }
3387
3388 val = rb_to_int(val);
3389 return NUM2LL(val);
3390}
3391
3392unsigned LONG_LONG
3393rb_num2ull(VALUE val)
3394{
3395 if (NIL_P(val)) {
3396 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3397 }
3398 else if (FIXNUM_P(val)) {
3399 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3400 }
3401 else if (RB_FLOAT_TYPE_P(val)) {
3402 double d = RFLOAT_VALUE(val);
3403 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3404 if (0 <= d)
3405 return (unsigned LONG_LONG)d;
3406 return (unsigned LONG_LONG)(LONG_LONG)d;
3407 }
3408 else {
3409 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3410 }
3411 }
3412 else if (RB_BIGNUM_TYPE_P(val)) {
3413 return rb_big2ull(val);
3414 }
3415 else {
3416 val = rb_to_int(val);
3417 return NUM2ULL(val);
3418 }
3419}
3420
3421#endif /* HAVE_LONG_LONG */
3422
3423// Conversion functions for unified 128-bit integer structures,
3424// These work with or without native 128-bit integer support.
3425
3426#ifndef HAVE_UINT128_T
3427// Helper function to build 128-bit value from bignum digits (fallback path).
3428static inline void
3429rb_uint128_from_bignum_digits_fallback(rb_uint128_t *result, BDIGIT *digits, size_t length)
3430{
3431 // Build the 128-bit value from bignum digits:
3432 for (long i = length - 1; i >= 0; i--) {
3433 // Shift both low and high parts:
3434 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3435 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3436 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3437 }
3438}
3439
3440// Helper function to convert absolute value of negative bignum to two's complement.
3441// Ruby stores negative bignums as absolute values, so we need to convert to two's complement.
3442static inline void
3443rb_uint128_twos_complement_negate(rb_uint128_t *value)
3444{
3445 if (value->parts.low == 0) {
3446 value->parts.high = ~value->parts.high + 1;
3447 }
3448 else {
3449 value->parts.low = ~value->parts.low + 1;
3450 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3451 }
3452}
3453#endif
3454
3456rb_numeric_to_uint128(VALUE x)
3457{
3458 rb_uint128_t result = {0};
3459 if (RB_FIXNUM_P(x)) {
3460 long value = RB_FIX2LONG(x);
3461 if (value < 0) {
3462 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3463 }
3464#ifdef HAVE_UINT128_T
3465 result.value = (uint128_t)value;
3466#else
3467 result.parts.low = (uint64_t)value;
3468 result.parts.high = 0;
3469#endif
3470 return result;
3471 }
3472 else if (RB_BIGNUM_TYPE_P(x)) {
3473 if (BIGNUM_NEGATIVE_P(x)) {
3474 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3475 }
3476 size_t length = BIGNUM_LEN(x);
3477#ifdef HAVE_UINT128_T
3478 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3479 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3480 }
3481 BDIGIT *digits = BIGNUM_DIGITS(x);
3482 result.value = 0;
3483 for (long i = length - 1; i >= 0; i--) {
3484 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3485 }
3486#else
3487 // Check if bignum fits in 128 bits (16 bytes)
3488 if (length > roomof(16, 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 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3493#endif
3494 return result;
3495 }
3496 else {
3497 rb_raise(rb_eTypeError, "not an integer");
3498 }
3499}
3500
3502rb_numeric_to_int128(VALUE x)
3503{
3504 rb_int128_t result = {0};
3505 if (RB_FIXNUM_P(x)) {
3506 long value = RB_FIX2LONG(x);
3507#ifdef HAVE_UINT128_T
3508 result.value = (int128_t)value;
3509#else
3510 if (value < 0) {
3511 // Two's complement representation: for negative values, sign extend
3512 // Convert to unsigned: for -1, we want all bits set
3513 result.parts.low = (uint64_t)value; // This will be the two's complement representation
3514 result.parts.high = UINT64_MAX; // Sign extend: all bits set for negative
3515 }
3516 else {
3517 result.parts.low = (uint64_t)value;
3518 result.parts.high = 0;
3519 }
3520#endif
3521 return result;
3522 }
3523 else if (RB_BIGNUM_TYPE_P(x)) {
3524 size_t length = BIGNUM_LEN(x);
3525#ifdef HAVE_UINT128_T
3526 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3527 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3528 }
3529 BDIGIT *digits = BIGNUM_DIGITS(x);
3530 uint128_t unsigned_result = 0;
3531 for (long i = length - 1; i >= 0; i--) {
3532 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3533 }
3534 if (BIGNUM_NEGATIVE_P(x)) {
3535 // Convert from two's complement
3536 // Maximum negative value is 2^127
3537 if (unsigned_result > ((uint128_t)1 << 127)) {
3538 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3539 }
3540 result.value = -(int128_t)(unsigned_result - 1) - 1;
3541 }
3542 else {
3543 // Maximum positive value is 2^127 - 1
3544 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3545 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3546 }
3547 result.value = (int128_t)unsigned_result;
3548 }
3549#else
3550 if (length > roomof(16, SIZEOF_BDIGIT)) {
3551 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3552 }
3553 BDIGIT *digits = BIGNUM_DIGITS(x);
3554 rb_uint128_t unsigned_result = {0};
3555 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3556 if (BIGNUM_NEGATIVE_P(x)) {
3557 // Check if value fits in signed 128-bit (max negative is 2^127)
3558 uint64_t max_neg_high = (uint64_t)1 << 63;
3559 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3560 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3561 }
3562 // Convert from absolute value to two's complement (Ruby stores negative as absolute value)
3563 rb_uint128_twos_complement_negate(&unsigned_result);
3564 result.parts.low = unsigned_result.parts.low;
3565 result.parts.high = (int64_t)unsigned_result.parts.high; // Sign extend
3566 }
3567 else {
3568 // Check if value fits in signed 128-bit (max positive is 2^127 - 1)
3569 // Max positive: high = 0x7FFFFFFFFFFFFFFF, low = 0xFFFFFFFFFFFFFFFF
3570 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3571 if (unsigned_result.parts.high > max_pos_high) {
3572 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3573 }
3574 result.parts.low = unsigned_result.parts.low;
3575 result.parts.high = unsigned_result.parts.high;
3576 }
3577#endif
3578 return result;
3579 }
3580 else {
3581 rb_raise(rb_eTypeError, "not an integer");
3582 }
3583}
3584
3585VALUE
3586rb_uint128_to_numeric(rb_uint128_t n)
3587{
3588#ifdef HAVE_UINT128_T
3589 if (n.value <= (uint128_t)RUBY_FIXNUM_MAX) {
3590 return LONG2FIX((long)n.value);
3591 }
3592 return rb_uint128t2big(n.value);
3593#else
3594 // If high part is zero and low part fits in fixnum
3595 if (n.parts.high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3596 return LONG2FIX((long)n.parts.low);
3597 }
3598 // Convert to bignum by building it from the two 64-bit parts
3599 VALUE bignum = rb_ull2big(n.parts.low);
3600 if (n.parts.high > 0) {
3601 VALUE high_bignum = rb_ull2big(n.parts.high);
3602 // Multiply high part by 2^64 and add to low part
3603 VALUE shifted_value = rb_int_lshift(high_bignum, INT2FIX(64));
3604 bignum = rb_int_plus(bignum, shifted_value);
3605 }
3606 return bignum;
3607#endif
3608}
3609
3610VALUE
3611rb_int128_to_numeric(rb_int128_t n)
3612{
3613#ifdef HAVE_UINT128_T
3614 if (FIXABLE(n.value)) {
3615 return LONG2FIX((long)n.value);
3616 }
3617 return rb_int128t2big(n.value);
3618#else
3619 int64_t high = (int64_t)n.parts.high;
3620 // If it's a small positive value that fits in fixnum
3621 if (high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3622 return LONG2FIX((long)n.parts.low);
3623 }
3624 // Check if it's negative (high bit of high part is set)
3625 if (high < 0) {
3626 // Negative value - convert from two's complement to absolute value
3627 rb_uint128_t unsigned_value = {0};
3628 if (n.parts.low == 0) {
3629 unsigned_value.parts.low = 0;
3630 unsigned_value.parts.high = ~n.parts.high + 1;
3631 }
3632 else {
3633 unsigned_value.parts.low = ~n.parts.low + 1;
3634 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3635 }
3636 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3637 return rb_int_uminus(bignum);
3638 }
3639 else {
3640 // Positive value
3641 union uint128_int128_conversion conversion = {
3642 .int128 = n
3643 };
3644 return rb_uint128_to_numeric(conversion.uint128);
3645 }
3646#endif
3647}
3648
3649/********************************************************************
3650 *
3651 * Document-class: Integer
3652 *
3653 * An \Integer object represents an integer value.
3654 *
3655 * You can create an \Integer object explicitly with:
3656 *
3657 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3658 *
3659 * You can convert certain objects to Integers with:
3660 *
3661 * - Method #Integer.
3662 *
3663 * An attempt to add a singleton method to an instance of this class
3664 * causes an exception to be raised.
3665 *
3666 * == What's Here
3667 *
3668 * First, what's elsewhere. Class \Integer:
3669 *
3670 * - Inherits from
3671 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3672 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3673 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3674 *
3675 * Here, class \Integer provides methods for:
3676 *
3677 * - {Querying}[rdoc-ref:Integer@Querying]
3678 * - {Comparing}[rdoc-ref:Integer@Comparing]
3679 * - {Converting}[rdoc-ref:Integer@Converting]
3680 * - {Other}[rdoc-ref:Integer@Other]
3681 *
3682 * === Querying
3683 *
3684 * - #allbits?: Returns whether all bits in +self+ are set.
3685 * - #anybits?: Returns whether any bits in +self+ are set.
3686 * - #nobits?: Returns whether no bits in +self+ are set.
3687 *
3688 * === Comparing
3689 *
3690 * - #<: Returns whether +self+ is less than the given value.
3691 * - #<=: Returns whether +self+ is less than or equal to the given value.
3692 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3693 * to, or greater than the given value.
3694 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3695 * value.
3696 * - #>: Returns whether +self+ is greater than the given value.
3697 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3698 *
3699 * === Converting
3700 *
3701 * - ::sqrt: Returns the integer square root of the given value.
3702 * - ::try_convert: Returns the given value converted to an \Integer.
3703 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3704 * - #&: Returns the bitwise AND of +self+ and the given value.
3705 * - #*: Returns the product of +self+ and the given value.
3706 * - #**: Returns the value of +self+ raised to the power of the given value.
3707 * - #+: Returns the sum of +self+ and the given value.
3708 * - #-: Returns the difference of +self+ and the given value.
3709 * - #/: Returns the quotient of +self+ and the given value.
3710 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3711 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3712 * - #[]: Returns a slice of bits from +self+.
3713 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3714 * - #|: Returns the bitwise OR of +self+ and the given value.
3715 * - #ceil: Returns the smallest number greater than or equal to +self+.
3716 * - #chr: Returns a 1-character string containing the character
3717 * represented by the value of +self+.
3718 * - #digits: Returns an array of integers representing the base-radix digits
3719 * of +self+.
3720 * - #div: Returns the integer result of dividing +self+ by the given value.
3721 * - #divmod: Returns a 2-element array containing the quotient and remainder
3722 * results of dividing +self+ by the given value.
3723 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3724 * - #floor: Returns the greatest number smaller than or equal to +self+.
3725 * - #pow: Returns the modular exponentiation of +self+.
3726 * - #pred: Returns the integer predecessor of +self+.
3727 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3728 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3729 * - #succ (aliased as #next): Returns the integer successor of +self+.
3730 * - #to_f: Returns +self+ converted to a Float.
3731 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3732 * representation of +self+ in the given radix.
3733 * - #truncate: Returns +self+ truncated to the given precision.
3734 *
3735 * === Other
3736 *
3737 * - #downto: Calls the given block with each integer value from +self+
3738 * down to the given value.
3739 * - #times: Calls the given block +self+ times with each integer
3740 * in <tt>(0..self-1)</tt>.
3741 * - #upto: Calls the given block with each integer value from +self+
3742 * up to the given value.
3743 *
3744 */
3745
3746VALUE
3747rb_int_odd_p(VALUE num)
3748{
3749 if (FIXNUM_P(num)) {
3750 return RBOOL(num & 2);
3751 }
3752 else {
3753 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3754 return rb_big_odd_p(num);
3755 }
3756}
3757
3758static VALUE
3759int_even_p(VALUE num)
3760{
3761 if (FIXNUM_P(num)) {
3762 return RBOOL((num & 2) == 0);
3763 }
3764 else {
3765 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3766 return rb_big_even_p(num);
3767 }
3768}
3769
3770VALUE
3771rb_int_even_p(VALUE num)
3772{
3773 return int_even_p(num);
3774}
3775
3776/*
3777 * call-seq:
3778 * allbits?(mask) -> true or false
3779 *
3780 * Returns +true+ if all bits that are set (=1) in +mask+
3781 * are also set in +self+; returns +false+ otherwise.
3782 *
3783 * Example values:
3784 *
3785 * 0b1010101 self
3786 * 0b1010100 mask
3787 * 0b1010100 self & mask
3788 * true self.allbits?(mask)
3789 *
3790 * 0b1010100 self
3791 * 0b1010101 mask
3792 * 0b1010100 self & mask
3793 * false self.allbits?(mask)
3794 *
3795 * Related: Integer#anybits?, Integer#nobits?.
3796 *
3797 */
3798
3799static VALUE
3800int_allbits_p(VALUE num, VALUE mask)
3801{
3802 mask = rb_to_int(mask);
3803 return rb_int_equal(rb_int_and(num, mask), mask);
3804}
3805
3806/*
3807 * call-seq:
3808 * anybits?(mask) -> true or false
3809 *
3810 * Returns +true+ if any bit that is set (=1) in +mask+
3811 * is also set in +self+; returns +false+ otherwise.
3812 *
3813 * Example values:
3814 *
3815 * 0b10000010 self
3816 * 0b11111111 mask
3817 * 0b10000010 self & mask
3818 * true self.anybits?(mask)
3819 *
3820 * 0b00000000 self
3821 * 0b11111111 mask
3822 * 0b00000000 self & mask
3823 * false self.anybits?(mask)
3824 *
3825 * Related: Integer#allbits?, Integer#nobits?.
3826 *
3827 */
3828
3829static VALUE
3830int_anybits_p(VALUE num, VALUE mask)
3831{
3832 mask = rb_to_int(mask);
3833 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3834}
3835
3836/*
3837 * call-seq:
3838 * nobits?(mask) -> true or false
3839 *
3840 * Returns +true+ if no bit that is set (=1) in +mask+
3841 * is also set in +self+; returns +false+ otherwise.
3842 *
3843 * Example values:
3844 *
3845 * 0b11110000 self
3846 * 0b00001111 mask
3847 * 0b00000000 self & mask
3848 * true self.nobits?(mask)
3849 *
3850 * 0b00000001 self
3851 * 0b11111111 mask
3852 * 0b00000001 self & mask
3853 * false self.nobits?(mask)
3854 *
3855 * Related: Integer#allbits?, Integer#anybits?.
3856 *
3857 */
3858
3859static VALUE
3860int_nobits_p(VALUE num, VALUE mask)
3861{
3862 mask = rb_to_int(mask);
3863 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3864}
3865
3866/*
3867 * call-seq:
3868 * succ -> next_integer
3869 *
3870 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3871 *
3872 * 1.succ #=> 2
3873 * -1.succ #=> 0
3874 *
3875 * Related: Integer#pred (predecessor value).
3876 */
3877
3878VALUE
3879rb_int_succ(VALUE num)
3880{
3881 if (FIXNUM_P(num)) {
3882 long i = FIX2LONG(num) + 1;
3883 return LONG2NUM(i);
3884 }
3885 if (RB_BIGNUM_TYPE_P(num)) {
3886 return rb_big_plus(num, INT2FIX(1));
3887 }
3888 return num_funcall1(num, '+', INT2FIX(1));
3889}
3890
3891#define int_succ rb_int_succ
3892
3893/*
3894 * call-seq:
3895 * pred -> next_integer
3896 *
3897 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3898 *
3899 * 1.pred #=> 0
3900 * -1.pred #=> -2
3901 *
3902 * Related: Integer#succ (successor value).
3903 *
3904 */
3905
3906static VALUE
3907rb_int_pred(VALUE num)
3908{
3909 if (FIXNUM_P(num)) {
3910 long i = FIX2LONG(num) - 1;
3911 return LONG2NUM(i);
3912 }
3913 if (RB_BIGNUM_TYPE_P(num)) {
3914 return rb_big_minus(num, INT2FIX(1));
3915 }
3916 return num_funcall1(num, '-', INT2FIX(1));
3917}
3918
3919#define int_pred rb_int_pred
3920
3921VALUE
3922rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3923{
3924 int n;
3925 VALUE str;
3926 switch (n = rb_enc_codelen(code, enc)) {
3927 case ONIGERR_INVALID_CODE_POINT_VALUE:
3928 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3929 break;
3930 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3931 case 0:
3932 rb_raise(rb_eRangeError, "%u out of char range", code);
3933 break;
3934 }
3935 str = rb_enc_str_new(0, n, enc);
3936 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3937 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3938 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3939 }
3940 return str;
3941}
3942
3943/* call-seq:
3944 * chr -> string
3945 * chr(encoding) -> string
3946 *
3947 * Returns a 1-character string containing the character
3948 * represented by the value of +self+, according to the given +encoding+.
3949 *
3950 * 65.chr # => "A"
3951 * 0.chr # => "\x00"
3952 * 255.chr # => "\xFF"
3953 * string = 255.chr(Encoding::UTF_8)
3954 * string.encoding # => Encoding::UTF_8
3955 *
3956 * Raises an exception if +self+ is negative.
3957 *
3958 * Related: Integer#ord.
3959 *
3960 */
3961
3962static VALUE
3963int_chr(int argc, VALUE *argv, VALUE num)
3964{
3965 char c;
3966 unsigned int i;
3967 rb_encoding *enc;
3968
3969 if (rb_num_to_uint(num, &i) == 0) {
3970 }
3971 else if (FIXNUM_P(num)) {
3972 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3973 }
3974 else {
3975 rb_raise(rb_eRangeError, "bignum out of char range");
3976 }
3977
3978 switch (argc) {
3979 case 0:
3980 if (0xff < i) {
3981 enc = rb_default_internal_encoding();
3982 if (!enc) {
3983 rb_raise(rb_eRangeError, "%u out of char range", i);
3984 }
3985 goto decode;
3986 }
3987 c = (char)i;
3988 if (i < 0x80) {
3989 return rb_usascii_str_new(&c, 1);
3990 }
3991 else {
3992 return rb_str_new(&c, 1);
3993 }
3994 case 1:
3995 break;
3996 default:
3997 rb_error_arity(argc, 0, 1);
3998 }
3999 enc = rb_to_encoding(argv[0]);
4000 if (!enc) enc = rb_ascii8bit_encoding();
4001 decode:
4002 return rb_enc_uint_chr(i, enc);
4003}
4004
4005/*
4006 * Fixnum
4007 */
4008
4009static VALUE
4010fix_uminus(VALUE num)
4011{
4012 return LONG2NUM(-FIX2LONG(num));
4013}
4014
4015VALUE
4016rb_int_uminus(VALUE num)
4017{
4018 if (FIXNUM_P(num)) {
4019 return fix_uminus(num);
4020 }
4021 else {
4022 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
4023 return rb_big_uminus(num);
4024 }
4025}
4026
4027VALUE
4028rb_fix2str(VALUE x, int base)
4029{
4030 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
4031 long val = FIX2LONG(x);
4032 unsigned long u;
4033 int neg = 0;
4034
4035 if (base < 2 || 36 < base) {
4036 rb_raise(rb_eArgError, "invalid radix %d", base);
4037 }
4038#if SIZEOF_LONG < SIZEOF_VOIDP
4039# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4040 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4041 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4042 rb_bug("Unnormalized Fixnum value %p", (void *)x);
4043 }
4044# else
4045 /* should do something like above code, but currently ruby does not know */
4046 /* such platforms */
4047# endif
4048#endif
4049 if (val == 0) {
4050 return rb_usascii_str_new2("0");
4051 }
4052 if (val < 0) {
4053 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
4054 neg = 1;
4055 }
4056 else {
4057 u = val;
4058 }
4059 do {
4060 *--b = ruby_digitmap[(int)(u % base)];
4061 } while (u /= base);
4062 if (neg) {
4063 *--b = '-';
4064 }
4065
4066 return rb_usascii_str_new(b, e - b);
4067}
4068
4069static VALUE rb_fix_to_s_static[10];
4070
4071VALUE
4072rb_fix_to_s(VALUE x)
4073{
4074 long i = FIX2LONG(x);
4075 if (i >= 0 && i < 10) {
4076 return rb_fix_to_s_static[i];
4077 }
4078 return rb_fix2str(x, 10);
4079}
4080
4081/*
4082 * call-seq:
4083 * to_s(base = 10) -> string
4084 *
4085 * Returns a string containing the place-value representation of +self+
4086 * in radix +base+ (in 2..36).
4087 *
4088 * 12345.to_s # => "12345"
4089 * 12345.to_s(2) # => "11000000111001"
4090 * 12345.to_s(8) # => "30071"
4091 * 12345.to_s(10) # => "12345"
4092 * 12345.to_s(16) # => "3039"
4093 * 12345.to_s(36) # => "9ix"
4094 * 78546939656932.to_s(36) # => "rubyrules"
4095 *
4096 * Raises an exception if +base+ is out of range.
4097 */
4098
4099VALUE
4100rb_int_to_s(int argc, VALUE *argv, VALUE x)
4101{
4102 int base;
4103
4104 if (rb_check_arity(argc, 0, 1))
4105 base = NUM2INT(argv[0]);
4106 else
4107 base = 10;
4108 return rb_int2str(x, base);
4109}
4110
4111VALUE
4112rb_int2str(VALUE x, int base)
4113{
4114 if (FIXNUM_P(x)) {
4115 return rb_fix2str(x, base);
4116 }
4117 else if (RB_BIGNUM_TYPE_P(x)) {
4118 return rb_big2str(x, base);
4119 }
4120
4121 return rb_any_to_s(x);
4122}
4123
4124static VALUE
4125fix_plus(VALUE x, VALUE y)
4126{
4127 if (FIXNUM_P(y)) {
4128 return rb_fix_plus_fix(x, y);
4129 }
4130 else if (RB_BIGNUM_TYPE_P(y)) {
4131 return rb_big_plus(y, x);
4132 }
4133 else if (RB_FLOAT_TYPE_P(y)) {
4134 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4135 }
4136 else if (RB_TYPE_P(y, T_COMPLEX)) {
4137 return rb_complex_plus(y, x);
4138 }
4139 else {
4140 return rb_num_coerce_bin(x, y, '+');
4141 }
4142}
4143
4144VALUE
4145rb_fix_plus(VALUE x, VALUE y)
4146{
4147 return fix_plus(x, y);
4148}
4149
4150/*
4151 * call-seq:
4152 * self + other -> numeric
4153 *
4154 * Returns the sum of +self+ and +other+:
4155 *
4156 * 1 + 1 # => 2
4157 * 1 + -1 # => 0
4158 * 1 + 0 # => 1
4159 * 1 + -2 # => -1
4160 * 1 + Complex(1, 0) # => (2+0i)
4161 * 1 + Rational(1, 1) # => (2/1)
4162 *
4163 * For a computation involving Floats, the result may be inexact (see Float#+):
4164 *
4165 * 1 + 3.14 # => 4.140000000000001
4166 */
4167
4168VALUE
4169rb_int_plus(VALUE x, VALUE y)
4170{
4171 if (FIXNUM_P(x)) {
4172 return fix_plus(x, y);
4173 }
4174 else if (RB_BIGNUM_TYPE_P(x)) {
4175 return rb_big_plus(x, y);
4176 }
4177 return rb_num_coerce_bin(x, y, '+');
4178}
4179
4180static VALUE
4181fix_minus(VALUE x, VALUE y)
4182{
4183 if (FIXNUM_P(y)) {
4184 return rb_fix_minus_fix(x, y);
4185 }
4186 else if (RB_BIGNUM_TYPE_P(y)) {
4187 x = rb_int2big(FIX2LONG(x));
4188 return rb_big_minus(x, y);
4189 }
4190 else if (RB_FLOAT_TYPE_P(y)) {
4191 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4192 }
4193 else {
4194 return rb_num_coerce_bin(x, y, '-');
4195 }
4196}
4197
4198/*
4199 * call-seq:
4200 * self - other -> numeric
4201 *
4202 * Returns the difference of +self+ and +other+:
4203 *
4204 * 4 - 2 # => 2
4205 * -4 - 2 # => -6
4206 * -4 - -2 # => -2
4207 * 4 - 2.0 # => 2.0
4208 * 4 - Rational(2, 1) # => (2/1)
4209 * 4 - Complex(2, 0) # => (2+0i)
4210 *
4211 */
4212
4213VALUE
4214rb_int_minus(VALUE x, VALUE y)
4215{
4216 if (FIXNUM_P(x)) {
4217 return fix_minus(x, y);
4218 }
4219 else if (RB_BIGNUM_TYPE_P(x)) {
4220 return rb_big_minus(x, y);
4221 }
4222 return rb_num_coerce_bin(x, y, '-');
4223}
4224
4225
4226#define SQRT_LONG_MAX HALF_LONG_MSB
4227/*tests if N*N would overflow*/
4228#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4229
4230static VALUE
4231fix_mul(VALUE x, VALUE y)
4232{
4233 if (FIXNUM_P(y)) {
4234 return rb_fix_mul_fix(x, y);
4235 }
4236 else if (RB_BIGNUM_TYPE_P(y)) {
4237 switch (x) {
4238 case INT2FIX(0): return x;
4239 case INT2FIX(1): return y;
4240 }
4241 return rb_big_mul(y, x);
4242 }
4243 else if (RB_FLOAT_TYPE_P(y)) {
4244 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4245 }
4246 else if (RB_TYPE_P(y, T_COMPLEX)) {
4247 return rb_complex_mul(y, x);
4248 }
4249 else {
4250 return rb_num_coerce_bin(x, y, '*');
4251 }
4252}
4253
4254/*
4255 * call-seq:
4256 * self * other -> numeric
4257 *
4258 * Returns the numeric product of +self+ and +other+:
4259 *
4260 * 4 * 2 # => 8
4261 * -4 * 2 # => -8
4262 * 4 * -2 # => -8
4263 * 4 * 2.0 # => 8.0
4264 * 4 * Rational(1, 3) # => (4/3)
4265 * 4 * Complex(2, 0) # => (8+0i)
4266 *
4267 */
4268
4269VALUE
4270rb_int_mul(VALUE x, VALUE y)
4271{
4272 if (FIXNUM_P(x)) {
4273 return fix_mul(x, y);
4274 }
4275 else if (RB_BIGNUM_TYPE_P(x)) {
4276 return rb_big_mul(x, y);
4277 }
4278 return rb_num_coerce_bin(x, y, '*');
4279}
4280
4281static double
4282fix_fdiv_double(VALUE x, VALUE y)
4283{
4284 if (FIXNUM_P(y)) {
4285 long iy = FIX2LONG(y);
4286#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4287 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4288 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4289 }
4290#endif
4291 return double_div_double(FIX2LONG(x), iy);
4292 }
4293 else if (RB_BIGNUM_TYPE_P(y)) {
4294 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4295 }
4296 else if (RB_FLOAT_TYPE_P(y)) {
4297 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4298 }
4299 else {
4300 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4301 }
4302}
4303
4304double
4305rb_int_fdiv_double(VALUE x, VALUE y)
4306{
4307 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) {
4308 VALUE gcd = rb_gcd(x, y);
4309 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4310 x = rb_int_idiv(x, gcd);
4311 y = rb_int_idiv(y, gcd);
4312 }
4313 }
4314 if (FIXNUM_P(x)) {
4315 return fix_fdiv_double(x, y);
4316 }
4317 else if (RB_BIGNUM_TYPE_P(x)) {
4318 return rb_big_fdiv_double(x, y);
4319 }
4320 else {
4321 return nan("");
4322 }
4323}
4324
4325/*
4326 * call-seq:
4327 * fdiv(numeric) -> float
4328 *
4329 * Returns the Float result of dividing +self+ by +numeric+:
4330 *
4331 * 4.fdiv(2) # => 2.0
4332 * 4.fdiv(-2) # => -2.0
4333 * -4.fdiv(2) # => -2.0
4334 * 4.fdiv(2.0) # => 2.0
4335 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4336 *
4337 * Raises an exception if +numeric+ cannot be converted to a Float.
4338 *
4339 */
4340
4341VALUE
4342rb_int_fdiv(VALUE x, VALUE y)
4343{
4344 if (RB_INTEGER_TYPE_P(x)) {
4345 return DBL2NUM(rb_int_fdiv_double(x, y));
4346 }
4347 return Qnil;
4348}
4349
4350static VALUE
4351fix_divide(VALUE x, VALUE y, ID op)
4352{
4353 if (FIXNUM_P(y)) {
4354 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4355 return rb_fix_div_fix(x, y);
4356 }
4357 else if (RB_BIGNUM_TYPE_P(y)) {
4358 x = rb_int2big(FIX2LONG(x));
4359 return rb_big_div(x, y);
4360 }
4361 else if (RB_FLOAT_TYPE_P(y)) {
4362 if (op == '/') {
4363 double d = FIX2LONG(x);
4364 return rb_flo_div_flo(DBL2NUM(d), y);
4365 }
4366 else {
4367 VALUE v;
4368 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4369 v = fix_divide(x, y, '/');
4370 return flo_floor(0, 0, v);
4371 }
4372 }
4373 else {
4374 if (RB_TYPE_P(y, T_RATIONAL) &&
4375 op == '/' && FIX2LONG(x) == 1)
4376 return rb_rational_reciprocal(y);
4377 return rb_num_coerce_bin(x, y, op);
4378 }
4379}
4380
4381static VALUE
4382fix_div(VALUE x, VALUE y)
4383{
4384 return fix_divide(x, y, '/');
4385}
4386
4387/*
4388 * call-seq:
4389 * self / numeric -> numeric_result
4390 *
4391 * Performs division; for integer +numeric+, truncates the result to an integer:
4392 *
4393 * 4 / 3 # => 1
4394 * 4 / -3 # => -2
4395 * -4 / 3 # => -2
4396 * -4 / -3 # => 1
4397 *
4398 * For other +numeric+, returns non-integer result:
4399 *
4400 * 4 / 3.0 # => 1.3333333333333333
4401 * 4 / Rational(3, 1) # => (4/3)
4402 * 4 / Complex(3, 0) # => ((4/3)+0i)
4403 *
4404 */
4405
4406VALUE
4407rb_int_div(VALUE x, VALUE y)
4408{
4409 if (FIXNUM_P(x)) {
4410 return fix_div(x, y);
4411 }
4412 else if (RB_BIGNUM_TYPE_P(x)) {
4413 return rb_big_div(x, y);
4414 }
4415 return Qnil;
4416}
4417
4418static VALUE
4419fix_idiv(VALUE x, VALUE y)
4420{
4421 return fix_divide(x, y, id_div);
4422}
4423
4424/*
4425 * call-seq:
4426 * div(numeric) -> integer
4427 *
4428 * Performs integer division; returns the integer result of dividing +self+
4429 * by +numeric+:
4430 *
4431 * 4.div(3) # => 1
4432 * 4.div(-3) # => -2
4433 * -4.div(3) # => -2
4434 * -4.div(-3) # => 1
4435 * 4.div(3.0) # => 1
4436 * 4.div(Rational(3, 1)) # => 1
4437 *
4438 * Raises an exception if +numeric+ does not have method +div+.
4439 *
4440 */
4441
4442VALUE
4443rb_int_idiv(VALUE x, VALUE y)
4444{
4445 if (FIXNUM_P(x)) {
4446 return fix_idiv(x, y);
4447 }
4448 else if (RB_BIGNUM_TYPE_P(x)) {
4449 return rb_big_idiv(x, y);
4450 }
4451 return num_div(x, y);
4452}
4453
4454static VALUE
4455fix_mod(VALUE x, VALUE y)
4456{
4457 if (FIXNUM_P(y)) {
4458 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4459 return rb_fix_mod_fix(x, y);
4460 }
4461 else if (RB_BIGNUM_TYPE_P(y)) {
4462 x = rb_int2big(FIX2LONG(x));
4463 return rb_big_modulo(x, y);
4464 }
4465 else if (RB_FLOAT_TYPE_P(y)) {
4466 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4467 }
4468 else {
4469 return rb_num_coerce_bin(x, y, '%');
4470 }
4471}
4472
4473/*
4474 * call-seq:
4475 * self % other -> real_numeric
4476 *
4477 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
4478 *
4479 * For integer +n+ and real number +r+, these expressions are equivalent:
4480 *
4481 * n % r
4482 * n-r*(n/r).floor
4483 * n.divmod(r)[1]
4484 *
4485 * See Numeric#divmod.
4486 *
4487 * Examples:
4488 *
4489 * 10 % 2 # => 0
4490 * 10 % 3 # => 1
4491 * 10 % 4 # => 2
4492 *
4493 * 10 % -2 # => 0
4494 * 10 % -3 # => -2
4495 * 10 % -4 # => -2
4496 *
4497 * 10 % 3.0 # => 1.0
4498 * 10 % Rational(3, 1) # => (1/1)
4499 *
4500 */
4501VALUE
4502rb_int_modulo(VALUE x, VALUE y)
4503{
4504 if (FIXNUM_P(x)) {
4505 return fix_mod(x, y);
4506 }
4507 else if (RB_BIGNUM_TYPE_P(x)) {
4508 return rb_big_modulo(x, y);
4509 }
4510 return num_modulo(x, y);
4511}
4512
4513/*
4514 * call-seq:
4515 * remainder(other) -> real_number
4516 *
4517 * Returns the remainder after dividing +self+ by +other+.
4518 *
4519 * Examples:
4520 *
4521 * 11.remainder(4) # => 3
4522 * 11.remainder(-4) # => 3
4523 * -11.remainder(4) # => -3
4524 * -11.remainder(-4) # => -3
4525 *
4526 * 12.remainder(4) # => 0
4527 * 12.remainder(-4) # => 0
4528 * -12.remainder(4) # => 0
4529 * -12.remainder(-4) # => 0
4530 *
4531 * 13.remainder(4.0) # => 1.0
4532 * 13.remainder(Rational(4, 1)) # => (1/1)
4533 *
4534 */
4535
4536static VALUE
4537int_remainder(VALUE x, VALUE y)
4538{
4539 if (FIXNUM_P(x)) {
4540 if (FIXNUM_P(y)) {
4541 VALUE z = fix_mod(x, y);
4543 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4544 z = fix_minus(z, y);
4545 return z;
4546 }
4547 else if (!RB_BIGNUM_TYPE_P(y)) {
4548 return num_remainder(x, y);
4549 }
4550 x = rb_int2big(FIX2LONG(x));
4551 }
4552 else if (!RB_BIGNUM_TYPE_P(x)) {
4553 return Qnil;
4554 }
4555 return rb_big_remainder(x, y);
4556}
4557
4558static VALUE
4559fix_divmod(VALUE x, VALUE y)
4560{
4561 if (FIXNUM_P(y)) {
4562 VALUE div, mod;
4563 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4564 rb_fix_divmod_fix(x, y, &div, &mod);
4565 return rb_assoc_new(div, mod);
4566 }
4567 else if (RB_BIGNUM_TYPE_P(y)) {
4568 x = rb_int2big(FIX2LONG(x));
4569 return rb_big_divmod(x, y);
4570 }
4571 else if (RB_FLOAT_TYPE_P(y)) {
4572 {
4573 double div, mod;
4574 volatile VALUE a, b;
4575
4576 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4577 a = dbl2ival(div);
4578 b = DBL2NUM(mod);
4579 return rb_assoc_new(a, b);
4580 }
4581 }
4582 else {
4583 return rb_num_coerce_bin(x, y, id_divmod);
4584 }
4585}
4586
4587/*
4588 * call-seq:
4589 * divmod(other) -> array
4590 *
4591 * Returns a 2-element array <tt>[q, r]</tt>, where
4592 *
4593 * q = (self/other).floor # Quotient
4594 * r = self % other # Remainder
4595 *
4596 * Examples:
4597 *
4598 * 11.divmod(4) # => [2, 3]
4599 * 11.divmod(-4) # => [-3, -1]
4600 * -11.divmod(4) # => [-3, 1]
4601 * -11.divmod(-4) # => [2, -3]
4602 *
4603 * 12.divmod(4) # => [3, 0]
4604 * 12.divmod(-4) # => [-3, 0]
4605 * -12.divmod(4) # => [-3, 0]
4606 * -12.divmod(-4) # => [3, 0]
4607 *
4608 * 13.divmod(4.0) # => [3, 1.0]
4609 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4610 *
4611 */
4612VALUE
4613rb_int_divmod(VALUE x, VALUE y)
4614{
4615 if (FIXNUM_P(x)) {
4616 return fix_divmod(x, y);
4617 }
4618 else if (RB_BIGNUM_TYPE_P(x)) {
4619 return rb_big_divmod(x, y);
4620 }
4621 return Qnil;
4622}
4623
4624/*
4625 * call-seq:
4626 * self ** exponent -> numeric
4627 *
4628 * Returns +self+ raised to the power +exponent+:
4629 *
4630 * 2 ** 3 # => 8
4631 * 2 ** -3 # => (1/8)
4632 * -2 ** 3 # => -8
4633 * -2 ** -3 # => (-1/8)
4634 * 2 ** 3.3 # => 9.849155306759329
4635 * 2 ** Rational(3, 1) # => (8/1)
4636 * 2 ** Complex(3, 0) # => (8+0i)
4637 *
4638 */
4639
4640static VALUE
4641int_pow(long x, unsigned long y)
4642{
4643 int neg = x < 0;
4644 long z = 1;
4645
4646 if (y == 0) return INT2FIX(1);
4647 if (y == 1) return LONG2NUM(x);
4648 if (neg) x = -x;
4649 if (y & 1)
4650 z = x;
4651 else
4652 neg = 0;
4653 y &= ~1;
4654 do {
4655 while (y % 2 == 0) {
4656 if (!FIT_SQRT_LONG(x)) {
4657 goto bignum;
4658 }
4659 x = x * x;
4660 y >>= 1;
4661 }
4662 {
4663 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4664 goto bignum;
4665 }
4666 z = x * z;
4667 }
4668 } while (--y);
4669 if (neg) z = -z;
4670 return LONG2NUM(z);
4671
4672 VALUE v;
4673 bignum:
4674 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4675 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4676 return v;
4677 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4678 return v;
4679}
4680
4681VALUE
4682rb_int_positive_pow(long x, unsigned long y)
4683{
4684 return int_pow(x, y);
4685}
4686
4687static VALUE
4688fix_pow_inverted(VALUE x, VALUE minusb)
4689{
4690 if (x == INT2FIX(0)) {
4693 }
4694 else {
4695 VALUE y = rb_int_pow(x, minusb);
4696
4697 if (RB_FLOAT_TYPE_P(y)) {
4698 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4699 return DBL2NUM(1.0 / d);
4700 }
4701 else {
4702 return rb_rational_raw(INT2FIX(1), y);
4703 }
4704 }
4705}
4706
4707static VALUE
4708fix_pow(VALUE x, VALUE y)
4709{
4710 long a = FIX2LONG(x);
4711
4712 if (FIXNUM_P(y)) {
4713 long b = FIX2LONG(y);
4714
4715 if (a == 1) return INT2FIX(1);
4716 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4717 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4718 if (b == 0) return INT2FIX(1);
4719 if (b == 1) return x;
4720 if (a == 0) return INT2FIX(0);
4721 return int_pow(a, b);
4722 }
4723 else if (RB_BIGNUM_TYPE_P(y)) {
4724 if (a == 1) return INT2FIX(1);
4725 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4726 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4727 if (a == 0) return INT2FIX(0);
4728 x = rb_int2big(FIX2LONG(x));
4729 return rb_big_pow(x, y);
4730 }
4731 else if (RB_FLOAT_TYPE_P(y)) {
4732 double dy = RFLOAT_VALUE(y);
4733 if (dy == 0.0) return DBL2NUM(1.0);
4734 if (a == 0) {
4735 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4736 }
4737 if (a == 1) return DBL2NUM(1.0);
4738 if (a < 0 && dy != round(dy))
4739 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4740 return DBL2NUM(pow((double)a, dy));
4741 }
4742 else {
4743 return rb_num_coerce_bin(x, y, idPow);
4744 }
4745}
4746
4747/*
4748 * call-seq:
4749 * self ** exponent -> numeric
4750 *
4751 * Returns +self+ raised to the power +exponent+:
4752 *
4753 * # Result for non-negative Integer exponent is Integer.
4754 * 2 ** 0 # => 1
4755 * 2 ** 1 # => 2
4756 * 2 ** 2 # => 4
4757 * 2 ** 3 # => 8
4758 * -2 ** 3 # => -8
4759 * # Result for negative Integer exponent is Rational, not Float.
4760 * 2 ** -3 # => (1/8)
4761 * -2 ** -3 # => (-1/8)
4762 *
4763 * # Result for Float exponent is Float.
4764 * 2 ** 0.0 # => 1.0
4765 * 2 ** 1.0 # => 2.0
4766 * 2 ** 2.0 # => 4.0
4767 * 2 ** 3.0 # => 8.0
4768 * -2 ** 3.0 # => -8.0
4769 * 2 ** -3.0 # => 0.125
4770 * -2 ** -3.0 # => -0.125
4771 *
4772 * # Result for non-negative Complex exponent is Complex with Integer parts.
4773 * 2 ** Complex(0, 0) # => (1+0i)
4774 * 2 ** Complex(1, 0) # => (2+0i)
4775 * 2 ** Complex(2, 0) # => (4+0i)
4776 * 2 ** Complex(3, 0) # => (8+0i)
4777 * -2 ** Complex(3, 0) # => (-8+0i)
4778 * # Result for negative Complex exponent is Complex with Rational parts.
4779 * 2 ** Complex(-3, 0) # => ((1/8)+(0/1)*i)
4780 * -2 ** Complex(-3, 0) # => ((-1/8)+(0/1)*i)
4781 *
4782 * # Result for Rational exponent is Rational.
4783 * 2 ** Rational(0, 1) # => (1/1)
4784 * 2 ** Rational(1, 1) # => (2/1)
4785 * 2 ** Rational(2, 1) # => (4/1)
4786 * 2 ** Rational(3, 1) # => (8/1)
4787 * -2 ** Rational(3, 1) # => (-8/1)
4788 * 2 ** Rational(-3, 1) # => (1/8)
4789 * -2 ** Rational(-3, 1) # => (-1/8)
4790 *
4791 */
4792VALUE
4793rb_int_pow(VALUE x, VALUE y)
4794{
4795 if (FIXNUM_P(x)) {
4796 return fix_pow(x, y);
4797 }
4798 else if (RB_BIGNUM_TYPE_P(x)) {
4799 return rb_big_pow(x, y);
4800 }
4801 return Qnil;
4802}
4803
4804VALUE
4805rb_num_pow(VALUE x, VALUE y)
4806{
4807 VALUE z = rb_int_pow(x, y);
4808 if (!NIL_P(z)) return z;
4809 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4810 if (SPECIAL_CONST_P(x)) return Qnil;
4811 switch (BUILTIN_TYPE(x)) {
4812 case T_COMPLEX:
4813 return rb_complex_pow(x, y);
4814 case T_RATIONAL:
4815 return rb_rational_pow(x, y);
4816 default:
4817 break;
4818 }
4819 return Qnil;
4820}
4821
4822static VALUE
4823fix_equal(VALUE x, VALUE y)
4824{
4825 if (x == y) return Qtrue;
4826 if (FIXNUM_P(y)) return Qfalse;
4827 else if (RB_BIGNUM_TYPE_P(y)) {
4828 return rb_big_eq(y, x);
4829 }
4830 else if (RB_FLOAT_TYPE_P(y)) {
4831 return rb_integer_float_eq(x, y);
4832 }
4833 else {
4834 return num_equal(x, y);
4835 }
4836}
4837
4838/*
4839 * call-seq:
4840 * self == other -> true or false
4841 *
4842 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4843 *
4844 * 1 == 2 #=> false
4845 * 1 == 1.0 #=> true
4846 *
4847 * Related: Integer#eql? (requires +other+ to be an \Integer).
4848 */
4849
4850VALUE
4851rb_int_equal(VALUE x, VALUE y)
4852{
4853 if (FIXNUM_P(x)) {
4854 return fix_equal(x, y);
4855 }
4856 else if (RB_BIGNUM_TYPE_P(x)) {
4857 return rb_big_eq(x, y);
4858 }
4859 return Qnil;
4860}
4861
4862static VALUE
4863fix_cmp(VALUE x, VALUE y)
4864{
4865 if (x == y) return INT2FIX(0);
4866 if (FIXNUM_P(y)) {
4867 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4868 return INT2FIX(-1);
4869 }
4870 else if (RB_BIGNUM_TYPE_P(y)) {
4871 VALUE cmp = rb_big_cmp(y, x);
4872 switch (cmp) {
4873 case INT2FIX(+1): return INT2FIX(-1);
4874 case INT2FIX(-1): return INT2FIX(+1);
4875 }
4876 return cmp;
4877 }
4878 else if (RB_FLOAT_TYPE_P(y)) {
4879 return rb_integer_float_cmp(x, y);
4880 }
4881 else {
4882 return rb_num_coerce_cmp(x, y, id_cmp);
4883 }
4884}
4885
4886/*
4887 * call-seq:
4888 * self <=> other -> -1, 0, +1, or nil
4889 *
4890 * Returns:
4891 *
4892 * - -1, if +self+ is less than +other+.
4893 * - 0, if +self+ is equal to +other+.
4894 * - 1, if +self+ is greater then +other+.
4895 * - +nil+, if +self+ and +other+ are incomparable.
4896 *
4897 * Examples:
4898 *
4899 * 1 <=> 2 # => -1
4900 * 1 <=> 1 # => 0
4901 * 1 <=> 0 # => 1
4902 * 1 <=> 'foo' # => nil
4903 *
4904 * 1 <=> 1.0 # => 0
4905 * 1 <=> Rational(1, 1) # => 0
4906 * 1 <=> Complex(1, 0) # => 0
4907 *
4908 * This method is the basis for comparisons in module Comparable.
4909 *
4910 */
4911
4912VALUE
4913rb_int_cmp(VALUE x, VALUE y)
4914{
4915 if (FIXNUM_P(x)) {
4916 return fix_cmp(x, y);
4917 }
4918 else if (RB_BIGNUM_TYPE_P(x)) {
4919 return rb_big_cmp(x, y);
4920 }
4921 else {
4922 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
4923 }
4924}
4925
4926static VALUE
4927fix_gt(VALUE x, VALUE y)
4928{
4929 if (FIXNUM_P(y)) {
4930 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4931 }
4932 else if (RB_BIGNUM_TYPE_P(y)) {
4933 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4934 }
4935 else if (RB_FLOAT_TYPE_P(y)) {
4936 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
4937 }
4938 else {
4939 return rb_num_coerce_relop(x, y, '>');
4940 }
4941}
4942
4943/*
4944 * call-seq:
4945 * self > other -> true or false
4946 *
4947 * Returns +true+ if the value of +self+ is greater than that of +other+:
4948 *
4949 * 1 > 0 # => true
4950 * 1 > 1 # => false
4951 * 1 > 2 # => false
4952 * 1 > 0.5 # => true
4953 * 1 > Rational(1, 2) # => true
4954 *
4955 * Raises an exception if the comparison cannot be made.
4956 *
4957 */
4958
4959VALUE
4960rb_int_gt(VALUE x, VALUE y)
4961{
4962 if (FIXNUM_P(x)) {
4963 return fix_gt(x, y);
4964 }
4965 else if (RB_BIGNUM_TYPE_P(x)) {
4966 return rb_big_gt(x, y);
4967 }
4968 return Qnil;
4969}
4970
4971static VALUE
4972fix_ge(VALUE x, VALUE y)
4973{
4974 if (FIXNUM_P(y)) {
4975 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
4976 }
4977 else if (RB_BIGNUM_TYPE_P(y)) {
4978 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
4979 }
4980 else if (RB_FLOAT_TYPE_P(y)) {
4981 VALUE rel = rb_integer_float_cmp(x, y);
4982 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
4983 }
4984 else {
4985 return rb_num_coerce_relop(x, y, idGE);
4986 }
4987}
4988
4989/*
4990 * call-seq:
4991 * self >= real -> true or false
4992 *
4993 * Returns +true+ if the value of +self+ is greater than or equal to
4994 * that of +other+:
4995 *
4996 * 1 >= 0 # => true
4997 * 1 >= 1 # => true
4998 * 1 >= 2 # => false
4999 * 1 >= 0.5 # => true
5000 * 1 >= Rational(1, 2) # => true
5001 *
5002 * Raises an exception if the comparison cannot be made.
5003 *
5004 */
5005
5006VALUE
5007rb_int_ge(VALUE x, VALUE y)
5008{
5009 if (FIXNUM_P(x)) {
5010 return fix_ge(x, y);
5011 }
5012 else if (RB_BIGNUM_TYPE_P(x)) {
5013 return rb_big_ge(x, y);
5014 }
5015 return Qnil;
5016}
5017
5018static VALUE
5019fix_lt(VALUE x, VALUE y)
5020{
5021 if (FIXNUM_P(y)) {
5022 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
5023 }
5024 else if (RB_BIGNUM_TYPE_P(y)) {
5025 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
5026 }
5027 else if (RB_FLOAT_TYPE_P(y)) {
5028 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
5029 }
5030 else {
5031 return rb_num_coerce_relop(x, y, '<');
5032 }
5033}
5034
5035/*
5036 * call-seq:
5037 * self < other -> true or false
5038 *
5039 * Returns +true+ if the value of +self+ is less than that of +other+:
5040 *
5041 * 1 < 0 # => false
5042 * 1 < 1 # => false
5043 * 1 < 2 # => true
5044 * 1 < 0.5 # => false
5045 * 1 < Rational(1, 2) # => false
5046 *
5047 * Raises an exception if the comparison cannot be made.
5048 *
5049 */
5050
5051static VALUE
5052int_lt(VALUE x, VALUE y)
5053{
5054 if (FIXNUM_P(x)) {
5055 return fix_lt(x, y);
5056 }
5057 else if (RB_BIGNUM_TYPE_P(x)) {
5058 return rb_big_lt(x, y);
5059 }
5060 return Qnil;
5061}
5062
5063static VALUE
5064fix_le(VALUE x, VALUE y)
5065{
5066 if (FIXNUM_P(y)) {
5067 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
5068 }
5069 else if (RB_BIGNUM_TYPE_P(y)) {
5070 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
5071 }
5072 else if (RB_FLOAT_TYPE_P(y)) {
5073 VALUE rel = rb_integer_float_cmp(x, y);
5074 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
5075 }
5076 else {
5077 return rb_num_coerce_relop(x, y, idLE);
5078 }
5079}
5080
5081/*
5082 * call-seq:
5083 * self <= real -> true or false
5084 *
5085 * Returns +true+ if the value of +self+ is less than or equal to
5086 * that of +other+:
5087 *
5088 * 1 <= 0 # => false
5089 * 1 <= 1 # => true
5090 * 1 <= 2 # => true
5091 * 1 <= 0.5 # => false
5092 * 1 <= Rational(1, 2) # => false
5093 *
5094 * Raises an exception if the comparison cannot be made.
5095 *
5096 */
5097
5098static VALUE
5099int_le(VALUE x, VALUE y)
5100{
5101 if (FIXNUM_P(x)) {
5102 return fix_le(x, y);
5103 }
5104 else if (RB_BIGNUM_TYPE_P(x)) {
5105 return rb_big_le(x, y);
5106 }
5107 return Qnil;
5108}
5109
5110static VALUE
5111fix_comp(VALUE num)
5112{
5113 return ~num | FIXNUM_FLAG;
5114}
5115
5116VALUE
5117rb_int_comp(VALUE num)
5118{
5119 if (FIXNUM_P(num)) {
5120 return fix_comp(num);
5121 }
5122 else if (RB_BIGNUM_TYPE_P(num)) {
5123 return rb_big_comp(num);
5124 }
5125 return Qnil;
5126}
5127
5128static VALUE
5129num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
5130{
5131 ID func = (ID)((VALUE *)arg)[0];
5132 VALUE x = ((VALUE *)arg)[1];
5133 if (recursive) {
5134 num_funcall_op_1_recursion(x, func, y);
5135 }
5136 return rb_check_funcall(x, func, 1, &y);
5137}
5138
5139VALUE
5141{
5142 VALUE ret, args[3];
5143
5144 args[0] = (VALUE)func;
5145 args[1] = x;
5146 args[2] = y;
5147 do_coerce(&args[1], &args[2], TRUE);
5148 ret = rb_exec_recursive_paired(num_funcall_bit_1,
5149 args[2], args[1], (VALUE)args);
5150 if (UNDEF_P(ret)) {
5151 /* show the original object, not coerced object */
5152 coerce_failed(x, y);
5153 }
5154 return ret;
5155}
5156
5157static VALUE
5158fix_and(VALUE x, VALUE y)
5159{
5160 if (FIXNUM_P(y)) {
5161 long val = FIX2LONG(x) & FIX2LONG(y);
5162 return LONG2NUM(val);
5163 }
5164
5165 if (RB_BIGNUM_TYPE_P(y)) {
5166 return rb_big_and(y, x);
5167 }
5168
5169 return rb_num_coerce_bit(x, y, '&');
5170}
5171
5172/*
5173 * call-seq:
5174 * self & other -> integer
5175 *
5176 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5177 * in +self+ and +other+ are 1, 0 otherwise:
5178 *
5179 * "%04b" % (0b0101 & 0b0110) # => "0100"
5180 *
5181 * Raises an exception if +other+ is not an \Integer.
5182 *
5183 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5184 *
5185 */
5186
5187VALUE
5188rb_int_and(VALUE x, VALUE y)
5189{
5190 if (FIXNUM_P(x)) {
5191 return fix_and(x, y);
5192 }
5193 else if (RB_BIGNUM_TYPE_P(x)) {
5194 return rb_big_and(x, y);
5195 }
5196 return Qnil;
5197}
5198
5199static VALUE
5200fix_or(VALUE x, VALUE y)
5201{
5202 if (FIXNUM_P(y)) {
5203 long val = FIX2LONG(x) | FIX2LONG(y);
5204 return LONG2NUM(val);
5205 }
5206
5207 if (RB_BIGNUM_TYPE_P(y)) {
5208 return rb_big_or(y, x);
5209 }
5210
5211 return rb_num_coerce_bit(x, y, '|');
5212}
5213
5214/*
5215 * call-seq:
5216 * self | other -> integer
5217 *
5218 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5219 * in +self+ or +other+ is 1, 0 otherwise:
5220 *
5221 * "%04b" % (0b0101 | 0b0110) # => "0111"
5222 *
5223 * Raises an exception if +other+ is not an \Integer.
5224 *
5225 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5226 *
5227 */
5228
5229static VALUE
5230int_or(VALUE x, VALUE y)
5231{
5232 if (FIXNUM_P(x)) {
5233 return fix_or(x, y);
5234 }
5235 else if (RB_BIGNUM_TYPE_P(x)) {
5236 return rb_big_or(x, y);
5237 }
5238 return Qnil;
5239}
5240
5241static VALUE
5242fix_xor(VALUE x, VALUE y)
5243{
5244 if (FIXNUM_P(y)) {
5245 long val = FIX2LONG(x) ^ FIX2LONG(y);
5246 return LONG2NUM(val);
5247 }
5248
5249 if (RB_BIGNUM_TYPE_P(y)) {
5250 return rb_big_xor(y, x);
5251 }
5252
5253 return rb_num_coerce_bit(x, y, '^');
5254}
5255
5256/*
5257 * call-seq:
5258 * self ^ other -> integer
5259 *
5260 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5261 * in +self+ and +other+ are different, 0 otherwise:
5262 *
5263 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5264 *
5265 * Raises an exception if +other+ is not an \Integer.
5266 *
5267 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5268 *
5269 */
5270
5271VALUE
5272rb_int_xor(VALUE x, VALUE y)
5273{
5274 if (FIXNUM_P(x)) {
5275 return fix_xor(x, y);
5276 }
5277 else if (RB_BIGNUM_TYPE_P(x)) {
5278 return rb_big_xor(x, y);
5279 }
5280 return Qnil;
5281}
5282
5283static VALUE
5284rb_fix_lshift(VALUE x, VALUE y)
5285{
5286 long val, width;
5287
5288 val = NUM2LONG(x);
5289 if (!val) return (rb_to_int(y), INT2FIX(0));
5290 if (!FIXNUM_P(y))
5291 return rb_big_lshift(rb_int2big(val), y);
5292 width = FIX2LONG(y);
5293 if (width < 0)
5294 return fix_rshift(val, (unsigned long)-width);
5295 return fix_lshift(val, width);
5296}
5297
5298static VALUE
5299fix_lshift(long val, unsigned long width)
5300{
5301 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5302 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5303 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5304 }
5305 val = val << width;
5306 return LONG2NUM(val);
5307}
5308
5309/*
5310 * call-seq:
5311 * self << count -> integer
5312 *
5313 * Returns +self+ with bits shifted +count+ positions to the left,
5314 * or to the right if +count+ is negative:
5315 *
5316 * n = 0b11110000
5317 * "%08b" % (n << 1) # => "111100000"
5318 * "%08b" % (n << 3) # => "11110000000"
5319 * "%08b" % (n << -1) # => "01111000"
5320 * "%08b" % (n << -3) # => "00011110"
5321 *
5322 * Related: Integer#>>.
5323 *
5324 */
5325
5326VALUE
5327rb_int_lshift(VALUE x, VALUE y)
5328{
5329 if (FIXNUM_P(x)) {
5330 return rb_fix_lshift(x, y);
5331 }
5332 else if (RB_BIGNUM_TYPE_P(x)) {
5333 return rb_big_lshift(x, y);
5334 }
5335 return Qnil;
5336}
5337
5338static VALUE
5339rb_fix_rshift(VALUE x, VALUE y)
5340{
5341 long i, val;
5342
5343 val = FIX2LONG(x);
5344 if (!val) return (rb_to_int(y), INT2FIX(0));
5345 if (!FIXNUM_P(y))
5346 return rb_big_rshift(rb_int2big(val), y);
5347 i = FIX2LONG(y);
5348 if (i == 0) return x;
5349 if (i < 0)
5350 return fix_lshift(val, (unsigned long)-i);
5351 return fix_rshift(val, i);
5352}
5353
5354static VALUE
5355fix_rshift(long val, unsigned long i)
5356{
5357 if (i >= sizeof(long)*CHAR_BIT-1) {
5358 if (val < 0) return INT2FIX(-1);
5359 return INT2FIX(0);
5360 }
5361 val = RSHIFT(val, i);
5362 return LONG2FIX(val);
5363}
5364
5365/*
5366 * call-seq:
5367 * self >> count -> integer
5368 *
5369 * Returns +self+ with bits shifted +count+ positions to the right,
5370 * or to the left if +count+ is negative:
5371 *
5372 * n = 0b11110000
5373 * "%08b" % (n >> 1) # => "01111000"
5374 * "%08b" % (n >> 3) # => "00011110"
5375 * "%08b" % (n >> -1) # => "111100000"
5376 * "%08b" % (n >> -3) # => "11110000000"
5377 *
5378 * Related: Integer#<<.
5379 *
5380 */
5381
5382VALUE
5383rb_int_rshift(VALUE x, VALUE y)
5384{
5385 if (FIXNUM_P(x)) {
5386 return rb_fix_rshift(x, y);
5387 }
5388 else if (RB_BIGNUM_TYPE_P(x)) {
5389 return rb_big_rshift(x, y);
5390 }
5391 return Qnil;
5392}
5393
5394VALUE
5395rb_fix_aref(VALUE fix, VALUE idx)
5396{
5397 long val = FIX2LONG(fix);
5398 long i;
5399
5400 idx = rb_to_int(idx);
5401 if (!FIXNUM_P(idx)) {
5402 idx = rb_big_norm(idx);
5403 if (!FIXNUM_P(idx)) {
5404 if (!BIGNUM_SIGN(idx) || val >= 0)
5405 return INT2FIX(0);
5406 return INT2FIX(1);
5407 }
5408 }
5409 i = FIX2LONG(idx);
5410
5411 if (i < 0) return INT2FIX(0);
5412 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5413 if (val < 0) return INT2FIX(1);
5414 return INT2FIX(0);
5415 }
5416 if (val & (1L<<i))
5417 return INT2FIX(1);
5418 return INT2FIX(0);
5419}
5420
5421
5422/* copied from "r_less" in range.c */
5423/* compares _a_ and _b_ and returns:
5424 * < 0: a < b
5425 * = 0: a = b
5426 * > 0: a > b or non-comparable
5427 */
5428static int
5429compare_indexes(VALUE a, VALUE b)
5430{
5431 VALUE r = rb_funcall(a, id_cmp, 1, b);
5432
5433 if (NIL_P(r))
5434 return INT_MAX;
5435 return rb_cmpint(r, a, b);
5436}
5437
5438static VALUE
5439generate_mask(VALUE len)
5440{
5441 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5442}
5443
5444static VALUE
5445int_aref2(VALUE num, VALUE beg, VALUE len)
5446{
5447 if (RB_TYPE_P(num, T_BIGNUM)) {
5448 return rb_big_aref2(num, beg, len);
5449 }
5450 else {
5451 num = rb_int_rshift(num, beg);
5452 VALUE mask = generate_mask(len);
5453 return rb_int_and(num, mask);
5454 }
5455}
5456
5457static VALUE
5458int_aref1(VALUE num, VALUE arg)
5459{
5460 VALUE beg, end;
5461 int excl;
5462
5463 if (rb_range_values(arg, &beg, &end, &excl)) {
5464 if (NIL_P(beg)) {
5465 /* beginless range */
5466 if (!RTEST(num_negative_p(end))) {
5467 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5468 VALUE mask = generate_mask(end);
5469 if (int_zero_p(rb_int_and(num, mask))) {
5470 return INT2FIX(0);
5471 }
5472 else {
5473 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5474 }
5475 }
5476 else {
5477 return INT2FIX(0);
5478 }
5479 }
5480
5481 int cmp = compare_indexes(beg, end);
5482 if (!NIL_P(end) && cmp < 0) {
5483 VALUE len = rb_int_minus(end, beg);
5484 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5485 return int_aref2(num, beg, len);
5486 }
5487 else if (cmp == 0) {
5488 if (excl) return INT2FIX(0);
5489 arg = beg;
5490 goto one_bit;
5491 }
5492 return rb_int_rshift(num, beg);
5493 }
5494
5495one_bit:
5496 if (FIXNUM_P(num)) {
5497 return rb_fix_aref(num, arg);
5498 }
5499 else if (RB_BIGNUM_TYPE_P(num)) {
5500 return rb_big_aref(num, arg);
5501 }
5502 return Qnil;
5503}
5504
5505/*
5506 * call-seq:
5507 * self[offset] -> 0 or 1
5508 * self[offset, size] -> integer
5509 * self[range] -> integer
5510 *
5511 * Returns a slice of bits from +self+.
5512 *
5513 * With argument +offset+, returns the bit at the given offset,
5514 * where offset 0 refers to the least significant bit:
5515 *
5516 * n = 0b10 # => 2
5517 * n[0] # => 0
5518 * n[1] # => 1
5519 * n[2] # => 0
5520 * n[3] # => 0
5521 *
5522 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5523 * Thus, negative index always returns zero:
5524 *
5525 * 255[-1] # => 0
5526 *
5527 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5528 * beginning at +offset+ and including bits of greater significance:
5529 *
5530 * n = 0b111000 # => 56
5531 * "%010b" % n[0, 10] # => "0000111000"
5532 * "%010b" % n[4, 10] # => "0000000011"
5533 *
5534 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5535 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5536 *
5537 * n = 0b111000 # => 56
5538 * "%010b" % n[0..9] # => "0000111000"
5539 * "%010b" % n[4..9] # => "0000000011"
5540 *
5541 * Raises an exception if the slice cannot be constructed.
5542 */
5543
5544static VALUE
5545int_aref(int const argc, VALUE * const argv, VALUE const num)
5546{
5547 rb_check_arity(argc, 1, 2);
5548 if (argc == 2) {
5549 return int_aref2(num, argv[0], argv[1]);
5550 }
5551 return int_aref1(num, argv[0]);
5552
5553 return Qnil;
5554}
5555
5556/*
5557 * call-seq:
5558 * to_f -> float
5559 *
5560 * Converts +self+ to a Float:
5561 *
5562 * 1.to_f # => 1.0
5563 * -1.to_f # => -1.0
5564 *
5565 * If the value of +self+ does not fit in a Float,
5566 * the result is infinity:
5567 *
5568 * (10**400).to_f # => Infinity
5569 * (-10**400).to_f # => -Infinity
5570 *
5571 */
5572
5573static VALUE
5574int_to_f(VALUE num)
5575{
5576 double val;
5577
5578 if (FIXNUM_P(num)) {
5579 val = (double)FIX2LONG(num);
5580 }
5581 else if (RB_BIGNUM_TYPE_P(num)) {
5582 val = rb_big2dbl(num);
5583 }
5584 else {
5585 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5586 }
5587
5588 return DBL2NUM(val);
5589}
5590
5591static VALUE
5592fix_abs(VALUE fix)
5593{
5594 long i = FIX2LONG(fix);
5595
5596 if (i < 0) i = -i;
5597
5598 return LONG2NUM(i);
5599}
5600
5601VALUE
5602rb_int_abs(VALUE num)
5603{
5604 if (FIXNUM_P(num)) {
5605 return fix_abs(num);
5606 }
5607 else if (RB_BIGNUM_TYPE_P(num)) {
5608 return rb_big_abs(num);
5609 }
5610 return Qnil;
5611}
5612
5613static VALUE
5614fix_size(VALUE fix)
5615{
5616 return INT2FIX(sizeof(long));
5617}
5618
5619VALUE
5620rb_int_size(VALUE num)
5621{
5622 if (FIXNUM_P(num)) {
5623 return fix_size(num);
5624 }
5625 else if (RB_BIGNUM_TYPE_P(num)) {
5626 return rb_big_size_m(num);
5627 }
5628 return Qnil;
5629}
5630
5631static VALUE
5632rb_fix_bit_length(VALUE fix)
5633{
5634 long v = FIX2LONG(fix);
5635 if (v < 0)
5636 v = ~v;
5637 return LONG2FIX(bit_length(v));
5638}
5639
5640VALUE
5641rb_int_bit_length(VALUE num)
5642{
5643 if (FIXNUM_P(num)) {
5644 return rb_fix_bit_length(num);
5645 }
5646 else if (RB_BIGNUM_TYPE_P(num)) {
5647 return rb_big_bit_length(num);
5648 }
5649 return Qnil;
5650}
5651
5652static VALUE
5653rb_fix_digits(VALUE fix, long base)
5654{
5655 VALUE digits;
5656 long x = FIX2LONG(fix);
5657
5658 RUBY_ASSERT(x >= 0);
5659
5660 if (base < 2)
5661 rb_raise(rb_eArgError, "invalid radix %ld", base);
5662
5663 if (x == 0)
5664 return rb_ary_new_from_args(1, INT2FIX(0));
5665
5666 digits = rb_ary_new();
5667 while (x >= base) {
5668 long q = x % base;
5669 rb_ary_push(digits, LONG2NUM(q));
5670 x /= base;
5671 }
5672 rb_ary_push(digits, LONG2NUM(x));
5673
5674 return digits;
5675}
5676
5677static VALUE
5678rb_int_digits_bigbase(VALUE num, VALUE base)
5679{
5680 VALUE digits, bases;
5681
5682 RUBY_ASSERT(!rb_num_negative_p(num));
5683
5684 if (RB_BIGNUM_TYPE_P(base))
5685 base = rb_big_norm(base);
5686
5687 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5688 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5689 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5690 rb_raise(rb_eArgError, "negative radix");
5691
5692 if (FIXNUM_P(base) && FIXNUM_P(num))
5693 return rb_fix_digits(num, FIX2LONG(base));
5694
5695 if (FIXNUM_P(num))
5696 return rb_ary_new_from_args(1, num);
5697
5698 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5699 digits = rb_ary_new();
5700 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5701 VALUE qr = rb_int_divmod(num, base);
5702 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5703 num = RARRAY_AREF(qr, 0);
5704 }
5705 return digits;
5706 }
5707
5708 bases = rb_ary_new();
5709 for (VALUE b = base; int_le(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5710 rb_ary_push(bases, b);
5711 }
5712 digits = rb_ary_new_from_args(1, num);
5713 while (RARRAY_LEN(bases)) {
5714 VALUE b = rb_ary_pop(bases);
5715 long i, last_idx = RARRAY_LEN(digits) - 1;
5716 for(i = last_idx; i >= 0; i--) {
5717 VALUE n = RARRAY_AREF(digits, i);
5718 VALUE divmod = rb_int_divmod(n, b);
5719 VALUE div = RARRAY_AREF(divmod, 0);
5720 VALUE mod = RARRAY_AREF(divmod, 1);
5721 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5722 rb_ary_store(digits, 2 * i, mod);
5723 }
5724 }
5725
5726 return digits;
5727}
5728
5729/*
5730 * call-seq:
5731 * digits(base = 10) -> array_of_integers
5732 *
5733 * Returns an array of integers representing the +base+-radix
5734 * digits of +self+;
5735 * the first element of the array represents the least significant digit:
5736 *
5737 * 12345.digits # => [5, 4, 3, 2, 1]
5738 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5739 * 12345.digits(100) # => [45, 23, 1]
5740 *
5741 * Raises an exception if +self+ is negative or +base+ is less than 2.
5742 *
5743 */
5744
5745static VALUE
5746rb_int_digits(int argc, VALUE *argv, VALUE num)
5747{
5748 VALUE base_value;
5749 long base;
5750
5751 if (rb_num_negative_p(num))
5752 rb_raise(rb_eMathDomainError, "out of domain");
5753
5754 if (rb_check_arity(argc, 0, 1)) {
5755 base_value = rb_to_int(argv[0]);
5756 if (!RB_INTEGER_TYPE_P(base_value))
5757 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5758 rb_obj_classname(argv[0]));
5759 if (RB_BIGNUM_TYPE_P(base_value))
5760 return rb_int_digits_bigbase(num, base_value);
5761
5762 base = FIX2LONG(base_value);
5763 if (base < 0)
5764 rb_raise(rb_eArgError, "negative radix");
5765 else if (base < 2)
5766 rb_raise(rb_eArgError, "invalid radix %ld", base);
5767 }
5768 else
5769 base = 10;
5770
5771 if (FIXNUM_P(num))
5772 return rb_fix_digits(num, base);
5773 else if (RB_BIGNUM_TYPE_P(num))
5774 return rb_int_digits_bigbase(num, LONG2FIX(base));
5775
5776 return Qnil;
5777}
5778
5779static VALUE
5780int_upto_size(VALUE from, VALUE args, VALUE eobj)
5781{
5782 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5783}
5784
5785/*
5786 * call-seq:
5787 * upto(limit) {|i| ... } -> self
5788 * upto(limit) -> enumerator
5789 *
5790 * Calls the given block with each integer value from +self+ up to +limit+;
5791 * returns +self+:
5792 *
5793 * a = []
5794 * 5.upto(10) {|i| a << i } # => 5
5795 * a # => [5, 6, 7, 8, 9, 10]
5796 * a = []
5797 * -5.upto(0) {|i| a << i } # => -5
5798 * a # => [-5, -4, -3, -2, -1, 0]
5799 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5800 *
5801 * With no block given, returns an Enumerator.
5802 *
5803 */
5804
5805static VALUE
5806int_upto(VALUE from, VALUE to)
5807{
5808 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5809 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5810 long i, end;
5811
5812 end = FIX2LONG(to);
5813 for (i = FIX2LONG(from); i <= end; i++) {
5814 rb_yield(LONG2FIX(i));
5815 }
5816 }
5817 else {
5818 VALUE i = from, c;
5819
5820 while (!(c = rb_funcall(i, '>', 1, to))) {
5821 rb_yield(i);
5822 i = rb_funcall(i, '+', 1, INT2FIX(1));
5823 }
5824 ensure_cmp(c, i, to);
5825 }
5826 return from;
5827}
5828
5829static VALUE
5830int_downto_size(VALUE from, VALUE args, VALUE eobj)
5831{
5832 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5833}
5834
5835/*
5836 * call-seq:
5837 * downto(limit) {|i| ... } -> self
5838 * downto(limit) -> enumerator
5839 *
5840 * Calls the given block with each integer value from +self+ down to +limit+;
5841 * returns +self+:
5842 *
5843 * a = []
5844 * 10.downto(5) {|i| a << i } # => 10
5845 * a # => [10, 9, 8, 7, 6, 5]
5846 * a = []
5847 * 0.downto(-5) {|i| a << i } # => 0
5848 * a # => [0, -1, -2, -3, -4, -5]
5849 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5850 *
5851 * With no block given, returns an Enumerator.
5852 *
5853 */
5854
5855static VALUE
5856int_downto(VALUE from, VALUE to)
5857{
5858 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5859 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5860 long i, end;
5861
5862 end = FIX2LONG(to);
5863 for (i=FIX2LONG(from); i >= end; i--) {
5864 rb_yield(LONG2FIX(i));
5865 }
5866 }
5867 else {
5868 VALUE i = from, c;
5869
5870 while (!(c = rb_funcall(i, '<', 1, to))) {
5871 rb_yield(i);
5872 i = rb_funcall(i, '-', 1, INT2FIX(1));
5873 }
5874 if (NIL_P(c)) rb_cmperr(i, to);
5875 }
5876 return from;
5877}
5878
5879static VALUE
5880int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5881{
5882 return int_neg_p(num) ? INT2FIX(0) : num;
5883}
5884
5885/*
5886 * call-seq:
5887 * round(ndigits= 0, half: :up) -> integer
5888 *
5889 * Returns +self+ rounded to the nearest value with
5890 * a precision of +ndigits+ decimal digits.
5891 *
5892 * When +ndigits+ is negative, the returned value
5893 * has at least <tt>ndigits.abs</tt> trailing zeros:
5894 *
5895 * 555.round(-1) # => 560
5896 * 555.round(-2) # => 600
5897 * 555.round(-3) # => 1000
5898 * -555.round(-2) # => -600
5899 * 555.round(-4) # => 0
5900 *
5901 * Returns +self+ when +ndigits+ is zero or positive.
5902 *
5903 * 555.round # => 555
5904 * 555.round(1) # => 555
5905 * 555.round(50) # => 555
5906 *
5907 * If keyword argument +half+ is given,
5908 * and +self+ is equidistant from the two candidate values,
5909 * the rounding is according to the given +half+ value:
5910 *
5911 * - +:up+ or +nil+: round away from zero:
5912 *
5913 * 25.round(-1, half: :up) # => 30
5914 * (-25).round(-1, half: :up) # => -30
5915 *
5916 * - +:down+: round toward zero:
5917 *
5918 * 25.round(-1, half: :down) # => 20
5919 * (-25).round(-1, half: :down) # => -20
5920 *
5921 *
5922 * - +:even+: round toward the candidate whose last nonzero digit is even:
5923 *
5924 * 25.round(-1, half: :even) # => 20
5925 * 15.round(-1, half: :even) # => 20
5926 * (-25).round(-1, half: :even) # => -20
5927 *
5928 * Raises and exception if the value for +half+ is invalid.
5929 *
5930 * Related: Integer#truncate.
5931 *
5932 */
5933
5934static VALUE
5935int_round(int argc, VALUE* argv, VALUE num)
5936{
5937 int ndigits;
5938 int mode;
5939 VALUE nd, opt;
5940
5941 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5942 ndigits = NUM2INT(nd);
5943 mode = rb_num_get_rounding_option(opt);
5944 if (ndigits >= 0) {
5945 return num;
5946 }
5947 return rb_int_round(num, ndigits, mode);
5948}
5949
5950/*
5951 * :markup: markdown
5952 *
5953 * call-seq:
5954 * floor(ndigits = 0) -> integer
5955 *
5956 * Returns an integer that is a "floor" value for `self`,
5957 * as specified by the given `ndigits`,
5958 * which must be an
5959 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5960 *
5961 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5962 *
5963 * ```
5964 * 0.floor(2) # => 0
5965 * 0.floor(-2) # => 0
5966 * ```
5967 *
5968 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5969 *
5970 * ```
5971 * 555.floor # => 555
5972 * 555.floor(50) # => 555
5973 * ```
5974 *
5975 * - When `self` is non-zero and `ndigits` is negative,
5976 * returns a value based on a computed granularity:
5977 *
5978 * - The granularity is `10 ** ndigits.abs`.
5979 * - The returned value is the largest multiple of the granularity
5980 * that is less than or equal to `self`.
5981 *
5982 * Examples with positive `self`:
5983 *
5984 * | ndigits | Granularity | 1234.floor(ndigits) |
5985 * |--------:|------------:|--------------------:|
5986 * | -1 | 10 | 1230 |
5987 * | -2 | 100 | 1200 |
5988 * | -3 | 1000 | 1000 |
5989 * | -4 | 10000 | 0 |
5990 * | -5 | 100000 | 0 |
5991 *
5992 * Examples with negative `self`:
5993 *
5994 * | ndigits | Granularity | -1234.floor(ndigits) |
5995 * |--------:|------------:|---------------------:|
5996 * | -1 | 10 | -1240 |
5997 * | -2 | 100 | -1300 |
5998 * | -3 | 1000 | -2000 |
5999 * | -4 | 10000 | -10000 |
6000 * | -5 | 100000 | -100000 |
6001 *
6002 * Related: Integer#ceil.
6003 *
6004 */
6005
6006static VALUE
6007int_floor(int argc, VALUE* argv, VALUE num)
6008{
6009 int ndigits;
6010
6011 if (!rb_check_arity(argc, 0, 1)) return num;
6012 ndigits = NUM2INT(argv[0]);
6013 if (ndigits >= 0) {
6014 return num;
6015 }
6016 return rb_int_floor(num, ndigits);
6017}
6018
6019/*
6020 * :markup: markdown
6021 *
6022 * call-seq:
6023 * ceil(ndigits = 0) -> integer
6024 *
6025 * Returns an integer that is a "ceiling" value for `self`,
6026 * as specified by the given `ndigits`,
6027 * which must be an
6028 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6029 *
6030 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6031 *
6032 * ```
6033 * 0.ceil(2) # => 0
6034 * 0.ceil(-2) # => 0
6035 * ```
6036 *
6037 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6038 *
6039 * ```
6040 * 555.ceil # => 555
6041 * 555.ceil(50) # => 555
6042 * ```
6043 *
6044 * - When `self` is non-zero and `ndigits` is negative,
6045 * returns a value based on a computed granularity:
6046 *
6047 * - The granularity is `10 ** ndigits.abs`.
6048 * - The returned value is the smallest multiple of the granularity
6049 * that is greater than or equal to `self`.
6050 *
6051 * Examples with positive `self`:
6052 *
6053 * | ndigits | Granularity | 1234.ceil(ndigits) |
6054 * |--------:|------------:|-------------------:|
6055 * | -1 | 10 | 1240 |
6056 * | -2 | 100 | 1300 |
6057 * | -3 | 1000 | 2000 |
6058 * | -4 | 10000 | 10000 |
6059 * | -5 | 100000 | 100000 |
6060 *
6061 * Examples with negative `self`:
6062 *
6063 * | ndigits | Granularity | -1234.ceil(ndigits) |
6064 * |--------:|------------:|--------------------:|
6065 * | -1 | 10 | -1230 |
6066 * | -2 | 100 | -1200 |
6067 * | -3 | 1000 | -1000 |
6068 * | -4 | 10000 | 0 |
6069 * | -5 | 100000 | 0 |
6070 *
6071 * Related: Integer#floor.
6072 */
6073
6074static VALUE
6075int_ceil(int argc, VALUE* argv, VALUE num)
6076{
6077 int ndigits;
6078
6079 if (!rb_check_arity(argc, 0, 1)) return num;
6080 ndigits = NUM2INT(argv[0]);
6081 if (ndigits >= 0) {
6082 return num;
6083 }
6084 return rb_int_ceil(num, ndigits);
6085}
6086
6087/*
6088 * call-seq:
6089 * truncate(ndigits = 0) -> integer
6090 *
6091 * Returns +self+ truncated (toward zero) to
6092 * a precision of +ndigits+ decimal digits.
6093 *
6094 * When +ndigits+ is negative, the returned value
6095 * has at least <tt>ndigits.abs</tt> trailing zeros:
6096 *
6097 * 555.truncate(-1) # => 550
6098 * 555.truncate(-2) # => 500
6099 * -555.truncate(-2) # => -500
6100 *
6101 * Returns +self+ when +ndigits+ is zero or positive.
6102 *
6103 * 555.truncate # => 555
6104 * 555.truncate(50) # => 555
6105 *
6106 * Related: Integer#round.
6107 *
6108 */
6109
6110static VALUE
6111int_truncate(int argc, VALUE* argv, VALUE num)
6112{
6113 int ndigits;
6114
6115 if (!rb_check_arity(argc, 0, 1)) return num;
6116 ndigits = NUM2INT(argv[0]);
6117 if (ndigits >= 0) {
6118 return num;
6119 }
6120 return rb_int_truncate(num, ndigits);
6121}
6122
6123#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6124rettype \
6125prefix##_isqrt(argtype n) \
6126{ \
6127 if (!argtype##_IN_DOUBLE_P(n)) { \
6128 unsigned int b = bit_length(n); \
6129 argtype t; \
6130 rettype x = (rettype)(n >> (b/2+1)); \
6131 x |= ((rettype)1LU << (b-1)/2); \
6132 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6133 return x; \
6134 } \
6135 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6136 /* libm sqrt may returns a larger approximation than actual. */ \
6137 /* Our isqrt always returns a smaller approximation. */ \
6138 if (x * x > n) x--; \
6139 return x; \
6140}
6141
6142#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6143# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6144#else
6145# define RB_ULONG_IN_DOUBLE_P(n) 1
6146#endif
6147#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6148#define RB_ULONG unsigned long
6149DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
6150
6151#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6152# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6153# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6154# else
6155# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6156# endif
6157# ifdef ULL_TO_DOUBLE
6158# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6159# else
6160# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6161# endif
6162DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6163#endif
6164
6165#define domain_error(msg) \
6166 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6167
6168/*
6169 * call-seq:
6170 * Integer.sqrt(numeric) -> integer
6171 *
6172 * Returns the integer square root of the non-negative integer +n+,
6173 * which is the largest non-negative integer less than or equal to the
6174 * square root of +numeric+.
6175 *
6176 * Integer.sqrt(0) # => 0
6177 * Integer.sqrt(1) # => 1
6178 * Integer.sqrt(24) # => 4
6179 * Integer.sqrt(25) # => 5
6180 * Integer.sqrt(10**400) # => 10**200
6181 *
6182 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6183 *
6184 * Integer.sqrt(Complex(4, 0)) # => 2
6185 * Integer.sqrt(Rational(4, 1)) # => 2
6186 * Integer.sqrt(4.0) # => 2
6187 * Integer.sqrt(3.14159) # => 1
6188 *
6189 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6190 * except that the result of the latter code may differ from the true value
6191 * due to the limited precision of floating point arithmetic.
6192 *
6193 * Integer.sqrt(10**46) # => 100000000000000000000000
6194 * Math.sqrt(10**46).floor # => 99999999999999991611392
6195 *
6196 * Raises an exception if +numeric+ is negative.
6197 *
6198 */
6199
6200static VALUE
6201rb_int_s_isqrt(VALUE self, VALUE num)
6202{
6203 unsigned long n, sq;
6204 num = rb_to_int(num);
6205 if (FIXNUM_P(num)) {
6206 if (FIXNUM_NEGATIVE_P(num)) {
6207 domain_error("isqrt");
6208 }
6209 n = FIX2ULONG(num);
6210 sq = rb_ulong_isqrt(n);
6211 return LONG2FIX(sq);
6212 }
6213 else {
6214 size_t biglen;
6215 if (RBIGNUM_NEGATIVE_P(num)) {
6216 domain_error("isqrt");
6217 }
6218 biglen = BIGNUM_LEN(num);
6219 if (biglen == 0) return INT2FIX(0);
6220#if SIZEOF_BDIGIT <= SIZEOF_LONG
6221 /* short-circuit */
6222 if (biglen == 1) {
6223 n = BIGNUM_DIGITS(num)[0];
6224 sq = rb_ulong_isqrt(n);
6225 return ULONG2NUM(sq);
6226 }
6227#endif
6228 return rb_big_isqrt(num);
6229 }
6230}
6231
6232/*
6233 * call-seq:
6234 * Integer.try_convert(object) -> object, integer, or nil
6235 *
6236 * If +object+ is an \Integer object, returns +object+.
6237 * Integer.try_convert(1) # => 1
6238 *
6239 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6240 * calls <tt>object.to_int</tt> and returns the result.
6241 * Integer.try_convert(1.25) # => 1
6242 *
6243 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6244 * Integer.try_convert([]) # => nil
6245 *
6246 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6247 */
6248static VALUE
6249int_s_try_convert(VALUE self, VALUE num)
6250{
6251 return rb_check_integer_type(num);
6252}
6253
6254/*
6255 * Document-class: ZeroDivisionError
6256 *
6257 * Raised when attempting to divide an integer by 0.
6258 *
6259 * 42 / 0 #=> ZeroDivisionError: divided by 0
6260 *
6261 * Note that only division by an exact 0 will raise the exception:
6262 *
6263 * 42 / 0.0 #=> Float::INFINITY
6264 * 42 / -0.0 #=> -Float::INFINITY
6265 * 0 / 0.0 #=> NaN
6266 */
6267
6268/*
6269 * Document-class: FloatDomainError
6270 *
6271 * Raised when attempting to convert special float values (in particular
6272 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6273 *
6274 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6275 */
6276
6277/*
6278 * Document-class: Numeric
6279 *
6280 * \Numeric is the class from which all higher-level numeric classes should inherit.
6281 *
6282 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6283 * Integer are implemented as immediates, which means that each Integer is a single immutable
6284 * object which is always passed by value.
6285 *
6286 * a = 1
6287 * 1.object_id == a.object_id #=> true
6288 *
6289 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6290 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6291 *
6292 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6293 * 1.dup #=> 1
6294 * 1.object_id == 1.dup.object_id #=> true
6295 *
6296 * For this reason, \Numeric should be used when defining other numeric classes.
6297 *
6298 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6299 * Array containing an object that has been coerced into an instance of the new class
6300 * and +self+ (see #coerce).
6301 *
6302 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6303 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6304 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6305 * instances of other numeric classes.
6306 *
6307 * class Tally < Numeric
6308 * def initialize(string)
6309 * @string = string
6310 * end
6311 *
6312 * def to_s
6313 * @string
6314 * end
6315 *
6316 * def to_i
6317 * @string.size
6318 * end
6319 *
6320 * def coerce(other)
6321 * [self.class.new('|' * other.to_i), self]
6322 * end
6323 *
6324 * def <=>(other)
6325 * to_i <=> other.to_i
6326 * end
6327 *
6328 * def +(other)
6329 * self.class.new('|' * (to_i + other.to_i))
6330 * end
6331 *
6332 * def -(other)
6333 * self.class.new('|' * (to_i - other.to_i))
6334 * end
6335 *
6336 * def *(other)
6337 * self.class.new('|' * (to_i * other.to_i))
6338 * end
6339 *
6340 * def /(other)
6341 * self.class.new('|' * (to_i / other.to_i))
6342 * end
6343 * end
6344 *
6345 * tally = Tally.new('||')
6346 * puts tally * 2 #=> "||||"
6347 * puts tally > 1 #=> true
6348 *
6349 * == What's Here
6350 *
6351 * First, what's elsewhere. Class \Numeric:
6352 *
6353 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6354 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6355 *
6356 * Here, class \Numeric provides methods for:
6357 *
6358 * - {Querying}[rdoc-ref:Numeric@Querying]
6359 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6360 * - {Converting}[rdoc-ref:Numeric@Converting]
6361 * - {Other}[rdoc-ref:Numeric@Other]
6362 *
6363 * === Querying
6364 *
6365 * - #finite?: Returns true unless +self+ is infinite or not a number.
6366 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6367 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6368 * - #integer?: Returns whether +self+ is an integer.
6369 * - #negative?: Returns whether +self+ is negative.
6370 * - #nonzero?: Returns whether +self+ is not zero.
6371 * - #positive?: Returns whether +self+ is positive.
6372 * - #real?: Returns whether +self+ is a real value.
6373 * - #zero?: Returns whether +self+ is zero.
6374 *
6375 * === Comparing
6376 *
6377 * - #<=>: Returns:
6378 *
6379 * - -1 if +self+ is less than the given value.
6380 * - 0 if +self+ is equal to the given value.
6381 * - 1 if +self+ is greater than the given value.
6382 * - +nil+ if +self+ and the given value are not comparable.
6383 *
6384 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6385 *
6386 * === Converting
6387 *
6388 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6389 * - #-@: Returns the value of +self+, negated.
6390 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6391 * - #abs2: Returns the square of +self+.
6392 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6393 * Math::PI otherwise.
6394 * - #ceil: Returns the smallest number greater than or equal to +self+,
6395 * to a given precision.
6396 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6397 * for the given other value.
6398 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6399 * - #denominator: Returns the denominator (always positive)
6400 * of the Rational representation of +self+.
6401 * - #div: Returns the value of +self+ divided by the given value
6402 * and converted to an integer.
6403 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6404 * from dividing +self+ the given divisor.
6405 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6406 * - #floor: Returns the largest number less than or equal to +self+,
6407 * to a given precision.
6408 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6409 * the given value.
6410 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6411 * - #numerator: Returns the numerator of the Rational representation of +self+;
6412 * has the same sign as +self+.
6413 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6414 * - #quo: Returns the value of +self+ divided by the given value.
6415 * - #real: Returns the real part of +self+.
6416 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6417 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6418 * - #round: Returns the value of +self+ rounded to the nearest value
6419 * for the given a precision.
6420 * - #to_c: Returns the Complex representation of +self+.
6421 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6422 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6423 *
6424 * === Other
6425 *
6426 * - #clone: Returns +self+; does not allow freezing.
6427 * - #dup (aliased as #+@): Returns +self+.
6428 * - #step: Invokes the given block with the sequence of specified numbers.
6429 *
6430 */
6431void
6432Init_Numeric(void)
6433{
6434#ifdef _UNICOSMP
6435 /* Turn off floating point exceptions for divide by zero, etc. */
6436 _set_Creg(0, 0);
6437#endif
6438 id_coerce = rb_intern_const("coerce");
6439 id_to = rb_intern_const("to");
6440 id_by = rb_intern_const("by");
6441
6442 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6444 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6445
6446 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6448 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6449 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6450
6451 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6452 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6453 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6454 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6455 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6456 rb_define_method(rb_cNumeric, "div", num_div, 1);
6457 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6458 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6459 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6460 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6461 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6462 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6463 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6464
6465 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6466 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6467
6468 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6469 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6470 rb_define_method(rb_cNumeric, "round", num_round, -1);
6471 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6472 rb_define_method(rb_cNumeric, "step", num_step, -1);
6473 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6474 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6475
6479 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6480 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6481
6482 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6483 rb_define_alias(rb_cInteger, "inspect", "to_s");
6484 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6485 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6486 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6487 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6488 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6489 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6490 rb_define_method(rb_cInteger, "next", int_succ, 0);
6491 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6492 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6493 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6494 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6495 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6496 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6497 rb_define_method(rb_cInteger, "round", int_round, -1);
6498 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6499
6500 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6501 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6502 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6503 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6504 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6505 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6506 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6507 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6508 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6509 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6510 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6511
6512 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6513
6514 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6515 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6516 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6517 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6518 rb_define_method(rb_cInteger, "<", int_lt, 1);
6519 rb_define_method(rb_cInteger, "<=", int_le, 1);
6520
6521 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6522 rb_define_method(rb_cInteger, "|", int_or, 1);
6523 rb_define_method(rb_cInteger, "^", rb_int_xor, 1);
6524 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6525
6526 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6527 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6528
6529 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6530
6531#define fix_to_s_static(n) do { \
6532 VALUE lit = rb_fstring_literal(#n); \
6533 rb_fix_to_s_static[n] = lit; \
6534 rb_vm_register_global_object(lit); \
6535 RB_GC_GUARD(lit); \
6536 } while (0)
6537
6538 fix_to_s_static(0);
6539 fix_to_s_static(1);
6540 fix_to_s_static(2);
6541 fix_to_s_static(3);
6542 fix_to_s_static(4);
6543 fix_to_s_static(5);
6544 fix_to_s_static(6);
6545 fix_to_s_static(7);
6546 fix_to_s_static(8);
6547 fix_to_s_static(9);
6548
6549#undef fix_to_s_static
6550
6552
6555
6556 /*
6557 * The base of the floating point, or number of unique digits used to
6558 * represent the number.
6559 *
6560 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6561 */
6562 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6563 /*
6564 * The number of base digits for the +double+ data type.
6565 *
6566 * Usually defaults to 53.
6567 */
6568 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6569 /*
6570 * The minimum number of significant decimal digits in a double-precision
6571 * floating point.
6572 *
6573 * Usually defaults to 15.
6574 */
6575 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6576 /*
6577 * The smallest possible exponent value in a double-precision floating
6578 * point.
6579 *
6580 * Usually defaults to -1021.
6581 */
6582 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6583 /*
6584 * The largest possible exponent value in a double-precision floating
6585 * point.
6586 *
6587 * Usually defaults to 1024.
6588 */
6589 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6590 /*
6591 * The smallest negative exponent in a double-precision floating point
6592 * where 10 raised to this power minus 1.
6593 *
6594 * Usually defaults to -307.
6595 */
6596 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6597 /*
6598 * The largest positive exponent in a double-precision floating point where
6599 * 10 raised to this power minus 1.
6600 *
6601 * Usually defaults to 308.
6602 */
6603 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6604 /*
6605 * The smallest positive normalized number in a double-precision floating point.
6606 *
6607 * Usually defaults to 2.2250738585072014e-308.
6608 *
6609 * If the platform supports denormalized numbers,
6610 * there are numbers between zero and Float::MIN.
6611 * +0.0.next_float+ returns the smallest positive floating point number
6612 * including denormalized numbers.
6613 */
6614 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6615 /*
6616 * The largest possible integer in a double-precision floating point number.
6617 *
6618 * Usually defaults to 1.7976931348623157e+308.
6619 */
6620 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6621 /*
6622 * The difference between 1 and the smallest double-precision floating
6623 * point number greater than 1.
6624 *
6625 * Usually defaults to 2.2204460492503131e-16.
6626 */
6627 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6628 /*
6629 * An expression representing positive infinity.
6630 */
6631 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6632 /*
6633 * An expression representing a value which is "not a number".
6634 */
6635 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6636
6637 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6638 rb_define_alias(rb_cFloat, "inspect", "to_s");
6639 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6640 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6641 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6642 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6643 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6644 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6645 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6646 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6647 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6648 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6649 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6650 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6651 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6652 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6653 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6654 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6655 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6656 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6657 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6658 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6659
6660 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6661 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6662 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6663 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6664 rb_define_method(rb_cFloat, "round", flo_round, -1);
6665 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6666
6667 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6668 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6669 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6670 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6671 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6672}
6673
6674#undef rb_float_value
6675double
6676rb_float_value(VALUE v)
6677{
6678 return rb_float_value_inline(v);
6679}
6680
6681#undef rb_float_new
6682VALUE
6683rb_float_new(double d)
6684{
6685 return rb_float_new_inline(d);
6686}
6687
6688#include "numeric.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define LONG_LONG
Definition long_long.h:38
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
VALUE rb_float_new_in_heap(double d)
Identical to rb_float_new(), except it does not generate Flonums.
Definition numeric.c:910
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1795
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1588
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2899
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2947
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2767
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:3237
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1007
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3026
#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:1679
#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 ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c: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:3721
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:3289
Encoding relates APIs.
#define RUBY_FIXNUM_MAX
Maximum possible value that a fixnum can represent.
Definition fixnum.h:55
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3922
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
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
Definition enumerator.h:195
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:206
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3335
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:4028
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4682
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
Definition numeric.c:1553
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:5140
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:1848
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1977
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1497
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1531
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3563
#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:1566
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2788
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2948
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1630
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:2100
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
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)
Definition string.c:12648
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:3249
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3243
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3237
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3255
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:3164
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3089
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3158
#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:3293
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3311
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3302
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3321
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