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