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