Ruby: numeric.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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