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