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