Ruby: numeric.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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 u, v, us, vs, f, d, uf;
148
149 v = modf(x, &u);
150 us = u * s;
151 vs = v * s;
152
153 if (x > 0.0) {
154 f = floor(vs);
155 uf = us + f;
156 d = vs - f;
157 if (d > 0.5)
158 d = 1.0;
159 else if (d == 0.5 || ((double)((uf + 0.5) / s) <= x))
160 d = fmod(uf, 2.0);
161 else
162 d = 0.0;
163 x = f + d;
164 }
165 else if (x < 0.0) {
166 f = ceil(vs);
167 uf = us + f;
168 d = f - vs;
169 if (d > 0.5)
170 d = 1.0;
171 else if (d == 0.5 || ((double)((uf - 0.5) / s) >= x))
172 d = fmod(-uf, 2.0);
173 else
174 d = 0.0;
175 x = f - d;
176 }
177 return us + x;
178}
179
180static VALUE fix_lshift(long, unsigned long);
181static VALUE fix_rshift(long, unsigned long);
182static VALUE int_pow(long x, unsigned long y);
183static VALUE rb_int_floor(VALUE num, int ndigits);
184static VALUE rb_int_ceil(VALUE num, int ndigits);
185static VALUE flo_to_i(VALUE num);
186static int float_round_overflow(int ndigits, int binexp);
187static int float_round_underflow(int ndigits, int binexp);
188
189static ID id_coerce;
190#define id_div idDiv
191#define id_divmod idDivmod
192#define id_to_i idTo_i
193#define id_eq idEq
194#define id_cmp idCmp
195
196 VALUE rb_cNumeric;
197 VALUE rb_cFloat;
198 VALUE rb_cInteger;
199
200 VALUE rb_eZeroDivError;
201 VALUE rb_eFloatDomainError;
202
203static ID id_to, id_by;
204
205void
206rb_num_zerodiv(void)
207{
208 rb_raise(rb_eZeroDivError, "divided by 0");
209}
210
211enum ruby_num_rounding_mode
212rb_num_get_rounding_option(VALUE opts)
213{
214 static ID round_kwds[1];
215 VALUE rounding;
216 VALUE str;
217 const char *s;
218
219 if (!NIL_P(opts)) {
220 if (!round_kwds[0]) {
221 round_kwds[0] = rb_intern_const("half");
222 }
223 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
224 if (SYMBOL_P(rounding)) {
225 str = rb_sym2str(rounding);
226 }
227 else if (NIL_P(rounding)) {
228 goto noopt;
229 }
230 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
231 str = rb_check_string_type(rounding);
232 if (NIL_P(str)) goto invalid;
233 }
234 rb_must_asciicompat(str);
235 s = RSTRING_PTR(str);
236 switch (RSTRING_LEN(str)) {
237 case 2:
238 if (rb_memcicmp(s, "up", 2) == 0)
239 return RUBY_NUM_ROUND_HALF_UP;
240 break;
241 case 4:
242 if (rb_memcicmp(s, "even", 4) == 0)
243 return RUBY_NUM_ROUND_HALF_EVEN;
244 if (strncasecmp(s, "down", 4) == 0)
245 return RUBY_NUM_ROUND_HALF_DOWN;
246 break;
247 }
248 invalid:
249 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
250 }
251 noopt:
252 return RUBY_NUM_ROUND_DEFAULT;
253}
254
255/* experimental API */
256int
257rb_num_to_uint(VALUE val, unsigned int *ret)
258{
259#define NUMERR_TYPE 1
260#define NUMERR_NEGATIVE 2
261#define NUMERR_TOOLARGE 3
262 if (FIXNUM_P(val)) {
263 long v = FIX2LONG(val);
264#if SIZEOF_INT < SIZEOF_LONG
265 if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
266#endif
267 if (v < 0) return NUMERR_NEGATIVE;
268 *ret = (unsigned int)v;
269 return 0;
270 }
271
272 if (RB_BIGNUM_TYPE_P(val)) {
273 if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
274#if SIZEOF_INT < SIZEOF_LONG
275 /* long is 64bit */
276 return NUMERR_TOOLARGE;
277#else
278 /* long is 32bit */
279 if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
280 *ret = (unsigned int)rb_big2ulong((VALUE)val);
281 return 0;
282#endif
283 }
284 return NUMERR_TYPE;
285}
286
287#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
288
289static inline int
290int_pos_p(VALUE num)
291{
292 if (FIXNUM_P(num)) {
293 return FIXNUM_POSITIVE_P(num);
294 }
295 else if (RB_BIGNUM_TYPE_P(num)) {
296 return BIGNUM_POSITIVE_P(num);
297 }
298 rb_raise(rb_eTypeError, "not an Integer");
299}
300
301static inline int
302int_neg_p(VALUE num)
303{
304 if (FIXNUM_P(num)) {
305 return FIXNUM_NEGATIVE_P(num);
306 }
307 else if (RB_BIGNUM_TYPE_P(num)) {
308 return BIGNUM_NEGATIVE_P(num);
309 }
310 rb_raise(rb_eTypeError, "not an Integer");
311}
312
313int
314rb_int_positive_p(VALUE num)
315{
316 return int_pos_p(num);
317}
318
319int
320rb_int_negative_p(VALUE num)
321{
322 return int_neg_p(num);
323}
324
325int
326rb_num_negative_p(VALUE num)
327{
328 return rb_num_negative_int_p(num);
329}
330
331static VALUE
332num_funcall_op_0(VALUE x, VALUE arg, int recursive)
333{
334 ID func = (ID)arg;
335 if (recursive) {
336 const char *name = rb_id2name(func);
337 if (ISALNUM(name[0])) {
338 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
339 x, ID2SYM(func));
340 }
341 else if (name[0] && name[1] == '@' && !name[2]) {
342 rb_name_error(func, "%c%"PRIsVALUE,
343 name[0], x);
344 }
345 else {
346 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
347 ID2SYM(func), x);
348 }
349 }
350 return rb_funcallv(x, func, 0, 0);
351}
352
353static VALUE
354num_funcall0(VALUE x, ID func)
355{
356 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
357}
358
359NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
360
361static void
362num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
363{
364 const char *name = rb_id2name(func);
365 if (ISALNUM(name[0])) {
366 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
367 x, ID2SYM(func), y);
368 }
369 else {
370 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
371 x, ID2SYM(func), y);
372 }
373}
374
375static VALUE
376num_funcall_op_1(VALUE y, VALUE arg, int recursive)
377{
378 ID func = (ID)((VALUE *)arg)[0];
379 VALUE x = ((VALUE *)arg)[1];
380 if (recursive) {
381 num_funcall_op_1_recursion(x, func, y);
382 }
383 return rb_funcall(x, func, 1, y);
384}
385
386static VALUE
387num_funcall1(VALUE x, ID func, VALUE y)
388{
389 VALUE args[2];
390 args[0] = (VALUE)func;
391 args[1] = x;
392 return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
393}
394
395/*
396 * call-seq:
397 * coerce(other) -> array
398 *
399 * Returns a 2-element array containing two numeric elements,
400 * formed from the two operands +self+ and +other+,
401 * of a common compatible type.
402 *
403 * Of the Core and Standard Library classes,
404 * Integer, Rational, and Complex use this implementation.
405 *
406 * Examples:
407 *
408 * i = 2 # => 2
409 * i.coerce(3) # => [3, 2]
410 * i.coerce(3.0) # => [3.0, 2.0]
411 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
412 * i.coerce(Complex(3, 4)) # Raises RangeError.
413 *
414 * r = Rational(5, 2) # => (5/2)
415 * r.coerce(2) # => [(2/1), (5/2)]
416 * r.coerce(2.0) # => [2.0, 2.5]
417 * r.coerce(Rational(2, 3)) # => [(2/3), (5/2)]
418 * r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)]
419 *
420 * c = Complex(2, 3) # => (2+3i)
421 * c.coerce(2) # => [(2+0i), (2+3i)]
422 * c.coerce(2.0) # => [(2.0+0i), (2+3i)]
423 * c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)]
424 * c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
425 *
426 * Raises an exception if any type conversion fails.
427 *
428 */
429
430static VALUE
431num_coerce(VALUE x, VALUE y)
432{
433 if (CLASS_OF(x) == CLASS_OF(y))
434 return rb_assoc_new(y, x);
435 x = rb_Float(x);
436 y = rb_Float(y);
437 return rb_assoc_new(y, x);
438}
439
440NORETURN(static void coerce_failed(VALUE x, VALUE y));
441static void
442coerce_failed(VALUE x, VALUE y)
443{
444 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
445 y = rb_inspect(y);
446 }
447 else {
448 y = rb_obj_class(y);
449 }
450 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
451 y, rb_obj_class(x));
452}
453
454static int
455do_coerce(VALUE *x, VALUE *y, int err)
456{
457 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
458 if (UNDEF_P(ary)) {
459 if (err) {
460 coerce_failed(*x, *y);
461 }
462 return FALSE;
463 }
464 if (!err && NIL_P(ary)) {
465 return FALSE;
466 }
467 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
468 rb_raise(rb_eTypeError, "coerce must return [x, y]");
469 }
470
471 *x = RARRAY_AREF(ary, 0);
472 *y = RARRAY_AREF(ary, 1);
473 return TRUE;
474}
475
476 VALUE
477rb_num_coerce_bin(VALUE x, VALUE y, ID func)
478{
479 do_coerce(&x, &y, TRUE);
480 return rb_funcall(x, func, 1, y);
481}
482
483 VALUE
484rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
485{
486 if (do_coerce(&x, &y, FALSE))
487 return rb_funcall(x, func, 1, y);
488 return Qnil;
489}
490
491static VALUE
492ensure_cmp(VALUE c, VALUE x, VALUE y)
493{
494 if (NIL_P(c)) rb_cmperr(x, y);
495 return c;
496}
497
498 VALUE
499rb_num_coerce_relop(VALUE x, VALUE y, ID func)
500{
501 VALUE x0 = x, y0 = y;
502
503 if (!do_coerce(&x, &y, FALSE)) {
504 rb_cmperr(x0, y0);
505 UNREACHABLE_RETURN(Qnil);
506 }
507 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
508}
509
510NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
511
512/*
513 * :nodoc:
514 *
515 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
516 *
517 * Numerics should be values; singleton_methods should not be added to them.
518 */
519
520static VALUE
521num_sadded(VALUE x, VALUE name)
522{
523 ID mid = rb_to_id(name);
524 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
525 rb_remove_method_id(rb_singleton_class(x), mid);
526 rb_raise(rb_eTypeError,
527 "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
528 rb_id2str(mid),
529 rb_obj_class(x));
530
531 UNREACHABLE_RETURN(Qnil);
532}
533
534#if 0
535/*
536 * call-seq:
537 * clone(freeze: true) -> self
538 *
539 * Returns +self+.
540 *
541 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
542 *
543 * Related: Numeric#dup.
544 *
545 */
546static VALUE
547num_clone(int argc, VALUE *argv, VALUE x)
548{
549 return rb_immutable_obj_clone(argc, argv, x);
550}
551#else
552# define num_clone rb_immutable_obj_clone
553#endif
554
555#if 0
556/*
557 * call-seq:
558 * dup -> self
559 *
560 * Returns +self+.
561 *
562 * Related: Numeric#clone.
563 *
564 */
565static VALUE
566num_dup(VALUE x)
567{
568 return x;
569}
570#else
571# define num_dup num_uplus
572#endif
573
574/*
575 * call-seq:
576 * +self -> self
577 *
578 * Returns +self+.
579 *
580 */
581
582static VALUE
583num_uplus(VALUE num)
584{
585 return num;
586}
587
588/*
589 * call-seq:
590 * i -> complex
591 *
592 * Returns <tt>Complex(0, self)</tt>:
593 *
594 * 2.i # => (0+2i)
595 * -2.i # => (0-2i)
596 * 2.0.i # => (0+2.0i)
597 * Rational(1, 2).i # => (0+(1/2)*i)
598 * Complex(3, 4).i # Raises NoMethodError.
599 *
600 */
601
602static VALUE
603num_imaginary(VALUE num)
604{
605 return rb_complex_new(INT2FIX(0), num);
606}
607
608/*
609 * call-seq:
610 * -self -> numeric
611 *
612 * Unary Minus---Returns the receiver, negated.
613 */
614
615static VALUE
616num_uminus(VALUE num)
617{
618 VALUE zero;
619
620 zero = INT2FIX(0);
621 do_coerce(&zero, &num, TRUE);
622
623 return num_funcall1(zero, '-', num);
624}
625
626/*
627 * call-seq:
628 * fdiv(other) -> float
629 *
630 * Returns the quotient <tt>self/other</tt> as a float,
631 * using method +/+ in the derived class of +self+.
632 * (\Numeric itself does not define method +/+.)
633 *
634 * Of the Core and Standard Library classes,
635 * only BigDecimal uses this implementation.
636 *
637 */
638
639static VALUE
640num_fdiv(VALUE x, VALUE y)
641{
642 return rb_funcall(rb_Float(x), '/', 1, y);
643}
644
645/*
646 * call-seq:
647 * div(other) -> integer
648 *
649 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
650 * using method +/+ in the derived class of +self+.
651 * (\Numeric itself does not define method +/+.)
652 *
653 * Of the Core and Standard Library classes,
654 * Only Float and Rational use this implementation.
655 *
656 */
657
658static VALUE
659num_div(VALUE x, VALUE y)
660{
661 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
662 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
663}
664
665/*
666 * call-seq:
667 * self % other -> real_numeric
668 *
669 * Returns +self+ modulo +other+ as a real number.
670 *
671 * Of the Core and Standard Library classes,
672 * only Rational uses this implementation.
673 *
674 * For Rational +r+ and real number +n+, these expressions are equivalent:
675 *
676 * r % n
677 * r-n*(r/n).floor
678 * r.divmod(n)[1]
679 *
680 * See Numeric#divmod.
681 *
682 * Examples:
683 *
684 * r = Rational(1, 2) # => (1/2)
685 * r2 = Rational(2, 3) # => (2/3)
686 * r % r2 # => (1/2)
687 * r % 2 # => (1/2)
688 * r % 2.0 # => 0.5
689 *
690 * r = Rational(301,100) # => (301/100)
691 * r2 = Rational(7,5) # => (7/5)
692 * r % r2 # => (21/100)
693 * r % -r2 # => (-119/100)
694 * (-r) % r2 # => (119/100)
695 * (-r) %-r2 # => (-21/100)
696 *
697 */
698
699static VALUE
700num_modulo(VALUE x, VALUE y)
701{
702 VALUE q = num_funcall1(x, id_div, y);
703 return rb_funcall(x, '-', 1,
704 rb_funcall(y, '*', 1, q));
705}
706
707/*
708 * call-seq:
709 * remainder(other) -> real_number
710 *
711 * Returns the remainder after dividing +self+ by +other+.
712 *
713 * Of the Core and Standard Library classes,
714 * only Float and Rational use this implementation.
715 *
716 * Examples:
717 *
718 * 11.0.remainder(4) # => 3.0
719 * 11.0.remainder(-4) # => 3.0
720 * -11.0.remainder(4) # => -3.0
721 * -11.0.remainder(-4) # => -3.0
722 *
723 * 12.0.remainder(4) # => 0.0
724 * 12.0.remainder(-4) # => 0.0
725 * -12.0.remainder(4) # => -0.0
726 * -12.0.remainder(-4) # => -0.0
727 *
728 * 13.0.remainder(4.0) # => 1.0
729 * 13.0.remainder(Rational(4, 1)) # => 1.0
730 *
731 * Rational(13, 1).remainder(4) # => (1/1)
732 * Rational(13, 1).remainder(-4) # => (1/1)
733 * Rational(-13, 1).remainder(4) # => (-1/1)
734 * Rational(-13, 1).remainder(-4) # => (-1/1)
735 *
736 */
737
738static VALUE
739num_remainder(VALUE x, VALUE y)
740{
741 if (!rb_obj_is_kind_of(y, rb_cNumeric)) {
742 do_coerce(&x, &y, TRUE);
743 }
744 VALUE z = num_funcall1(x, '%', y);
745
746 if ((!rb_equal(z, INT2FIX(0))) &&
747 ((rb_num_negative_int_p(x) &&
748 rb_num_positive_int_p(y)) ||
749 (rb_num_positive_int_p(x) &&
750 rb_num_negative_int_p(y)))) {
751 if (RB_FLOAT_TYPE_P(y)) {
752 if (isinf(RFLOAT_VALUE(y))) {
753 return x;
754 }
755 }
756 return rb_funcall(z, '-', 1, y);
757 }
758 return z;
759}
760
761/*
762 * call-seq:
763 * divmod(other) -> array
764 *
765 * Returns a 2-element array <tt>[q, r]</tt>, where
766 *
767 * q = (self/other).floor # Quotient
768 * r = self % other # Remainder
769 *
770 * Of the Core and Standard Library classes,
771 * only Rational uses this implementation.
772 *
773 * Examples:
774 *
775 * Rational(11, 1).divmod(4) # => [2, (3/1)]
776 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
777 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
778 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
779 *
780 * Rational(12, 1).divmod(4) # => [3, (0/1)]
781 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
782 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
783 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
784 *
785 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
786 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
787 */
788
789static VALUE
790num_divmod(VALUE x, VALUE y)
791{
792 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
793}
794
795/*
796 * call-seq:
797 * abs -> numeric
798 *
799 * Returns the absolute value of +self+.
800 *
801 * 12.abs #=> 12
802 * (-34.56).abs #=> 34.56
803 * -34.56.abs #=> 34.56
804 *
805 */
806
807static VALUE
808num_abs(VALUE num)
809{
810 if (rb_num_negative_int_p(num)) {
811 return num_funcall0(num, idUMinus);
812 }
813 return num;
814}
815
816/*
817 * call-seq:
818 * zero? -> true or false
819 *
820 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
821 *
822 * Of the Core and Standard Library classes,
823 * only Rational and Complex use this implementation.
824 *
825 */
826
827static VALUE
828num_zero_p(VALUE num)
829{
830 return rb_equal(num, INT2FIX(0));
831}
832
833static bool
834int_zero_p(VALUE num)
835{
836 if (FIXNUM_P(num)) {
837 return FIXNUM_ZERO_P(num);
838 }
839 assert(RB_BIGNUM_TYPE_P(num));
840 return rb_bigzero_p(num);
841}
842
843 VALUE
844rb_int_zero_p(VALUE num)
845{
846 return RBOOL(int_zero_p(num));
847}
848
849/*
850 * call-seq:
851 * nonzero? -> self or nil
852 *
853 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
854 * uses method <tt>zero?</tt> for the evaluation.
855 *
856 * The returned +self+ allows the method to be chained:
857 *
858 * a = %w[z Bb bB bb BB a aA Aa AA A]
859 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
860 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
861 *
862 * Of the Core and Standard Library classes,
863 * Integer, Float, Rational, and Complex use this implementation.
864 *
865 */
866
867static VALUE
868num_nonzero_p(VALUE num)
869{
870 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
871 return Qnil;
872 }
873 return num;
874}
875
876/*
877 * call-seq:
878 * to_int -> integer
879 *
880 * Returns +self+ as an integer;
881 * converts using method +to_i+ in the derived class.
882 *
883 * Of the Core and Standard Library classes,
884 * only Rational and Complex use this implementation.
885 *
886 * Examples:
887 *
888 * Rational(1, 2).to_int # => 0
889 * Rational(2, 1).to_int # => 2
890 * Complex(2, 0).to_int # => 2
891 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
892 *
893 */
894
895static VALUE
896num_to_int(VALUE num)
897{
898 return num_funcall0(num, id_to_i);
899}
900
901/*
902 * call-seq:
903 * positive? -> true or false
904 *
905 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
906 *
907 */
908
909static VALUE
910num_positive_p(VALUE num)
911{
912 const ID mid = '>';
913
914 if (FIXNUM_P(num)) {
915 if (method_basic_p(rb_cInteger))
916 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
917 }
918 else if (RB_BIGNUM_TYPE_P(num)) {
919 if (method_basic_p(rb_cInteger))
920 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
921 }
922 return rb_num_compare_with_zero(num, mid);
923}
924
925/*
926 * call-seq:
927 * negative? -> true or false
928 *
929 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
930 *
931 */
932
933static VALUE
934num_negative_p(VALUE num)
935{
936 return RBOOL(rb_num_negative_int_p(num));
937}
938
939
940/********************************************************************
941 *
942 * Document-class: Float
943 *
944 * A \Float object represents a sometimes-inexact real number using the native
945 * architecture's double-precision floating point representation.
946 *
947 * Floating point has a different arithmetic and is an inexact number.
948 * So you should know its esoteric system. See following:
949 *
950 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
951 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#-why-are-rubys-floats-imprecise
952 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
953 *
954 * You can create a \Float object explicitly with:
955 *
956 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
957 *
958 * You can convert certain objects to Floats with:
959 *
960 * - \Method #Float.
961 *
962 * == What's Here
963 *
964 * First, what's elsewhere. \Class \Float:
965 *
966 * - Inherits from {class Numeric}[rdoc-ref:Numeric@What-27s+Here].
967 *
968 * Here, class \Float provides methods for:
969 *
970 * - {Querying}[rdoc-ref:Float@Querying]
971 * - {Comparing}[rdoc-ref:Float@Comparing]
972 * - {Converting}[rdoc-ref:Float@Converting]
973 *
974 * === Querying
975 *
976 * - #finite?: Returns whether +self+ is finite.
977 * - #hash: Returns the integer hash code for +self+.
978 * - #infinite?: Returns whether +self+ is infinite.
979 * - #nan?: Returns whether +self+ is a NaN (not-a-number).
980 *
981 * === Comparing
982 *
983 * - #<: Returns whether +self+ is less than the given value.
984 * - #<=: Returns whether +self+ is less than or equal to the given value.
985 * - #<=>: Returns a number indicating whether +self+ is less than, equal
986 * to, or greater than the given value.
987 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
988 * the given value.
989 * - #>: Returns whether +self+ is greater than the given value.
990 * - #>=: Returns whether +self+ is greater than or equal to the given value.
991 *
992 * === Converting
993 *
994 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
995 * - #*: Returns the product of +self+ and the given value.
996 * - #**: Returns the value of +self+ raised to the power of the given value.
997 * - #+: Returns the sum of +self+ and the given value.
998 * - #-: Returns the difference of +self+ and the given value.
999 * - #/: Returns the quotient of +self+ and the given value.
1000 * - #ceil: Returns the smallest number greater than or equal to +self+.
1001 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
1002 * and +self+
1003 * - #divmod: Returns a 2-element array containing the quotient and remainder
1004 * results of dividing +self+ by the given value.
1005 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
1006 * - #floor: Returns the greatest number smaller than or equal to +self+.
1007 * - #next_float: Returns the next-larger representable \Float.
1008 * - #prev_float: Returns the next-smaller representable \Float.
1009 * - #quo: Returns the quotient from dividing +self+ by the given value.
1010 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
1011 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
1012 * - #to_s (aliased as #inspect): Returns a string containing the place-value
1013 * representation of +self+ in the given radix.
1014 * - #truncate: Returns +self+ truncated to a given precision.
1015 *
1016 */
1017
1018 VALUE
1019rb_float_new_in_heap(double d)
1020{
1021 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0), sizeof(struct RFloat), 0);
1022
1023#if SIZEOF_DOUBLE <= SIZEOF_VALUE
1024 flt->float_value = d;
1025#else
1026 union {
1027 double d;
1028 rb_float_value_type v;
1029 } u = {d};
1030 flt->float_value = u.v;
1031#endif
1032 OBJ_FREEZE((VALUE)flt);
1033 return (VALUE)flt;
1034}
1035
1036/*
1037 * call-seq:
1038 * to_s -> string
1039 *
1040 * Returns a string containing a representation of +self+;
1041 * depending of the value of +self+, the string representation
1042 * may contain:
1043 *
1044 * - A fixed-point number.
1045 * - A number in "scientific notation" (containing an exponent).
1046 * - 'Infinity'.
1047 * - '-Infinity'.
1048 * - 'NaN' (indicating not-a-number).
1049 *
1050 * 3.14.to_s # => "3.14"
1051 * (10.1**50).to_s # => "1.644631821843879e+50"
1052 * (10.1**500).to_s # => "Infinity"
1053 * (-10.1**500).to_s # => "-Infinity"
1054 * (0.0/0.0).to_s # => "NaN"
1055 *
1056 */
1057
1058static VALUE
1059flo_to_s(VALUE flt)
1060{
1061 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
1062 enum {float_dig = DBL_DIG+1};
1063 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
1064 double value = RFLOAT_VALUE(flt);
1065 VALUE s;
1066 char *p, *e;
1067 int sign, decpt, digs;
1068
1069 if (isinf(value)) {
1070 static const char minf[] = "-Infinity";
1071 const int pos = (value > 0); /* skip "-" */
1072 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
1073 }
1074 else if (isnan(value))
1075 return rb_usascii_str_new2("NaN");
1076
1077 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
1078 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1079 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
1080 memcpy(buf, p, digs);
1081 free(p);
1082 if (decpt > 0) {
1083 if (decpt < digs) {
1084 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
1085 buf[decpt] = '.';
1086 rb_str_cat(s, buf, digs + 1);
1087 }
1088 else if (decpt <= DBL_DIG) {
1089 long len;
1090 char *ptr;
1091 rb_str_cat(s, buf, digs);
1092 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
1093 ptr = RSTRING_PTR(s) + len;
1094 if (decpt > digs) {
1095 memset(ptr, '0', decpt - digs);
1096 ptr += decpt - digs;
1097 }
1098 memcpy(ptr, ".0", 2);
1099 }
1100 else {
1101 goto exp;
1102 }
1103 }
1104 else if (decpt > -4) {
1105 long len;
1106 char *ptr;
1107 rb_str_cat(s, "0.", 2);
1108 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1109 ptr = RSTRING_PTR(s);
1110 memset(ptr += len, '0', -decpt);
1111 memcpy(ptr -= decpt, buf, digs);
1112 }
1113 else {
1114 goto exp;
1115 }
1116 return s;
1117
1118 exp:
1119 if (digs > 1) {
1120 memmove(buf + 2, buf + 1, digs - 1);
1121 }
1122 else {
1123 buf[2] = '0';
1124 digs++;
1125 }
1126 buf[1] = '.';
1127 rb_str_cat(s, buf, digs + 1);
1128 rb_str_catf(s, "e%+03d", decpt - 1);
1129 return s;
1130}
1131
1132/*
1133 * call-seq:
1134 * coerce(other) -> array
1135 *
1136 * Returns a 2-element array containing +other+ converted to a \Float
1137 * and +self+:
1138 *
1139 * f = 3.14 # => 3.14
1140 * f.coerce(2) # => [2.0, 3.14]
1141 * f.coerce(2.0) # => [2.0, 3.14]
1142 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1143 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1144 *
1145 * Raises an exception if a type conversion fails.
1146 *
1147 */
1148
1149static VALUE
1150flo_coerce(VALUE x, VALUE y)
1151{
1152 return rb_assoc_new(rb_Float(y), x);
1153}
1154
1155 VALUE
1156rb_float_uminus(VALUE flt)
1157{
1158 return DBL2NUM(-RFLOAT_VALUE(flt));
1159}
1160
1161/*
1162 * call-seq:
1163 * self + other -> numeric
1164 *
1165 * Returns a new \Float which is the sum of +self+ and +other+:
1166 *
1167 * f = 3.14
1168 * f + 1 # => 4.140000000000001
1169 * f + 1.0 # => 4.140000000000001
1170 * f + Rational(1, 1) # => 4.140000000000001
1171 * f + Complex(1, 0) # => (4.140000000000001+0i)
1172 *
1173 */
1174
1175 VALUE
1176rb_float_plus(VALUE x, VALUE y)
1177{
1178 if (FIXNUM_P(y)) {
1179 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1180 }
1181 else if (RB_BIGNUM_TYPE_P(y)) {
1182 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1183 }
1184 else if (RB_FLOAT_TYPE_P(y)) {
1185 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1186 }
1187 else {
1188 return rb_num_coerce_bin(x, y, '+');
1189 }
1190}
1191
1192/*
1193 * call-seq:
1194 * self - other -> numeric
1195 *
1196 * Returns a new \Float which is the difference of +self+ and +other+:
1197 *
1198 * f = 3.14
1199 * f - 1 # => 2.14
1200 * f - 1.0 # => 2.14
1201 * f - Rational(1, 1) # => 2.14
1202 * f - Complex(1, 0) # => (2.14+0i)
1203 *
1204 */
1205
1206 VALUE
1207rb_float_minus(VALUE x, VALUE y)
1208{
1209 if (FIXNUM_P(y)) {
1210 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1211 }
1212 else if (RB_BIGNUM_TYPE_P(y)) {
1213 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1214 }
1215 else if (RB_FLOAT_TYPE_P(y)) {
1216 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1217 }
1218 else {
1219 return rb_num_coerce_bin(x, y, '-');
1220 }
1221}
1222
1223/*
1224 * call-seq:
1225 * self * other -> numeric
1226 *
1227 * Returns a new \Float which is the product of +self+ and +other+:
1228 *
1229 * f = 3.14
1230 * f * 2 # => 6.28
1231 * f * 2.0 # => 6.28
1232 * f * Rational(1, 2) # => 1.57
1233 * f * Complex(2, 0) # => (6.28+0.0i)
1234 */
1235
1236 VALUE
1237rb_float_mul(VALUE x, VALUE y)
1238{
1239 if (FIXNUM_P(y)) {
1240 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1241 }
1242 else if (RB_BIGNUM_TYPE_P(y)) {
1243 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1244 }
1245 else if (RB_FLOAT_TYPE_P(y)) {
1246 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1247 }
1248 else {
1249 return rb_num_coerce_bin(x, y, '*');
1250 }
1251}
1252
1253static double
1254double_div_double(double x, double y)
1255{
1256 if (LIKELY(y != 0.0)) {
1257 return x / y;
1258 }
1259 else if (x == 0.0) {
1260 return nan("");
1261 }
1262 else {
1263 double z = signbit(y) ? -1.0 : 1.0;
1264 return x * z * HUGE_VAL;
1265 }
1266}
1267
1268 VALUE
1269rb_flo_div_flo(VALUE x, VALUE y)
1270{
1271 double num = RFLOAT_VALUE(x);
1272 double den = RFLOAT_VALUE(y);
1273 double ret = double_div_double(num, den);
1274 return DBL2NUM(ret);
1275}
1276
1277/*
1278 * call-seq:
1279 * self / other -> numeric
1280 *
1281 * Returns a new \Float which is the result of dividing +self+ by +other+:
1282 *
1283 * f = 3.14
1284 * f / 2 # => 1.57
1285 * f / 2.0 # => 1.57
1286 * f / Rational(2, 1) # => 1.57
1287 * f / Complex(2, 0) # => (1.57+0.0i)
1288 *
1289 */
1290
1291 VALUE
1292rb_float_div(VALUE x, VALUE y)
1293{
1294 double num = RFLOAT_VALUE(x);
1295 double den;
1296 double ret;
1297
1298 if (FIXNUM_P(y)) {
1299 den = FIX2LONG(y);
1300 }
1301 else if (RB_BIGNUM_TYPE_P(y)) {
1302 den = rb_big2dbl(y);
1303 }
1304 else if (RB_FLOAT_TYPE_P(y)) {
1305 den = RFLOAT_VALUE(y);
1306 }
1307 else {
1308 return rb_num_coerce_bin(x, y, '/');
1309 }
1310
1311 ret = double_div_double(num, den);
1312 return DBL2NUM(ret);
1313}
1314
1315/*
1316 * call-seq:
1317 * quo(other) -> numeric
1318 *
1319 * Returns the quotient from dividing +self+ by +other+:
1320 *
1321 * f = 3.14
1322 * f.quo(2) # => 1.57
1323 * f.quo(-2) # => -1.57
1324 * f.quo(Rational(2, 1)) # => 1.57
1325 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1326 *
1327 */
1328
1329static VALUE
1330flo_quo(VALUE x, VALUE y)
1331{
1332 return num_funcall1(x, '/', y);
1333}
1334
1335static void
1336flodivmod(double x, double y, double *divp, double *modp)
1337{
1338 double div, mod;
1339
1340 if (isnan(y)) {
1341 /* y is NaN so all results are NaN */
1342 if (modp) *modp = y;
1343 if (divp) *divp = y;
1344 return;
1345 }
1346 if (y == 0.0) rb_num_zerodiv();
1347 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1348 mod = x;
1349 else {
1350#ifdef HAVE_FMOD
1351 mod = fmod(x, y);
1352#else
1353 double z;
1354
1355 modf(x/y, &z);
1356 mod = x - z * y;
1357#endif
1358 }
1359 if (isinf(x) && !isinf(y))
1360 div = x;
1361 else {
1362 div = (x - mod) / y;
1363 if (modp && divp) div = round(div);
1364 }
1365 if (y*mod < 0) {
1366 mod += y;
1367 div -= 1.0;
1368 }
1369 if (modp) *modp = mod;
1370 if (divp) *divp = div;
1371}
1372
1373/*
1374 * Returns the modulo of division of x by y.
1375 * An error will be raised if y == 0.
1376 */
1377
1378double
1379ruby_float_mod(double x, double y)
1380{
1381 double mod;
1382 flodivmod(x, y, 0, &mod);
1383 return mod;
1384}
1385
1386/*
1387 * call-seq:
1388 * self % other -> float
1389 *
1390 * Returns +self+ modulo +other+ as a float.
1391 *
1392 * For float +f+ and real number +r+, these expressions are equivalent:
1393 *
1394 * f % r
1395 * f-r*(f/r).floor
1396 * f.divmod(r)[1]
1397 *
1398 * See Numeric#divmod.
1399 *
1400 * Examples:
1401 *
1402 * 10.0 % 2 # => 0.0
1403 * 10.0 % 3 # => 1.0
1404 * 10.0 % 4 # => 2.0
1405 *
1406 * 10.0 % -2 # => 0.0
1407 * 10.0 % -3 # => -2.0
1408 * 10.0 % -4 # => -2.0
1409 *
1410 * 10.0 % 4.0 # => 2.0
1411 * 10.0 % Rational(4, 1) # => 2.0
1412 *
1413 */
1414
1415static VALUE
1416flo_mod(VALUE x, VALUE y)
1417{
1418 double fy;
1419
1420 if (FIXNUM_P(y)) {
1421 fy = (double)FIX2LONG(y);
1422 }
1423 else if (RB_BIGNUM_TYPE_P(y)) {
1424 fy = rb_big2dbl(y);
1425 }
1426 else if (RB_FLOAT_TYPE_P(y)) {
1427 fy = RFLOAT_VALUE(y);
1428 }
1429 else {
1430 return rb_num_coerce_bin(x, y, '%');
1431 }
1432 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1433}
1434
1435static VALUE
1436dbl2ival(double d)
1437{
1438 if (FIXABLE(d)) {
1439 return LONG2FIX((long)d);
1440 }
1441 return rb_dbl2big(d);
1442}
1443
1444/*
1445 * call-seq:
1446 * divmod(other) -> array
1447 *
1448 * Returns a 2-element array <tt>[q, r]</tt>, where
1449 *
1450 * q = (self/other).floor # Quotient
1451 * r = self % other # Remainder
1452 *
1453 * Examples:
1454 *
1455 * 11.0.divmod(4) # => [2, 3.0]
1456 * 11.0.divmod(-4) # => [-3, -1.0]
1457 * -11.0.divmod(4) # => [-3, 1.0]
1458 * -11.0.divmod(-4) # => [2, -3.0]
1459 *
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 * -12.0.divmod(-4) # => [3, -0.0]
1464 *
1465 * 13.0.divmod(4.0) # => [3, 1.0]
1466 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1467 *
1468 */
1469
1470static VALUE
1471flo_divmod(VALUE x, VALUE y)
1472{
1473 double fy, div, mod;
1474 volatile VALUE a, b;
1475
1476 if (FIXNUM_P(y)) {
1477 fy = (double)FIX2LONG(y);
1478 }
1479 else if (RB_BIGNUM_TYPE_P(y)) {
1480 fy = rb_big2dbl(y);
1481 }
1482 else if (RB_FLOAT_TYPE_P(y)) {
1483 fy = RFLOAT_VALUE(y);
1484 }
1485 else {
1486 return rb_num_coerce_bin(x, y, id_divmod);
1487 }
1488 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1489 a = dbl2ival(div);
1490 b = DBL2NUM(mod);
1491 return rb_assoc_new(a, b);
1492}
1493
1494/*
1495 * call-seq:
1496 * self ** other -> numeric
1497 *
1498 * Raises +self+ to the power of +other+:
1499 *
1500 * f = 3.14
1501 * f ** 2 # => 9.8596
1502 * f ** -2 # => 0.1014239928597509
1503 * f ** 2.1 # => 11.054834900588839
1504 * f ** Rational(2, 1) # => 9.8596
1505 * f ** Complex(2, 0) # => (9.8596+0i)
1506 *
1507 */
1508
1509 VALUE
1510rb_float_pow(VALUE x, VALUE y)
1511{
1512 double dx, dy;
1513 if (y == INT2FIX(2)) {
1514 dx = RFLOAT_VALUE(x);
1515 return DBL2NUM(dx * dx);
1516 }
1517 else if (FIXNUM_P(y)) {
1518 dx = RFLOAT_VALUE(x);
1519 dy = (double)FIX2LONG(y);
1520 }
1521 else if (RB_BIGNUM_TYPE_P(y)) {
1522 dx = RFLOAT_VALUE(x);
1523 dy = rb_big2dbl(y);
1524 }
1525 else if (RB_FLOAT_TYPE_P(y)) {
1526 dx = RFLOAT_VALUE(x);
1527 dy = RFLOAT_VALUE(y);
1528 if (dx < 0 && dy != round(dy))
1529 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1530 }
1531 else {
1532 return rb_num_coerce_bin(x, y, idPow);
1533 }
1534 return DBL2NUM(pow(dx, dy));
1535}
1536
1537/*
1538 * call-seq:
1539 * eql?(other) -> true or false
1540 *
1541 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1542 *
1543 * Of the Core and Standard Library classes,
1544 * only Integer, Rational, and Complex use this implementation.
1545 *
1546 * Examples:
1547 *
1548 * 1.eql?(1) # => true
1549 * 1.eql?(1.0) # => false
1550 * 1.eql?(Rational(1, 1)) # => false
1551 * 1.eql?(Complex(1, 0)) # => false
1552 *
1553 * \Method +eql?+ is different from +==+ in that +eql?+ requires matching types,
1554 * while +==+ does not.
1555 *
1556 */
1557
1558static VALUE
1559num_eql(VALUE x, VALUE y)
1560{
1561 if (TYPE(x) != TYPE(y)) return Qfalse;
1562
1563 if (RB_BIGNUM_TYPE_P(x)) {
1564 return rb_big_eql(x, y);
1565 }
1566
1567 return rb_equal(x, y);
1568}
1569
1570/*
1571 * call-seq:
1572 * self <=> other -> zero or nil
1573 *
1574 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1575 *
1576 * No subclass in the Ruby Core or Standard Library uses this implementation.
1577 *
1578 */
1579
1580static VALUE
1581num_cmp(VALUE x, VALUE y)
1582{
1583 if (x == y) return INT2FIX(0);
1584 return Qnil;
1585}
1586
1587static VALUE
1588num_equal(VALUE x, VALUE y)
1589{
1590 VALUE result;
1591 if (x == y) return Qtrue;
1592 result = num_funcall1(y, id_eq, x);
1593 return RBOOL(RTEST(result));
1594}
1595
1596/*
1597 * call-seq:
1598 * self == other -> true or false
1599 *
1600 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1601 *
1602 * 2.0 == 2 # => true
1603 * 2.0 == 2.0 # => true
1604 * 2.0 == Rational(2, 1) # => true
1605 * 2.0 == Complex(2, 0) # => true
1606 *
1607 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1608 *
1609 * Related: Float#eql? (requires +other+ to be a \Float).
1610 *
1611 */
1612
1613 VALUE
1614rb_float_equal(VALUE x, VALUE y)
1615{
1616 volatile double a, b;
1617
1618 if (RB_INTEGER_TYPE_P(y)) {
1619 return rb_integer_float_eq(y, x);
1620 }
1621 else if (RB_FLOAT_TYPE_P(y)) {
1622 b = RFLOAT_VALUE(y);
1623#if MSC_VERSION_BEFORE(1300)
1624 if (isnan(b)) return Qfalse;
1625#endif
1626 }
1627 else {
1628 return num_equal(x, y);
1629 }
1630 a = RFLOAT_VALUE(x);
1631#if MSC_VERSION_BEFORE(1300)
1632 if (isnan(a)) return Qfalse;
1633#endif
1634 return RBOOL(a == b);
1635}
1636
1637#define flo_eq rb_float_equal
1638static VALUE rb_dbl_hash(double d);
1639
1640/*
1641 * call-seq:
1642 * hash -> integer
1643 *
1644 * Returns the integer hash value for +self+.
1645 *
1646 * See also Object#hash.
1647 */
1648
1649static VALUE
1650flo_hash(VALUE num)
1651{
1652 return rb_dbl_hash(RFLOAT_VALUE(num));
1653}
1654
1655static VALUE
1656rb_dbl_hash(double d)
1657{
1658 return ST2FIX(rb_dbl_long_hash(d));
1659}
1660
1661 VALUE
1662rb_dbl_cmp(double a, double b)
1663{
1664 if (isnan(a) || isnan(b)) return Qnil;
1665 if (a == b) return INT2FIX(0);
1666 if (a > b) return INT2FIX(1);
1667 if (a < b) return INT2FIX(-1);
1668 return Qnil;
1669}
1670
1671/*
1672 * call-seq:
1673 * self <=> other -> -1, 0, +1, or nil
1674 *
1675 * Returns a value that depends on the numeric relation
1676 * between +self+ and +other+:
1677 *
1678 * - -1, if +self+ is less than +other+.
1679 * - 0, if +self+ is equal to +other+.
1680 * - 1, if +self+ is greater than +other+.
1681 * - +nil+, if the two values are incommensurate.
1682 *
1683 * Examples:
1684 *
1685 * 2.0 <=> 2 # => 0
1686 * 2.0 <=> 2.0 # => 0
1687 * 2.0 <=> Rational(2, 1) # => 0
1688 * 2.0 <=> Complex(2, 0) # => 0
1689 * 2.0 <=> 1.9 # => 1
1690 * 2.0 <=> 2.1 # => -1
1691 * 2.0 <=> 'foo' # => nil
1692 *
1693 * This is the basis for the tests in the Comparable module.
1694 *
1695 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1696 *
1697 */
1698
1699static VALUE
1700flo_cmp(VALUE x, VALUE y)
1701{
1702 double a, b;
1703 VALUE i;
1704
1705 a = RFLOAT_VALUE(x);
1706 if (isnan(a)) return Qnil;
1707 if (RB_INTEGER_TYPE_P(y)) {
1708 VALUE rel = rb_integer_float_cmp(y, x);
1709 if (FIXNUM_P(rel))
1710 return LONG2FIX(-FIX2LONG(rel));
1711 return rel;
1712 }
1713 else if (RB_FLOAT_TYPE_P(y)) {
1714 b = RFLOAT_VALUE(y);
1715 }
1716 else {
1717 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1718 if (RTEST(i)) {
1719 int j = rb_cmpint(i, x, y);
1720 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1721 return INT2FIX(j);
1722 }
1723 if (a > 0.0) return INT2FIX(1);
1724 return INT2FIX(-1);
1725 }
1726 return rb_num_coerce_cmp(x, y, id_cmp);
1727 }
1728 return rb_dbl_cmp(a, b);
1729}
1730
1731int
1732rb_float_cmp(VALUE x, VALUE y)
1733{
1734 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1735}
1736
1737/*
1738 * call-seq:
1739 * self > other -> true or false
1740 *
1741 * Returns +true+ if +self+ is numerically greater than +other+:
1742 *
1743 * 2.0 > 1 # => true
1744 * 2.0 > 1.0 # => true
1745 * 2.0 > Rational(1, 2) # => true
1746 * 2.0 > 2.0 # => false
1747 *
1748 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1749 *
1750 */
1751
1752 VALUE
1753rb_float_gt(VALUE x, VALUE y)
1754{
1755 double a, b;
1756
1757 a = RFLOAT_VALUE(x);
1758 if (RB_INTEGER_TYPE_P(y)) {
1759 VALUE rel = rb_integer_float_cmp(y, x);
1760 if (FIXNUM_P(rel))
1761 return RBOOL(-FIX2LONG(rel) > 0);
1762 return Qfalse;
1763 }
1764 else if (RB_FLOAT_TYPE_P(y)) {
1765 b = RFLOAT_VALUE(y);
1766#if MSC_VERSION_BEFORE(1300)
1767 if (isnan(b)) return Qfalse;
1768#endif
1769 }
1770 else {
1771 return rb_num_coerce_relop(x, y, '>');
1772 }
1773#if MSC_VERSION_BEFORE(1300)
1774 if (isnan(a)) return Qfalse;
1775#endif
1776 return RBOOL(a > b);
1777}
1778
1779/*
1780 * call-seq:
1781 * self >= other -> true or false
1782 *
1783 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1784 *
1785 * 2.0 >= 1 # => true
1786 * 2.0 >= 1.0 # => true
1787 * 2.0 >= Rational(1, 2) # => true
1788 * 2.0 >= 2.0 # => true
1789 * 2.0 >= 2.1 # => false
1790 *
1791 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1792 *
1793 */
1794
1795static VALUE
1796flo_ge(VALUE x, VALUE y)
1797{
1798 double a, b;
1799
1800 a = RFLOAT_VALUE(x);
1801 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1802 VALUE rel = rb_integer_float_cmp(y, x);
1803 if (FIXNUM_P(rel))
1804 return RBOOL(-FIX2LONG(rel) >= 0);
1805 return Qfalse;
1806 }
1807 else if (RB_FLOAT_TYPE_P(y)) {
1808 b = RFLOAT_VALUE(y);
1809#if MSC_VERSION_BEFORE(1300)
1810 if (isnan(b)) return Qfalse;
1811#endif
1812 }
1813 else {
1814 return rb_num_coerce_relop(x, y, idGE);
1815 }
1816#if MSC_VERSION_BEFORE(1300)
1817 if (isnan(a)) return Qfalse;
1818#endif
1819 return RBOOL(a >= b);
1820}
1821
1822/*
1823 * call-seq:
1824 * self < other -> true or false
1825 *
1826 * Returns +true+ if +self+ is numerically less than +other+:
1827 *
1828 * 2.0 < 3 # => true
1829 * 2.0 < 3.0 # => true
1830 * 2.0 < Rational(3, 1) # => true
1831 * 2.0 < 2.0 # => false
1832 *
1833 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1834 *
1835 */
1836
1837static VALUE
1838flo_lt(VALUE x, VALUE y)
1839{
1840 double a, b;
1841
1842 a = RFLOAT_VALUE(x);
1843 if (RB_INTEGER_TYPE_P(y)) {
1844 VALUE rel = rb_integer_float_cmp(y, x);
1845 if (FIXNUM_P(rel))
1846 return RBOOL(-FIX2LONG(rel) < 0);
1847 return Qfalse;
1848 }
1849 else if (RB_FLOAT_TYPE_P(y)) {
1850 b = RFLOAT_VALUE(y);
1851#if MSC_VERSION_BEFORE(1300)
1852 if (isnan(b)) return Qfalse;
1853#endif
1854 }
1855 else {
1856 return rb_num_coerce_relop(x, y, '<');
1857 }
1858#if MSC_VERSION_BEFORE(1300)
1859 if (isnan(a)) return Qfalse;
1860#endif
1861 return RBOOL(a < b);
1862}
1863
1864/*
1865 * call-seq:
1866 * self <= other -> true or false
1867 *
1868 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1869 *
1870 * 2.0 <= 3 # => true
1871 * 2.0 <= 3.0 # => true
1872 * 2.0 <= Rational(3, 1) # => true
1873 * 2.0 <= 2.0 # => true
1874 * 2.0 <= 1.0 # => false
1875 *
1876 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1877 *
1878 */
1879
1880static VALUE
1881flo_le(VALUE x, VALUE y)
1882{
1883 double a, b;
1884
1885 a = RFLOAT_VALUE(x);
1886 if (RB_INTEGER_TYPE_P(y)) {
1887 VALUE rel = rb_integer_float_cmp(y, x);
1888 if (FIXNUM_P(rel))
1889 return RBOOL(-FIX2LONG(rel) <= 0);
1890 return Qfalse;
1891 }
1892 else if (RB_FLOAT_TYPE_P(y)) {
1893 b = RFLOAT_VALUE(y);
1894#if MSC_VERSION_BEFORE(1300)
1895 if (isnan(b)) return Qfalse;
1896#endif
1897 }
1898 else {
1899 return rb_num_coerce_relop(x, y, idLE);
1900 }
1901#if MSC_VERSION_BEFORE(1300)
1902 if (isnan(a)) return Qfalse;
1903#endif
1904 return RBOOL(a <= b);
1905}
1906
1907/*
1908 * call-seq:
1909 * eql?(other) -> true or false
1910 *
1911 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1912 * +false+ otherwise:
1913 *
1914 * 2.0.eql?(2.0) # => true
1915 * 2.0.eql?(1.0) # => false
1916 * 2.0.eql?(1) # => false
1917 * 2.0.eql?(Rational(2, 1)) # => false
1918 * 2.0.eql?(Complex(2, 0)) # => false
1919 *
1920 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1921 *
1922 * Related: Float#== (performs type conversions).
1923 */
1924
1925 VALUE
1926rb_float_eql(VALUE x, VALUE y)
1927{
1928 if (RB_FLOAT_TYPE_P(y)) {
1929 double a = RFLOAT_VALUE(x);
1930 double b = RFLOAT_VALUE(y);
1931#if MSC_VERSION_BEFORE(1300)
1932 if (isnan(a) || isnan(b)) return Qfalse;
1933#endif
1934 return RBOOL(a == b);
1935 }
1936 return Qfalse;
1937}
1938
1939#define flo_eql rb_float_eql
1940
1941 VALUE
1942rb_float_abs(VALUE flt)
1943{
1944 double val = fabs(RFLOAT_VALUE(flt));
1945 return DBL2NUM(val);
1946}
1947
1948/*
1949 * call-seq:
1950 * nan? -> true or false
1951 *
1952 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1953 *
1954 * f = -1.0 #=> -1.0
1955 * f.nan? #=> false
1956 * f = 0.0/0.0 #=> NaN
1957 * f.nan? #=> true
1958 */
1959
1960static VALUE
1961flo_is_nan_p(VALUE num)
1962{
1963 double value = RFLOAT_VALUE(num);
1964
1965 return RBOOL(isnan(value));
1966}
1967
1968/*
1969 * call-seq:
1970 * infinite? -> -1, 1, or nil
1971 *
1972 * Returns:
1973 *
1974 * - 1, if +self+ is <tt>Infinity</tt>.
1975 * - -1 if +self+ is <tt>-Infinity</tt>.
1976 * - +nil+, otherwise.
1977 *
1978 * Examples:
1979 *
1980 * f = 1.0/0.0 # => Infinity
1981 * f.infinite? # => 1
1982 * f = -1.0/0.0 # => -Infinity
1983 * f.infinite? # => -1
1984 * f = 1.0 # => 1.0
1985 * f.infinite? # => nil
1986 * f = 0.0/0.0 # => NaN
1987 * f.infinite? # => nil
1988 *
1989 */
1990
1991 VALUE
1992rb_flo_is_infinite_p(VALUE num)
1993{
1994 double value = RFLOAT_VALUE(num);
1995
1996 if (isinf(value)) {
1997 return INT2FIX( value < 0 ? -1 : 1 );
1998 }
1999
2000 return Qnil;
2001}
2002
2003/*
2004 * call-seq:
2005 * finite? -> true or false
2006 *
2007 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
2008 * +false+ otherwise:
2009 *
2010 * f = 2.0 # => 2.0
2011 * f.finite? # => true
2012 * f = 1.0/0.0 # => Infinity
2013 * f.finite? # => false
2014 * f = -1.0/0.0 # => -Infinity
2015 * f.finite? # => false
2016 * f = 0.0/0.0 # => NaN
2017 * f.finite? # => false
2018 *
2019 */
2020
2021 VALUE
2022rb_flo_is_finite_p(VALUE num)
2023{
2024 double value = RFLOAT_VALUE(num);
2025
2026 return RBOOL(isfinite(value));
2027}
2028
2029static VALUE
2030flo_nextafter(VALUE flo, double value)
2031{
2032 double x, y;
2033 x = NUM2DBL(flo);
2034 y = nextafter(x, value);
2035 return DBL2NUM(y);
2036}
2037
2038/*
2039 * call-seq:
2040 * next_float -> float
2041 *
2042 * Returns the next-larger representable \Float.
2043 *
2044 * These examples show the internally stored values (64-bit hexadecimal)
2045 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2046 *
2047 * f = 0.0 # 0x0000000000000000
2048 * f.next_float # 0x0000000000000001
2049 *
2050 * f = 0.01 # 0x3f847ae147ae147b
2051 * f.next_float # 0x3f847ae147ae147c
2052 *
2053 * In the remaining examples here, the output is shown in the usual way
2054 * (result +to_s+):
2055 *
2056 * 0.01.next_float # => 0.010000000000000002
2057 * 1.0.next_float # => 1.0000000000000002
2058 * 100.0.next_float # => 100.00000000000001
2059 *
2060 * f = 0.01
2061 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2062 *
2063 * Output:
2064 *
2065 * 0 0x1.47ae147ae147bp-7 0.01
2066 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2067 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2068 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2069 *
2070 * f = 0.0; 100.times { f += 0.1 }
2071 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2072 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2073 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2074 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2075 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2076 * "%a" % 10 # => "0x1.4p+3"
2077 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2078 *
2079 * Related: Float#prev_float
2080 *
2081 */
2082static VALUE
2083flo_next_float(VALUE vx)
2084{
2085 return flo_nextafter(vx, HUGE_VAL);
2086}
2087
2088/*
2089 * call-seq:
2090 * float.prev_float -> float
2091 *
2092 * Returns the next-smaller representable \Float.
2093 *
2094 * These examples show the internally stored values (64-bit hexadecimal)
2095 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2096 *
2097 * f = 5e-324 # 0x0000000000000001
2098 * f.prev_float # 0x0000000000000000
2099 *
2100 * f = 0.01 # 0x3f847ae147ae147b
2101 * f.prev_float # 0x3f847ae147ae147a
2102 *
2103 * In the remaining examples here, the output is shown in the usual way
2104 * (result +to_s+):
2105 *
2106 * 0.01.prev_float # => 0.009999999999999998
2107 * 1.0.prev_float # => 0.9999999999999999
2108 * 100.0.prev_float # => 99.99999999999999
2109 *
2110 * f = 0.01
2111 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2112 *
2113 * Output:
2114 *
2115 * 0 0x1.47ae147ae147bp-7 0.01
2116 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2117 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2118 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2119 *
2120 * Related: Float#next_float.
2121 *
2122 */
2123static VALUE
2124flo_prev_float(VALUE vx)
2125{
2126 return flo_nextafter(vx, -HUGE_VAL);
2127}
2128
2129 VALUE
2130rb_float_floor(VALUE num, int ndigits)
2131{
2132 double number;
2133 number = RFLOAT_VALUE(num);
2134 if (number == 0.0) {
2135 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2136 }
2137 if (ndigits > 0) {
2138 int binexp;
2139 double f, mul, res;
2140 frexp(number, &binexp);
2141 if (float_round_overflow(ndigits, binexp)) return num;
2142 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2143 return DBL2NUM(0.0);
2144 f = pow(10, ndigits);
2145 mul = floor(number * f);
2146 res = (mul + 1) / f;
2147 if (res > number)
2148 res = mul / f;
2149 return DBL2NUM(res);
2150 }
2151 else {
2152 num = dbl2ival(floor(number));
2153 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2154 return num;
2155 }
2156}
2157
2158static int
2159flo_ndigits(int argc, VALUE *argv)
2160{
2161 if (rb_check_arity(argc, 0, 1)) {
2162 return NUM2INT(argv[0]);
2163 }
2164 return 0;
2165}
2166
2167/*
2168 * call-seq:
2169 * floor(ndigits = 0) -> float or integer
2170 *
2171 * Returns the largest number less than or equal to +self+ with
2172 * a precision of +ndigits+ decimal digits.
2173 *
2174 * When +ndigits+ is positive, returns a float with +ndigits+
2175 * digits after the decimal point (as available):
2176 *
2177 * f = 12345.6789
2178 * f.floor(1) # => 12345.6
2179 * f.floor(3) # => 12345.678
2180 * f = -12345.6789
2181 * f.floor(1) # => -12345.7
2182 * f.floor(3) # => -12345.679
2183 *
2184 * When +ndigits+ is non-positive, returns an integer with at least
2185 * <code>ndigits.abs</code> trailing zeros:
2186 *
2187 * f = 12345.6789
2188 * f.floor(0) # => 12345
2189 * f.floor(-3) # => 12000
2190 * f = -12345.6789
2191 * f.floor(0) # => -12346
2192 * f.floor(-3) # => -13000
2193 *
2194 * Note that the limited precision of floating-point arithmetic
2195 * may lead to surprising results:
2196 *
2197 * (0.3 / 0.1).floor #=> 2 (!)
2198 *
2199 * Related: Float#ceil.
2200 *
2201 */
2202
2203static VALUE
2204flo_floor(int argc, VALUE *argv, VALUE num)
2205{
2206 int ndigits = flo_ndigits(argc, argv);
2207 return rb_float_floor(num, ndigits);
2208}
2209
2210/*
2211 * call-seq:
2212 * ceil(ndigits = 0) -> float or integer
2213 *
2214 * Returns the smallest number greater than or equal to +self+ with
2215 * a precision of +ndigits+ decimal digits.
2216 *
2217 * When +ndigits+ is positive, returns a float with +ndigits+
2218 * digits after the decimal point (as available):
2219 *
2220 * f = 12345.6789
2221 * f.ceil(1) # => 12345.7
2222 * f.ceil(3) # => 12345.679
2223 * f = -12345.6789
2224 * f.ceil(1) # => -12345.6
2225 * f.ceil(3) # => -12345.678
2226 *
2227 * When +ndigits+ is non-positive, returns an integer with at least
2228 * <code>ndigits.abs</code> trailing zeros:
2229 *
2230 * f = 12345.6789
2231 * f.ceil(0) # => 12346
2232 * f.ceil(-3) # => 13000
2233 * f = -12345.6789
2234 * f.ceil(0) # => -12345
2235 * f.ceil(-3) # => -12000
2236 *
2237 * Note that the limited precision of floating-point arithmetic
2238 * may lead to surprising results:
2239 *
2240 * (2.1 / 0.7).ceil #=> 4 (!)
2241 *
2242 * Related: Float#floor.
2243 *
2244 */
2245
2246static VALUE
2247flo_ceil(int argc, VALUE *argv, VALUE num)
2248{
2249 int ndigits = flo_ndigits(argc, argv);
2250 return rb_float_ceil(num, ndigits);
2251}
2252
2253 VALUE
2254rb_float_ceil(VALUE num, int ndigits)
2255{
2256 double number, f;
2257
2258 number = RFLOAT_VALUE(num);
2259 if (number == 0.0) {
2260 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2261 }
2262 if (ndigits > 0) {
2263 int binexp;
2264 frexp(number, &binexp);
2265 if (float_round_overflow(ndigits, binexp)) return num;
2266 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2267 return DBL2NUM(0.0);
2268 f = pow(10, ndigits);
2269 f = ceil(number * f) / f;
2270 return DBL2NUM(f);
2271 }
2272 else {
2273 num = dbl2ival(ceil(number));
2274 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2275 return num;
2276 }
2277}
2278
2279static int
2280int_round_zero_p(VALUE num, int ndigits)
2281{
2282 long bytes;
2283 /* If 10**N / 2 > num, then return 0 */
2284 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2285 if (FIXNUM_P(num)) {
2286 bytes = sizeof(long);
2287 }
2288 else if (RB_BIGNUM_TYPE_P(num)) {
2289 bytes = rb_big_size(num);
2290 }
2291 else {
2292 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2293 }
2294 return (-0.415241 * ndigits - 0.125 > bytes);
2295}
2296
2297static SIGNED_VALUE
2298int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2299{
2300 SIGNED_VALUE z = +(x + y / 2) / y;
2301 if ((z * y - x) * 2 == y) {
2302 z &= ~1;
2303 }
2304 return z * y;
2305}
2306
2307static SIGNED_VALUE
2308int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2309{
2310 return (x + y / 2) / y * y;
2311}
2312
2313static SIGNED_VALUE
2314int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2315{
2316 return (x + y / 2 - 1) / y * y;
2317}
2318
2319static int
2320int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2321{
2322 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2323}
2324
2325static int
2326int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2327{
2328 return int_pos_p(num);
2329}
2330
2331static int
2332int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2333{
2334 return int_neg_p(num);
2335}
2336
2337/*
2338 * Assumes num is an \Integer, ndigits <= 0
2339 */
2340static VALUE
2341rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2342{
2343 VALUE n, f, h, r;
2344
2345 if (int_round_zero_p(num, ndigits)) {
2346 return INT2FIX(0);
2347 }
2348
2349 f = int_pow(10, -ndigits);
2350 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2351 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2352 int neg = x < 0;
2353 if (neg) x = -x;
2354 x = ROUND_CALL(mode, int_round, (x, y));
2355 if (neg) x = -x;
2356 return LONG2NUM(x);
2357 }
2358 if (RB_FLOAT_TYPE_P(f)) {
2359 /* then int_pow overflow */
2360 return INT2FIX(0);
2361 }
2362 h = rb_int_idiv(f, INT2FIX(2));
2363 r = rb_int_modulo(num, f);
2364 n = rb_int_minus(num, r);
2365 r = rb_int_cmp(r, h);
2366 if (FIXNUM_POSITIVE_P(r) ||
2367 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2368 n = rb_int_plus(n, f);
2369 }
2370 return n;
2371}
2372
2373static VALUE
2374rb_int_floor(VALUE num, int ndigits)
2375{
2376 VALUE f = int_pow(10, -ndigits);
2377 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2378 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2379 int neg = x < 0;
2380 if (neg) x = -x + y - 1;
2381 x = x / y * y;
2382 if (neg) x = -x;
2383 return LONG2NUM(x);
2384 }
2385 else {
2386 bool neg = int_neg_p(num);
2387 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2388 num = rb_int_mul(rb_int_div(num, f), f);
2389 if (neg) num = rb_int_uminus(num);
2390 return num;
2391 }
2392}
2393
2394static VALUE
2395rb_int_ceil(VALUE num, int ndigits)
2396{
2397 VALUE f = int_pow(10, -ndigits);
2398 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2399 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2400 int neg = x < 0;
2401 if (neg) x = -x;
2402 else x += y - 1;
2403 x = (x / y) * y;
2404 if (neg) x = -x;
2405 return LONG2NUM(x);
2406 }
2407 else {
2408 bool neg = int_neg_p(num);
2409 if (neg)
2410 num = rb_int_uminus(num);
2411 else
2412 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2413 num = rb_int_mul(rb_int_div(num, f), f);
2414 if (neg) num = rb_int_uminus(num);
2415 return num;
2416 }
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 */
2595
2596static VALUE
2597flo_to_i(VALUE num)
2598{
2599 double f = RFLOAT_VALUE(num);
2600
2601 if (f > 0.0) f = floor(f);
2602 if (f < 0.0) f = ceil(f);
2603
2604 return dbl2ival(f);
2605}
2606
2607/*
2608 * call-seq:
2609 * truncate(ndigits = 0) -> float or integer
2610 *
2611 * Returns +self+ truncated (toward zero) to
2612 * a precision of +ndigits+ decimal digits.
2613 *
2614 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2615 * after the decimal point (as available):
2616 *
2617 * f = 12345.6789
2618 * f.truncate(1) # => 12345.6
2619 * f.truncate(3) # => 12345.678
2620 * f = -12345.6789
2621 * f.truncate(1) # => -12345.6
2622 * f.truncate(3) # => -12345.678
2623 *
2624 * When +ndigits+ is negative, returns an integer
2625 * with at least <tt>ndigits.abs</tt> trailing zeros:
2626 *
2627 * f = 12345.6789
2628 * f.truncate(0) # => 12345
2629 * f.truncate(-3) # => 12000
2630 * f = -12345.6789
2631 * f.truncate(0) # => -12345
2632 * f.truncate(-3) # => -12000
2633 *
2634 * Note that the limited precision of floating-point arithmetic
2635 * may lead to surprising results:
2636 *
2637 * (0.3 / 0.1).truncate #=> 2 (!)
2638 *
2639 * Related: Float#round.
2640 *
2641 */
2642static VALUE
2643flo_truncate(int argc, VALUE *argv, VALUE num)
2644{
2645 if (signbit(RFLOAT_VALUE(num)))
2646 return flo_ceil(argc, argv, num);
2647 else
2648 return flo_floor(argc, argv, num);
2649}
2650
2651/*
2652 * call-seq:
2653 * floor(digits = 0) -> integer or float
2654 *
2655 * Returns the largest number that is less than or equal to +self+ with
2656 * a precision of +digits+ decimal digits.
2657 *
2658 * \Numeric implements this by converting +self+ to a Float and
2659 * invoking Float#floor.
2660 */
2661
2662static VALUE
2663num_floor(int argc, VALUE *argv, VALUE num)
2664{
2665 return flo_floor(argc, argv, rb_Float(num));
2666}
2667
2668/*
2669 * call-seq:
2670 * ceil(digits = 0) -> integer or float
2671 *
2672 * Returns the smallest number that is greater than or equal to +self+ with
2673 * a precision of +digits+ decimal digits.
2674 *
2675 * \Numeric implements this by converting +self+ to a Float and
2676 * invoking Float#ceil.
2677 */
2678
2679static VALUE
2680num_ceil(int argc, VALUE *argv, VALUE num)
2681{
2682 return flo_ceil(argc, argv, rb_Float(num));
2683}
2684
2685/*
2686 * call-seq:
2687 * round(digits = 0) -> integer or float
2688 *
2689 * Returns +self+ rounded to the nearest value with
2690 * a precision of +digits+ decimal digits.
2691 *
2692 * \Numeric implements this by converting +self+ to a Float and
2693 * invoking Float#round.
2694 */
2695
2696static VALUE
2697num_round(int argc, VALUE* argv, VALUE num)
2698{
2699 return flo_round(argc, argv, rb_Float(num));
2700}
2701
2702/*
2703 * call-seq:
2704 * truncate(digits = 0) -> integer or float
2705 *
2706 * Returns +self+ truncated (toward zero) to
2707 * a precision of +digits+ decimal digits.
2708 *
2709 * \Numeric implements this by converting +self+ to a Float and
2710 * invoking Float#truncate.
2711 */
2712
2713static VALUE
2714num_truncate(int argc, VALUE *argv, VALUE num)
2715{
2716 return flo_truncate(argc, argv, rb_Float(num));
2717}
2718
2719double
2720ruby_float_step_size(double beg, double end, double unit, int excl)
2721{
2722 const double epsilon = DBL_EPSILON;
2723 double d, n, err;
2724
2725 if (unit == 0) {
2726 return HUGE_VAL;
2727 }
2728 if (isinf(unit)) {
2729 return unit > 0 ? beg <= end : beg >= end;
2730 }
2731 n= (end - beg)/unit;
2732 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2733 if (err>0.5) err=0.5;
2734 if (excl) {
2735 if (n<=0) return 0;
2736 if (n<1)
2737 n = 0;
2738 else
2739 n = floor(n - err);
2740 d = +((n + 1) * unit) + beg;
2741 if (beg < end) {
2742 if (d < end)
2743 n++;
2744 }
2745 else if (beg > end) {
2746 if (d > end)
2747 n++;
2748 }
2749 }
2750 else {
2751 if (n<0) return 0;
2752 n = floor(n + err);
2753 d = +((n + 1) * unit) + beg;
2754 if (beg < end) {
2755 if (d <= end)
2756 n++;
2757 }
2758 else if (beg > end) {
2759 if (d >= end)
2760 n++;
2761 }
2762 }
2763 return n+1;
2764}
2765
2766int
2767ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2768{
2769 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2770 double unit = NUM2DBL(step);
2771 double beg = NUM2DBL(from);
2772 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2773 double n = ruby_float_step_size(beg, end, unit, excl);
2774 long i;
2775
2776 if (isinf(unit)) {
2777 /* if unit is infinity, i*unit+beg is NaN */
2778 if (n) rb_yield(DBL2NUM(beg));
2779 }
2780 else if (unit == 0) {
2781 VALUE val = DBL2NUM(beg);
2782 for (;;)
2783 rb_yield(val);
2784 }
2785 else {
2786 for (i=0; i<n; i++) {
2787 double d = i*unit+beg;
2788 if (unit >= 0 ? end < d : d < end) d = end;
2789 rb_yield(DBL2NUM(d));
2790 }
2791 }
2792 return TRUE;
2793 }
2794 return FALSE;
2795}
2796
2797 VALUE
2798ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2799{
2800 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2801 long delta, diff;
2802
2803 diff = FIX2LONG(step);
2804 if (diff == 0) {
2805 return DBL2NUM(HUGE_VAL);
2806 }
2807 delta = FIX2LONG(to) - FIX2LONG(from);
2808 if (diff < 0) {
2809 diff = -diff;
2810 delta = -delta;
2811 }
2812 if (excl) {
2813 delta--;
2814 }
2815 if (delta < 0) {
2816 return INT2FIX(0);
2817 }
2818 return ULONG2NUM(delta / diff + 1UL);
2819 }
2820 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2821 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2822
2823 if (isinf(n)) return DBL2NUM(n);
2824 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2825 return rb_dbl2big(n);
2826 }
2827 else {
2828 VALUE result;
2829 ID cmp = '>';
2830 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2831 case 0: return DBL2NUM(HUGE_VAL);
2832 case -1: cmp = '<'; break;
2833 }
2834 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2835 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2836 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2837 result = rb_funcall(result, '+', 1, INT2FIX(1));
2838 }
2839 return result;
2840 }
2841}
2842
2843static int
2844num_step_negative_p(VALUE num)
2845{
2846 const ID mid = '<';
2847 VALUE zero = INT2FIX(0);
2848 VALUE r;
2849
2850 if (FIXNUM_P(num)) {
2851 if (method_basic_p(rb_cInteger))
2852 return (SIGNED_VALUE)num < 0;
2853 }
2854 else if (RB_BIGNUM_TYPE_P(num)) {
2855 if (method_basic_p(rb_cInteger))
2856 return BIGNUM_NEGATIVE_P(num);
2857 }
2858
2859 r = rb_check_funcall(num, '>', 1, &zero);
2860 if (UNDEF_P(r)) {
2861 coerce_failed(num, INT2FIX(0));
2862 }
2863 return !RTEST(r);
2864}
2865
2866static int
2867num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2868{
2869 VALUE hash;
2870
2871 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2872 if (!NIL_P(hash)) {
2873 ID keys[2];
2874 VALUE values[2];
2875 keys[0] = id_to;
2876 keys[1] = id_by;
2877 rb_get_kwargs(hash, keys, 0, 2, values);
2878 if (!UNDEF_P(values[0])) {
2879 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2880 *to = values[0];
2881 }
2882 if (!UNDEF_P(values[1])) {
2883 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2884 *by = values[1];
2885 }
2886 }
2887
2888 return argc;
2889}
2890
2891static int
2892num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2893{
2894 int desc;
2895 if (!UNDEF_P(by)) {
2896 *step = by;
2897 }
2898 else {
2899 /* compatibility */
2900 if (argc > 1 && NIL_P(*step)) {
2901 rb_raise(rb_eTypeError, "step must be numeric");
2902 }
2903 }
2904 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2905 rb_raise(rb_eArgError, "step can't be 0");
2906 }
2907 if (NIL_P(*step)) {
2908 *step = INT2FIX(1);
2909 }
2910 desc = num_step_negative_p(*step);
2911 if (fix_nil && NIL_P(*to)) {
2912 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2913 }
2914 return desc;
2915}
2916
2917static int
2918num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2919{
2920 VALUE by = Qundef;
2921 argc = num_step_extract_args(argc, argv, to, step, &by);
2922 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2923}
2924
2925static VALUE
2926num_step_size(VALUE from, VALUE args, VALUE eobj)
2927{
2928 VALUE to, step;
2929 int argc = args ? RARRAY_LENINT(args) : 0;
2930 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2931
2932 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2933
2934 return ruby_num_interval_step_size(from, to, step, FALSE);
2935}
2936
2937/*
2938 * call-seq:
2939 * step(to = nil, by = 1) {|n| ... } -> self
2940 * step(to = nil, by = 1) -> enumerator
2941 * step(to = nil, by: 1) {|n| ... } -> self
2942 * step(to = nil, by: 1) -> enumerator
2943 * step(by: 1, to: ) {|n| ... } -> self
2944 * step(by: 1, to: ) -> enumerator
2945 * step(by: , to: nil) {|n| ... } -> self
2946 * step(by: , to: nil) -> enumerator
2947 *
2948 * Generates a sequence of numbers; with a block given, traverses the sequence.
2949 *
2950 * Of the Core and Standard Library classes,
2951 * Integer, Float, and Rational use this implementation.
2952 *
2953 * A quick example:
2954 *
2955 * squares = []
2956 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2957 * squares # => [1, 9, 25, 49, 81]
2958 *
2959 * The generated sequence:
2960 *
2961 * - Begins with +self+.
2962 * - Continues at intervals of +by+ (which may not be zero).
2963 * - Ends with the last number that is within or equal to +to+;
2964 * that is, less than or equal to +to+ if +by+ is positive,
2965 * greater than or equal to +to+ if +by+ is negative.
2966 * If +to+ is +nil+, the sequence is of infinite length.
2967 *
2968 * If a block is given, calls the block with each number in the sequence;
2969 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2970 *
2971 * <b>Keyword Arguments</b>
2972 *
2973 * With keyword arguments +by+ and +to+,
2974 * their values (or defaults) determine the step and limit:
2975 *
2976 * # Both keywords given.
2977 * squares = []
2978 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2979 * squares # => [16, 36, 64, 100]
2980 * cubes = []
2981 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2982 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2983 * squares = []
2984 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2985 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2986 *
2987 * squares = []
2988 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2989 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2990 *
2991 * # Only keyword to given.
2992 * squares = []
2993 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
2994 * squares # => [16, 25, 36, 49, 64, 81, 100]
2995 * # Only by given.
2996 *
2997 * # Only keyword by given
2998 * squares = []
2999 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3000 * squares # => [16, 36, 64, 100, 144]
3001 *
3002 * # No block given.
3003 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3004 * e.class # => Enumerator::ArithmeticSequence
3005 *
3006 * <b>Positional Arguments</b>
3007 *
3008 * With optional positional arguments +to+ and +by+,
3009 * their values (or defaults) determine the step and limit:
3010 *
3011 * squares = []
3012 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3013 * squares # => [16, 36, 64, 100]
3014 * squares = []
3015 * 4.step(10) {|i| squares.push(i*i) }
3016 * squares # => [16, 25, 36, 49, 64, 81, 100]
3017 * squares = []
3018 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3019 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3020 *
3021 * <b>Implementation Notes</b>
3022 *
3023 * If all the arguments are integers, the loop operates using an integer
3024 * counter.
3025 *
3026 * If any of the arguments are floating point numbers, all are converted
3027 * to floats, and the loop is executed
3028 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3029 * where <i>n = (limit - self)/step</i>.
3030 *
3031 */
3032
3033static VALUE
3034num_step(int argc, VALUE *argv, VALUE from)
3035{
3036 VALUE to, step;
3037 int desc, inf;
3038
3039 if (!rb_block_given_p()) {
3040 VALUE by = Qundef;
3041
3042 num_step_extract_args(argc, argv, &to, &step, &by);
3043 if (!UNDEF_P(by)) {
3044 step = by;
3045 }
3046 if (NIL_P(step)) {
3047 step = INT2FIX(1);
3048 }
3049 else if (rb_equal(step, INT2FIX(0))) {
3050 rb_raise(rb_eArgError, "step can't be 0");
3051 }
3052 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3053 rb_obj_is_kind_of(step, rb_cNumeric)) {
3054 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3055 num_step_size, from, to, step, FALSE);
3056 }
3057
3058 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3059 }
3060
3061 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3062 if (rb_equal(step, INT2FIX(0))) {
3063 inf = 1;
3064 }
3065 else if (RB_FLOAT_TYPE_P(to)) {
3066 double f = RFLOAT_VALUE(to);
3067 inf = isinf(f) && (signbit(f) ? desc : !desc);
3068 }
3069 else inf = 0;
3070
3071 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3072 long i = FIX2LONG(from);
3073 long diff = FIX2LONG(step);
3074
3075 if (inf) {
3076 for (;; i += diff)
3077 rb_yield(LONG2FIX(i));
3078 }
3079 else {
3080 long end = FIX2LONG(to);
3081
3082 if (desc) {
3083 for (; i >= end; i += diff)
3084 rb_yield(LONG2FIX(i));
3085 }
3086 else {
3087 for (; i <= end; i += diff)
3088 rb_yield(LONG2FIX(i));
3089 }
3090 }
3091 }
3092 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3093 VALUE i = from;
3094
3095 if (inf) {
3096 for (;; i = rb_funcall(i, '+', 1, step))
3097 rb_yield(i);
3098 }
3099 else {
3100 ID cmp = desc ? '<' : '>';
3101
3102 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3103 rb_yield(i);
3104 }
3105 }
3106 return from;
3107}
3108
3109static char *
3110out_of_range_float(char (*pbuf)[24], VALUE val)
3111{
3112 char *const buf = *pbuf;
3113 char *s;
3114
3115 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3116 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3117 return buf;
3118}
3119
3120#define FLOAT_OUT_OF_RANGE(val, type) do { \
3121 char buf[24]; \
3122 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3123 out_of_range_float(&buf, (val))); \
3124} while (0)
3125
3126#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3127#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3128#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3129#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3130 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3131 LONG_MIN <= (n): \
3132 LONG_MIN_MINUS_ONE < (n))
3133
3134long
3135rb_num2long(VALUE val)
3136{
3137 again:
3138 if (NIL_P(val)) {
3139 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3140 }
3141
3142 if (FIXNUM_P(val)) return FIX2LONG(val);
3143
3144 else if (RB_FLOAT_TYPE_P(val)) {
3145 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3146 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3147 return (long)RFLOAT_VALUE(val);
3148 }
3149 else {
3150 FLOAT_OUT_OF_RANGE(val, "integer");
3151 }
3152 }
3153 else if (RB_BIGNUM_TYPE_P(val)) {
3154 return rb_big2long(val);
3155 }
3156 else {
3157 val = rb_to_int(val);
3158 goto again;
3159 }
3160}
3161
3162static unsigned long
3163rb_num2ulong_internal(VALUE val, int *wrap_p)
3164{
3165 again:
3166 if (NIL_P(val)) {
3167 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3168 }
3169
3170 if (FIXNUM_P(val)) {
3171 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3172 if (wrap_p)
3173 *wrap_p = l < 0;
3174 return (unsigned long)l;
3175 }
3176 else if (RB_FLOAT_TYPE_P(val)) {
3177 double d = RFLOAT_VALUE(val);
3178 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3179 if (wrap_p)
3180 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3181 if (0 <= d)
3182 return (unsigned long)d;
3183 return (unsigned long)(long)d;
3184 }
3185 else {
3186 FLOAT_OUT_OF_RANGE(val, "integer");
3187 }
3188 }
3189 else if (RB_BIGNUM_TYPE_P(val)) {
3190 {
3191 unsigned long ul = rb_big2ulong(val);
3192 if (wrap_p)
3193 *wrap_p = BIGNUM_NEGATIVE_P(val);
3194 return ul;
3195 }
3196 }
3197 else {
3198 val = rb_to_int(val);
3199 goto again;
3200 }
3201}
3202
3203unsigned long
3204rb_num2ulong(VALUE val)
3205{
3206 return rb_num2ulong_internal(val, NULL);
3207}
3208
3209void
3210rb_out_of_int(SIGNED_VALUE num)
3211{
3212 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'",
3213 num, num < 0 ? "small" : "big");
3214}
3215
3216#if SIZEOF_INT < SIZEOF_LONG
3217static void
3218check_int(long num)
3219{
3220 if ((long)(int)num != num) {
3221 rb_out_of_int(num);
3222 }
3223}
3224
3225static void
3226check_uint(unsigned long num, int sign)
3227{
3228 if (sign) {
3229 /* minus */
3230 if (num < (unsigned long)INT_MIN)
3231 rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned int'", (long)num);
3232 }
3233 else {
3234 /* plus */
3235 if (UINT_MAX < num)
3236 rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num);
3237 }
3238}
3239
3240long
3241 rb_num2int(VALUE val)
3242{
3243 long num = rb_num2long(val);
3244
3245 check_int(num);
3246 return num;
3247}
3248
3249long
3250 rb_fix2int(VALUE val)
3251{
3252 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3253
3254 check_int(num);
3255 return num;
3256}
3257
3258unsigned long
3259 rb_num2uint(VALUE val)
3260{
3261 int wrap;
3262 unsigned long num = rb_num2ulong_internal(val, &wrap);
3263
3264 check_uint(num, wrap);
3265 return num;
3266}
3267
3268unsigned long
3269 rb_fix2uint(VALUE val)
3270{
3271 unsigned long num;
3272
3273 if (!FIXNUM_P(val)) {
3274 return rb_num2uint(val);
3275 }
3276 num = FIX2ULONG(val);
3277
3278 check_uint(num, FIXNUM_NEGATIVE_P(val));
3279 return num;
3280}
3281#else
3282long
3283rb_num2int(VALUE val)
3284{
3285 return rb_num2long(val);
3286}
3287
3288long
3289rb_fix2int(VALUE val)
3290{
3291 return FIX2INT(val);
3292}
3293
3294unsigned long
3295rb_num2uint(VALUE val)
3296{
3297 return rb_num2ulong(val);
3298}
3299
3300unsigned long
3301rb_fix2uint(VALUE val)
3302{
3303 return RB_FIX2ULONG(val);
3304}
3305#endif
3306
3307NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3308static void
3309rb_out_of_short(SIGNED_VALUE num)
3310{
3311 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `short'",
3312 num, num < 0 ? "small" : "big");
3313}
3314
3315static void
3316check_short(long num)
3317{
3318 if ((long)(short)num != num) {
3319 rb_out_of_short(num);
3320 }
3321}
3322
3323static void
3324check_ushort(unsigned long num, int sign)
3325{
3326 if (sign) {
3327 /* minus */
3328 if (num < (unsigned long)SHRT_MIN)
3329 rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned short'", (long)num);
3330 }
3331 else {
3332 /* plus */
3333 if (USHRT_MAX < num)
3334 rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned short'", num);
3335 }
3336}
3337
3338short
3339rb_num2short(VALUE val)
3340{
3341 long num = rb_num2long(val);
3342
3343 check_short(num);
3344 return num;
3345}
3346
3347short
3348rb_fix2short(VALUE val)
3349{
3350 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3351
3352 check_short(num);
3353 return num;
3354}
3355
3356unsigned short
3357rb_num2ushort(VALUE val)
3358{
3359 int wrap;
3360 unsigned long num = rb_num2ulong_internal(val, &wrap);
3361
3362 check_ushort(num, wrap);
3363 return num;
3364}
3365
3366unsigned short
3367rb_fix2ushort(VALUE val)
3368{
3369 unsigned long num;
3370
3371 if (!FIXNUM_P(val)) {
3372 return rb_num2ushort(val);
3373 }
3374 num = FIX2ULONG(val);
3375
3376 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3377 return num;
3378}
3379
3380 VALUE
3381rb_num2fix(VALUE val)
3382{
3383 long v;
3384
3385 if (FIXNUM_P(val)) return val;
3386
3387 v = rb_num2long(val);
3388 if (!FIXABLE(v))
3389 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3390 return LONG2FIX(v);
3391}
3392
3393#if HAVE_LONG_LONG
3394
3395#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3396#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3397#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3398#ifndef ULLONG_MAX
3399#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3400#endif
3401#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3402 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3403 LLONG_MIN <= (n): \
3404 LLONG_MIN_MINUS_ONE < (n))
3405
3406 LONG_LONG
3407 rb_num2ll(VALUE val)
3408{
3409 if (NIL_P(val)) {
3410 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3411 }
3412
3413 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3414
3415 else if (RB_FLOAT_TYPE_P(val)) {
3416 double d = RFLOAT_VALUE(val);
3417 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3418 return (LONG_LONG)d;
3419 }
3420 else {
3421 FLOAT_OUT_OF_RANGE(val, "long long");
3422 }
3423 }
3424 else if (RB_BIGNUM_TYPE_P(val)) {
3425 return rb_big2ll(val);
3426 }
3427 else if (RB_TYPE_P(val, T_STRING)) {
3428 rb_raise(rb_eTypeError, "no implicit conversion from string");
3429 }
3430 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3431 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3432 }
3433
3434 val = rb_to_int(val);
3435 return NUM2LL(val);
3436}
3437
3438unsigned LONG_LONG
3439 rb_num2ull(VALUE val)
3440{
3441 if (NIL_P(val)) {
3442 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3443 }
3444 else if (FIXNUM_P(val)) {
3445 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3446 }
3447 else if (RB_FLOAT_TYPE_P(val)) {
3448 double d = RFLOAT_VALUE(val);
3449 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3450 if (0 <= d)
3451 return (unsigned LONG_LONG)d;
3452 return (unsigned LONG_LONG)(LONG_LONG)d;
3453 }
3454 else {
3455 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3456 }
3457 }
3458 else if (RB_BIGNUM_TYPE_P(val)) {
3459 return rb_big2ull(val);
3460 }
3461 else {
3462 val = rb_to_int(val);
3463 return NUM2ULL(val);
3464 }
3465}
3466
3467#endif /* HAVE_LONG_LONG */
3468
3469/********************************************************************
3470 *
3471 * Document-class: Integer
3472 *
3473 * An \Integer object represents an integer value.
3474 *
3475 * You can create an \Integer object explicitly with:
3476 *
3477 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3478 *
3479 * You can convert certain objects to Integers with:
3480 *
3481 * - \Method #Integer.
3482 *
3483 * An attempt to add a singleton method to an instance of this class
3484 * causes an exception to be raised.
3485 *
3486 * == What's Here
3487 *
3488 * First, what's elsewhere. \Class \Integer:
3489 *
3490 * - Inherits from {class Numeric}[rdoc-ref:Numeric@What-27s+Here].
3491 *
3492 * Here, class \Integer provides methods for:
3493 *
3494 * - {Querying}[rdoc-ref:Integer@Querying]
3495 * - {Comparing}[rdoc-ref:Integer@Comparing]
3496 * - {Converting}[rdoc-ref:Integer@Converting]
3497 * - {Other}[rdoc-ref:Integer@Other]
3498 *
3499 * === Querying
3500 *
3501 * - #allbits?: Returns whether all bits in +self+ are set.
3502 * - #anybits?: Returns whether any bits in +self+ are set.
3503 * - #nobits?: Returns whether no bits in +self+ are set.
3504 *
3505 * === Comparing
3506 *
3507 * - #<: Returns whether +self+ is less than the given value.
3508 * - #<=: Returns whether +self+ is less than or equal to the given value.
3509 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3510 * to, or greater than the given value.
3511 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3512 * value.
3513 * - #>: Returns whether +self+ is greater than the given value.
3514 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3515 *
3516 * === Converting
3517 *
3518 * - ::sqrt: Returns the integer square root of the given value.
3519 * - ::try_convert: Returns the given value converted to an \Integer.
3520 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3521 * - #&: Returns the bitwise AND of +self+ and the given value.
3522 * - #*: Returns the product of +self+ and the given value.
3523 * - #**: Returns the value of +self+ raised to the power of the given value.
3524 * - #+: Returns the sum of +self+ and the given value.
3525 * - #-: Returns the difference of +self+ and the given value.
3526 * - #/: Returns the quotient of +self+ and the given value.
3527 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3528 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3529 * - #[]: Returns a slice of bits from +self+.
3530 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3531 * - #ceil: Returns the smallest number greater than or equal to +self+.
3532 * - #chr: Returns a 1-character string containing the character
3533 * represented by the value of +self+.
3534 * - #digits: Returns an array of integers representing the base-radix digits
3535 * of +self+.
3536 * - #div: Returns the integer result of dividing +self+ by the given value.
3537 * - #divmod: Returns a 2-element array containing the quotient and remainder
3538 * results of dividing +self+ by the given value.
3539 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3540 * - #floor: Returns the greatest number smaller than or equal to +self+.
3541 * - #pow: Returns the modular exponentiation of +self+.
3542 * - #pred: Returns the integer predecessor of +self+.
3543 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3544 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3545 * - #succ (aliased as #next): Returns the integer successor of +self+.
3546 * - #to_f: Returns +self+ converted to a Float.
3547 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3548 * representation of +self+ in the given radix.
3549 * - #truncate: Returns +self+ truncated to the given precision.
3550 * - #|: Returns the bitwise OR of +self+ and the given value.
3551 *
3552 * === Other
3553 *
3554 * - #downto: Calls the given block with each integer value from +self+
3555 * down to the given value.
3556 * - #times: Calls the given block +self+ times with each integer
3557 * in <tt>(0..self-1)</tt>.
3558 * - #upto: Calls the given block with each integer value from +self+
3559 * up to the given value.
3560 *
3561 */
3562
3563 VALUE
3564rb_int_odd_p(VALUE num)
3565{
3566 if (FIXNUM_P(num)) {
3567 return RBOOL(num & 2);
3568 }
3569 else {
3570 assert(RB_BIGNUM_TYPE_P(num));
3571 return rb_big_odd_p(num);
3572 }
3573}
3574
3575static VALUE
3576int_even_p(VALUE num)
3577{
3578 if (FIXNUM_P(num)) {
3579 return RBOOL((num & 2) == 0);
3580 }
3581 else {
3582 assert(RB_BIGNUM_TYPE_P(num));
3583 return rb_big_even_p(num);
3584 }
3585}
3586
3587 VALUE
3588rb_int_even_p(VALUE num)
3589{
3590 return int_even_p(num);
3591}
3592
3593/*
3594 * call-seq:
3595 * allbits?(mask) -> true or false
3596 *
3597 * Returns +true+ if all bits that are set (=1) in +mask+
3598 * are also set in +self+; returns +false+ otherwise.
3599 *
3600 * Example values:
3601 *
3602 * 0b1010101 self
3603 * 0b1010100 mask
3604 * 0b1010100 self & mask
3605 * true self.allbits?(mask)
3606 *
3607 * 0b1010100 self
3608 * 0b1010101 mask
3609 * 0b1010100 self & mask
3610 * false self.allbits?(mask)
3611 *
3612 * Related: Integer#anybits?, Integer#nobits?.
3613 *
3614 */
3615
3616static VALUE
3617int_allbits_p(VALUE num, VALUE mask)
3618{
3619 mask = rb_to_int(mask);
3620 return rb_int_equal(rb_int_and(num, mask), mask);
3621}
3622
3623/*
3624 * call-seq:
3625 * anybits?(mask) -> true or false
3626 *
3627 * Returns +true+ if any bit that is set (=1) in +mask+
3628 * is also set in +self+; returns +false+ otherwise.
3629 *
3630 * Example values:
3631 *
3632 * 0b10000010 self
3633 * 0b11111111 mask
3634 * 0b10000010 self & mask
3635 * true self.anybits?(mask)
3636 *
3637 * 0b00000000 self
3638 * 0b11111111 mask
3639 * 0b00000000 self & mask
3640 * false self.anybits?(mask)
3641 *
3642 * Related: Integer#allbits?, Integer#nobits?.
3643 *
3644 */
3645
3646static VALUE
3647int_anybits_p(VALUE num, VALUE mask)
3648{
3649 mask = rb_to_int(mask);
3650 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3651}
3652
3653/*
3654 * call-seq:
3655 * nobits?(mask) -> true or false
3656 *
3657 * Returns +true+ if no bit that is set (=1) in +mask+
3658 * is also set in +self+; returns +false+ otherwise.
3659 *
3660 * Example values:
3661 *
3662 * 0b11110000 self
3663 * 0b00001111 mask
3664 * 0b00000000 self & mask
3665 * true self.nobits?(mask)
3666 *
3667 * 0b00000001 self
3668 * 0b11111111 mask
3669 * 0b00000001 self & mask
3670 * false self.nobits?(mask)
3671 *
3672 * Related: Integer#allbits?, Integer#anybits?.
3673 *
3674 */
3675
3676static VALUE
3677int_nobits_p(VALUE num, VALUE mask)
3678{
3679 mask = rb_to_int(mask);
3680 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3681}
3682
3683/*
3684 * call-seq:
3685 * succ -> next_integer
3686 *
3687 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3688 *
3689 * 1.succ #=> 2
3690 * -1.succ #=> 0
3691 *
3692 * Related: Integer#pred (predecessor value).
3693 */
3694
3695 VALUE
3696rb_int_succ(VALUE num)
3697{
3698 if (FIXNUM_P(num)) {
3699 long i = FIX2LONG(num) + 1;
3700 return LONG2NUM(i);
3701 }
3702 if (RB_BIGNUM_TYPE_P(num)) {
3703 return rb_big_plus(num, INT2FIX(1));
3704 }
3705 return num_funcall1(num, '+', INT2FIX(1));
3706}
3707
3708#define int_succ rb_int_succ
3709
3710/*
3711 * call-seq:
3712 * pred -> next_integer
3713 *
3714 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3715 *
3716 * 1.pred #=> 0
3717 * -1.pred #=> -2
3718 *
3719 * Related: Integer#succ (successor value).
3720 *
3721 */
3722
3723static VALUE
3724rb_int_pred(VALUE num)
3725{
3726 if (FIXNUM_P(num)) {
3727 long i = FIX2LONG(num) - 1;
3728 return LONG2NUM(i);
3729 }
3730 if (RB_BIGNUM_TYPE_P(num)) {
3731 return rb_big_minus(num, INT2FIX(1));
3732 }
3733 return num_funcall1(num, '-', INT2FIX(1));
3734}
3735
3736#define int_pred rb_int_pred
3737
3738 VALUE
3739rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3740{
3741 int n;
3742 VALUE str;
3743 switch (n = rb_enc_codelen(code, enc)) {
3744 case ONIGERR_INVALID_CODE_POINT_VALUE:
3745 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3746 break;
3747 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3748 case 0:
3749 rb_raise(rb_eRangeError, "%u out of char range", code);
3750 break;
3751 }
3752 str = rb_enc_str_new(0, n, enc);
3753 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3754 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3755 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3756 }
3757 return str;
3758}
3759
3760/* call-seq:
3761 * chr -> string
3762 * chr(encoding) -> string
3763 *
3764 * Returns a 1-character string containing the character
3765 * represented by the value of +self+, according to the given +encoding+.
3766 *
3767 * 65.chr # => "A"
3768 * 0.chr # => "\x00"
3769 * 255.chr # => "\xFF"
3770 * string = 255.chr(Encoding::UTF_8)
3771 * string.encoding # => Encoding::UTF_8
3772 *
3773 * Raises an exception if +self+ is negative.
3774 *
3775 * Related: Integer#ord.
3776 *
3777 */
3778
3779static VALUE
3780int_chr(int argc, VALUE *argv, VALUE num)
3781{
3782 char c;
3783 unsigned int i;
3784 rb_encoding *enc;
3785
3786 if (rb_num_to_uint(num, &i) == 0) {
3787 }
3788 else if (FIXNUM_P(num)) {
3789 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3790 }
3791 else {
3792 rb_raise(rb_eRangeError, "bignum out of char range");
3793 }
3794
3795 switch (argc) {
3796 case 0:
3797 if (0xff < i) {
3798 enc = rb_default_internal_encoding();
3799 if (!enc) {
3800 rb_raise(rb_eRangeError, "%u out of char range", i);
3801 }
3802 goto decode;
3803 }
3804 c = (char)i;
3805 if (i < 0x80) {
3806 return rb_usascii_str_new(&c, 1);
3807 }
3808 else {
3809 return rb_str_new(&c, 1);
3810 }
3811 case 1:
3812 break;
3813 default:
3814 rb_error_arity(argc, 0, 1);
3815 }
3816 enc = rb_to_encoding(argv[0]);
3817 if (!enc) enc = rb_ascii8bit_encoding();
3818 decode:
3819 return rb_enc_uint_chr(i, enc);
3820}
3821
3822/*
3823 * Fixnum
3824 */
3825
3826static VALUE
3827fix_uminus(VALUE num)
3828{
3829 return LONG2NUM(-FIX2LONG(num));
3830}
3831
3832 VALUE
3833rb_int_uminus(VALUE num)
3834{
3835 if (FIXNUM_P(num)) {
3836 return fix_uminus(num);
3837 }
3838 else {
3839 assert(RB_BIGNUM_TYPE_P(num));
3840 return rb_big_uminus(num);
3841 }
3842}
3843
3844 VALUE
3845rb_fix2str(VALUE x, int base)
3846{
3847 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3848 long val = FIX2LONG(x);
3849 unsigned long u;
3850 int neg = 0;
3851
3852 if (base < 2 || 36 < base) {
3853 rb_raise(rb_eArgError, "invalid radix %d", base);
3854 }
3855#if SIZEOF_LONG < SIZEOF_VOIDP
3856# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3857 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
3858 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
3859 rb_bug("Unnormalized Fixnum value %p", (void *)x);
3860 }
3861# else
3862 /* should do something like above code, but currently ruby does not know */
3863 /* such platforms */
3864# endif
3865#endif
3866 if (val == 0) {
3867 return rb_usascii_str_new2("0");
3868 }
3869 if (val < 0) {
3870 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3871 neg = 1;
3872 }
3873 else {
3874 u = val;
3875 }
3876 do {
3877 *--b = ruby_digitmap[(int)(u % base)];
3878 } while (u /= base);
3879 if (neg) {
3880 *--b = '-';
3881 }
3882
3883 return rb_usascii_str_new(b, e - b);
3884}
3885
3886static VALUE rb_fix_to_s_static[10];
3887
3888 VALUE
3889rb_fix_to_s(VALUE x)
3890{
3891 long i = FIX2LONG(x);
3892 if (i >= 0 && i < 10) {
3893 return rb_fix_to_s_static[i];
3894 }
3895 return rb_fix2str(x, 10);
3896}
3897
3898/*
3899 * call-seq:
3900 * to_s(base = 10) -> string
3901 *
3902 * Returns a string containing the place-value representation of +self+
3903 * in radix +base+ (in 2..36).
3904 *
3905 * 12345.to_s # => "12345"
3906 * 12345.to_s(2) # => "11000000111001"
3907 * 12345.to_s(8) # => "30071"
3908 * 12345.to_s(10) # => "12345"
3909 * 12345.to_s(16) # => "3039"
3910 * 12345.to_s(36) # => "9ix"
3911 * 78546939656932.to_s(36) # => "rubyrules"
3912 *
3913 * Raises an exception if +base+ is out of range.
3914 */
3915
3916 VALUE
3917rb_int_to_s(int argc, VALUE *argv, VALUE x)
3918{
3919 int base;
3920
3921 if (rb_check_arity(argc, 0, 1))
3922 base = NUM2INT(argv[0]);
3923 else
3924 base = 10;
3925 return rb_int2str(x, base);
3926}
3927
3928 VALUE
3929rb_int2str(VALUE x, int base)
3930{
3931 if (FIXNUM_P(x)) {
3932 return rb_fix2str(x, base);
3933 }
3934 else if (RB_BIGNUM_TYPE_P(x)) {
3935 return rb_big2str(x, base);
3936 }
3937
3938 return rb_any_to_s(x);
3939}
3940
3941static VALUE
3942fix_plus(VALUE x, VALUE y)
3943{
3944 if (FIXNUM_P(y)) {
3945 return rb_fix_plus_fix(x, y);
3946 }
3947 else if (RB_BIGNUM_TYPE_P(y)) {
3948 return rb_big_plus(y, x);
3949 }
3950 else if (RB_FLOAT_TYPE_P(y)) {
3951 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
3952 }
3953 else if (RB_TYPE_P(y, T_COMPLEX)) {
3954 return rb_complex_plus(y, x);
3955 }
3956 else {
3957 return rb_num_coerce_bin(x, y, '+');
3958 }
3959}
3960
3961 VALUE
3962rb_fix_plus(VALUE x, VALUE y)
3963{
3964 return fix_plus(x, y);
3965}
3966
3967/*
3968 * call-seq:
3969 * self + numeric -> numeric_result
3970 *
3971 * Performs addition:
3972 *
3973 * 2 + 2 # => 4
3974 * -2 + 2 # => 0
3975 * -2 + -2 # => -4
3976 * 2 + 2.0 # => 4.0
3977 * 2 + Rational(2, 1) # => (4/1)
3978 * 2 + Complex(2, 0) # => (4+0i)
3979 *
3980 */
3981
3982 VALUE
3983rb_int_plus(VALUE x, VALUE y)
3984{
3985 if (FIXNUM_P(x)) {
3986 return fix_plus(x, y);
3987 }
3988 else if (RB_BIGNUM_TYPE_P(x)) {
3989 return rb_big_plus(x, y);
3990 }
3991 return rb_num_coerce_bin(x, y, '+');
3992}
3993
3994static VALUE
3995fix_minus(VALUE x, VALUE y)
3996{
3997 if (FIXNUM_P(y)) {
3998 return rb_fix_minus_fix(x, y);
3999 }
4000 else if (RB_BIGNUM_TYPE_P(y)) {
4001 x = rb_int2big(FIX2LONG(x));
4002 return rb_big_minus(x, y);
4003 }
4004 else if (RB_FLOAT_TYPE_P(y)) {
4005 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4006 }
4007 else {
4008 return rb_num_coerce_bin(x, y, '-');
4009 }
4010}
4011
4012/*
4013 * call-seq:
4014 * self - numeric -> numeric_result
4015 *
4016 * Performs subtraction:
4017 *
4018 * 4 - 2 # => 2
4019 * -4 - 2 # => -6
4020 * -4 - -2 # => -2
4021 * 4 - 2.0 # => 2.0
4022 * 4 - Rational(2, 1) # => (2/1)
4023 * 4 - Complex(2, 0) # => (2+0i)
4024 *
4025 */
4026
4027 VALUE
4028rb_int_minus(VALUE x, VALUE y)
4029{
4030 if (FIXNUM_P(x)) {
4031 return fix_minus(x, y);
4032 }
4033 else if (RB_BIGNUM_TYPE_P(x)) {
4034 return rb_big_minus(x, y);
4035 }
4036 return rb_num_coerce_bin(x, y, '-');
4037}
4038
4039
4040#define SQRT_LONG_MAX HALF_LONG_MSB
4041/*tests if N*N would overflow*/
4042#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4043
4044static VALUE
4045fix_mul(VALUE x, VALUE y)
4046{
4047 if (FIXNUM_P(y)) {
4048 return rb_fix_mul_fix(x, y);
4049 }
4050 else if (RB_BIGNUM_TYPE_P(y)) {
4051 switch (x) {
4052 case INT2FIX(0): return x;
4053 case INT2FIX(1): return y;
4054 }
4055 return rb_big_mul(y, x);
4056 }
4057 else if (RB_FLOAT_TYPE_P(y)) {
4058 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4059 }
4060 else if (RB_TYPE_P(y, T_COMPLEX)) {
4061 return rb_complex_mul(y, x);
4062 }
4063 else {
4064 return rb_num_coerce_bin(x, y, '*');
4065 }
4066}
4067
4068/*
4069 * call-seq:
4070 * self * numeric -> numeric_result
4071 *
4072 * Performs multiplication:
4073 *
4074 * 4 * 2 # => 8
4075 * 4 * -2 # => -8
4076 * -4 * 2 # => -8
4077 * 4 * 2.0 # => 8.0
4078 * 4 * Rational(1, 3) # => (4/3)
4079 * 4 * Complex(2, 0) # => (8+0i)
4080 */
4081
4082 VALUE
4083rb_int_mul(VALUE x, VALUE y)
4084{
4085 if (FIXNUM_P(x)) {
4086 return fix_mul(x, y);
4087 }
4088 else if (RB_BIGNUM_TYPE_P(x)) {
4089 return rb_big_mul(x, y);
4090 }
4091 return rb_num_coerce_bin(x, y, '*');
4092}
4093
4094static double
4095fix_fdiv_double(VALUE x, VALUE y)
4096{
4097 if (FIXNUM_P(y)) {
4098 long iy = FIX2LONG(y);
4099#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4100 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4101 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4102 }
4103#endif
4104 return double_div_double(FIX2LONG(x), iy);
4105 }
4106 else if (RB_BIGNUM_TYPE_P(y)) {
4107 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4108 }
4109 else if (RB_FLOAT_TYPE_P(y)) {
4110 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4111 }
4112 else {
4113 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4114 }
4115}
4116
4117double
4118rb_int_fdiv_double(VALUE x, VALUE y)
4119{
4120 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) {
4121 VALUE gcd = rb_gcd(x, y);
4122 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4123 x = rb_int_idiv(x, gcd);
4124 y = rb_int_idiv(y, gcd);
4125 }
4126 }
4127 if (FIXNUM_P(x)) {
4128 return fix_fdiv_double(x, y);
4129 }
4130 else if (RB_BIGNUM_TYPE_P(x)) {
4131 return rb_big_fdiv_double(x, y);
4132 }
4133 else {
4134 return nan("");
4135 }
4136}
4137
4138/*
4139 * call-seq:
4140 * fdiv(numeric) -> float
4141 *
4142 * Returns the Float result of dividing +self+ by +numeric+:
4143 *
4144 * 4.fdiv(2) # => 2.0
4145 * 4.fdiv(-2) # => -2.0
4146 * -4.fdiv(2) # => -2.0
4147 * 4.fdiv(2.0) # => 2.0
4148 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4149 *
4150 * Raises an exception if +numeric+ cannot be converted to a Float.
4151 *
4152 */
4153
4154 VALUE
4155rb_int_fdiv(VALUE x, VALUE y)
4156{
4157 if (RB_INTEGER_TYPE_P(x)) {
4158 return DBL2NUM(rb_int_fdiv_double(x, y));
4159 }
4160 return Qnil;
4161}
4162
4163static VALUE
4164fix_divide(VALUE x, VALUE y, ID op)
4165{
4166 if (FIXNUM_P(y)) {
4167 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4168 return rb_fix_div_fix(x, y);
4169 }
4170 else if (RB_BIGNUM_TYPE_P(y)) {
4171 x = rb_int2big(FIX2LONG(x));
4172 return rb_big_div(x, y);
4173 }
4174 else if (RB_FLOAT_TYPE_P(y)) {
4175 if (op == '/') {
4176 double d = FIX2LONG(x);
4177 return rb_flo_div_flo(DBL2NUM(d), y);
4178 }
4179 else {
4180 VALUE v;
4181 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4182 v = fix_divide(x, y, '/');
4183 return flo_floor(0, 0, v);
4184 }
4185 }
4186 else {
4187 if (RB_TYPE_P(y, T_RATIONAL) &&
4188 op == '/' && FIX2LONG(x) == 1)
4189 return rb_rational_reciprocal(y);
4190 return rb_num_coerce_bin(x, y, op);
4191 }
4192}
4193
4194static VALUE
4195fix_div(VALUE x, VALUE y)
4196{
4197 return fix_divide(x, y, '/');
4198}
4199
4200/*
4201 * call-seq:
4202 * self / numeric -> numeric_result
4203 *
4204 * Performs division; for integer +numeric+, truncates the result to an integer:
4205 *
4206 * 4 / 3 # => 1
4207 * 4 / -3 # => -2
4208 * -4 / 3 # => -2
4209 * -4 / -3 # => 1
4210 *
4211 * For other +numeric+, returns non-integer result:
4212 *
4213 * 4 / 3.0 # => 1.3333333333333333
4214 * 4 / Rational(3, 1) # => (4/3)
4215 * 4 / Complex(3, 0) # => ((4/3)+0i)
4216 *
4217 */
4218
4219 VALUE
4220rb_int_div(VALUE x, VALUE y)
4221{
4222 if (FIXNUM_P(x)) {
4223 return fix_div(x, y);
4224 }
4225 else if (RB_BIGNUM_TYPE_P(x)) {
4226 return rb_big_div(x, y);
4227 }
4228 return Qnil;
4229}
4230
4231static VALUE
4232fix_idiv(VALUE x, VALUE y)
4233{
4234 return fix_divide(x, y, id_div);
4235}
4236
4237/*
4238 * call-seq:
4239 * div(numeric) -> integer
4240 *
4241 * Performs integer division; returns the integer result of dividing +self+
4242 * by +numeric+:
4243 *
4244 * 4.div(3) # => 1
4245 * 4.div(-3) # => -2
4246 * -4.div(3) # => -2
4247 * -4.div(-3) # => 1
4248 * 4.div(3.0) # => 1
4249 * 4.div(Rational(3, 1)) # => 1
4250 *
4251 * Raises an exception if +numeric+ does not have method +div+.
4252 *
4253 */
4254
4255 VALUE
4256rb_int_idiv(VALUE x, VALUE y)
4257{
4258 if (FIXNUM_P(x)) {
4259 return fix_idiv(x, y);
4260 }
4261 else if (RB_BIGNUM_TYPE_P(x)) {
4262 return rb_big_idiv(x, y);
4263 }
4264 return num_div(x, y);
4265}
4266
4267static VALUE
4268fix_mod(VALUE x, VALUE y)
4269{
4270 if (FIXNUM_P(y)) {
4271 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4272 return rb_fix_mod_fix(x, y);
4273 }
4274 else if (RB_BIGNUM_TYPE_P(y)) {
4275 x = rb_int2big(FIX2LONG(x));
4276 return rb_big_modulo(x, y);
4277 }
4278 else if (RB_FLOAT_TYPE_P(y)) {
4279 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4280 }
4281 else {
4282 return rb_num_coerce_bin(x, y, '%');
4283 }
4284}
4285
4286/*
4287 * call-seq:
4288 * self % other -> real_number
4289 *
4290 * Returns +self+ modulo +other+ as a real number.
4291 *
4292 * For integer +n+ and real number +r+, these expressions are equivalent:
4293 *
4294 * n % r
4295 * n-r*(n/r).floor
4296 * n.divmod(r)[1]
4297 *
4298 * See Numeric#divmod.
4299 *
4300 * Examples:
4301 *
4302 * 10 % 2 # => 0
4303 * 10 % 3 # => 1
4304 * 10 % 4 # => 2
4305 *
4306 * 10 % -2 # => 0
4307 * 10 % -3 # => -2
4308 * 10 % -4 # => -2
4309 *
4310 * 10 % 3.0 # => 1.0
4311 * 10 % Rational(3, 1) # => (1/1)
4312 *
4313 */
4314 VALUE
4315rb_int_modulo(VALUE x, VALUE y)
4316{
4317 if (FIXNUM_P(x)) {
4318 return fix_mod(x, y);
4319 }
4320 else if (RB_BIGNUM_TYPE_P(x)) {
4321 return rb_big_modulo(x, y);
4322 }
4323 return num_modulo(x, y);
4324}
4325
4326/*
4327 * call-seq:
4328 * remainder(other) -> real_number
4329 *
4330 * Returns the remainder after dividing +self+ by +other+.
4331 *
4332 * Examples:
4333 *
4334 * 11.remainder(4) # => 3
4335 * 11.remainder(-4) # => 3
4336 * -11.remainder(4) # => -3
4337 * -11.remainder(-4) # => -3
4338 *
4339 * 12.remainder(4) # => 0
4340 * 12.remainder(-4) # => 0
4341 * -12.remainder(4) # => 0
4342 * -12.remainder(-4) # => 0
4343 *
4344 * 13.remainder(4.0) # => 1.0
4345 * 13.remainder(Rational(4, 1)) # => (1/1)
4346 *
4347 */
4348
4349static VALUE
4350int_remainder(VALUE x, VALUE y)
4351{
4352 if (FIXNUM_P(x)) {
4353 if (FIXNUM_P(y)) {
4354 VALUE z = fix_mod(x, y);
4355 assert(FIXNUM_P(z));
4356 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4357 z = fix_minus(z, y);
4358 return z;
4359 }
4360 else if (!RB_BIGNUM_TYPE_P(y)) {
4361 return num_remainder(x, y);
4362 }
4363 x = rb_int2big(FIX2LONG(x));
4364 }
4365 else if (!RB_BIGNUM_TYPE_P(x)) {
4366 return Qnil;
4367 }
4368 return rb_big_remainder(x, y);
4369}
4370
4371static VALUE
4372fix_divmod(VALUE x, VALUE y)
4373{
4374 if (FIXNUM_P(y)) {
4375 VALUE div, mod;
4376 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4377 rb_fix_divmod_fix(x, y, &div, &mod);
4378 return rb_assoc_new(div, mod);
4379 }
4380 else if (RB_BIGNUM_TYPE_P(y)) {
4381 x = rb_int2big(FIX2LONG(x));
4382 return rb_big_divmod(x, y);
4383 }
4384 else if (RB_FLOAT_TYPE_P(y)) {
4385 {
4386 double div, mod;
4387 volatile VALUE a, b;
4388
4389 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4390 a = dbl2ival(div);
4391 b = DBL2NUM(mod);
4392 return rb_assoc_new(a, b);
4393 }
4394 }
4395 else {
4396 return rb_num_coerce_bin(x, y, id_divmod);
4397 }
4398}
4399
4400/*
4401 * call-seq:
4402 * divmod(other) -> array
4403 *
4404 * Returns a 2-element array <tt>[q, r]</tt>, where
4405 *
4406 * q = (self/other).floor # Quotient
4407 * r = self % other # Remainder
4408 *
4409 * Examples:
4410 *
4411 * 11.divmod(4) # => [2, 3]
4412 * 11.divmod(-4) # => [-3, -1]
4413 * -11.divmod(4) # => [-3, 1]
4414 * -11.divmod(-4) # => [2, -3]
4415 *
4416 * 12.divmod(4) # => [3, 0]
4417 * 12.divmod(-4) # => [-3, 0]
4418 * -12.divmod(4) # => [-3, 0]
4419 * -12.divmod(-4) # => [3, 0]
4420 *
4421 * 13.divmod(4.0) # => [3, 1.0]
4422 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4423 *
4424 */
4425 VALUE
4426rb_int_divmod(VALUE x, VALUE y)
4427{
4428 if (FIXNUM_P(x)) {
4429 return fix_divmod(x, y);
4430 }
4431 else if (RB_BIGNUM_TYPE_P(x)) {
4432 return rb_big_divmod(x, y);
4433 }
4434 return Qnil;
4435}
4436
4437/*
4438 * call-seq:
4439 * self ** numeric -> numeric_result
4440 *
4441 * Raises +self+ to the power of +numeric+:
4442 *
4443 * 2 ** 3 # => 8
4444 * 2 ** -3 # => (1/8)
4445 * -2 ** 3 # => -8
4446 * -2 ** -3 # => (-1/8)
4447 * 2 ** 3.3 # => 9.849155306759329
4448 * 2 ** Rational(3, 1) # => (8/1)
4449 * 2 ** Complex(3, 0) # => (8+0i)
4450 *
4451 */
4452
4453static VALUE
4454int_pow(long x, unsigned long y)
4455{
4456 int neg = x < 0;
4457 long z = 1;
4458
4459 if (y == 0) return INT2FIX(1);
4460 if (y == 1) return LONG2NUM(x);
4461 if (neg) x = -x;
4462 if (y & 1)
4463 z = x;
4464 else
4465 neg = 0;
4466 y &= ~1;
4467 do {
4468 while (y % 2 == 0) {
4469 if (!FIT_SQRT_LONG(x)) {
4470 goto bignum;
4471 }
4472 x = x * x;
4473 y >>= 1;
4474 }
4475 {
4476 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4477 goto bignum;
4478 }
4479 z = x * z;
4480 }
4481 } while (--y);
4482 if (neg) z = -z;
4483 return LONG2NUM(z);
4484
4485 VALUE v;
4486 bignum:
4487 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4488 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4489 return v;
4490 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4491 return v;
4492}
4493
4494 VALUE
4495rb_int_positive_pow(long x, unsigned long y)
4496{
4497 return int_pow(x, y);
4498}
4499
4500static VALUE
4501fix_pow_inverted(VALUE x, VALUE minusb)
4502{
4503 if (x == INT2FIX(0)) {
4504 rb_num_zerodiv();
4505 UNREACHABLE_RETURN(Qundef);
4506 }
4507 else {
4508 VALUE y = rb_int_pow(x, minusb);
4509
4510 if (RB_FLOAT_TYPE_P(y)) {
4511 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4512 return DBL2NUM(1.0 / d);
4513 }
4514 else {
4515 return rb_rational_raw(INT2FIX(1), y);
4516 }
4517 }
4518}
4519
4520static VALUE
4521fix_pow(VALUE x, VALUE y)
4522{
4523 long a = FIX2LONG(x);
4524
4525 if (FIXNUM_P(y)) {
4526 long b = FIX2LONG(y);
4527
4528 if (a == 1) return INT2FIX(1);
4529 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4530 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4531 if (b == 0) return INT2FIX(1);
4532 if (b == 1) return x;
4533 if (a == 0) return INT2FIX(0);
4534 return int_pow(a, b);
4535 }
4536 else if (RB_BIGNUM_TYPE_P(y)) {
4537 if (a == 1) return INT2FIX(1);
4538 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4539 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4540 if (a == 0) return INT2FIX(0);
4541 x = rb_int2big(FIX2LONG(x));
4542 return rb_big_pow(x, y);
4543 }
4544 else if (RB_FLOAT_TYPE_P(y)) {
4545 double dy = RFLOAT_VALUE(y);
4546 if (dy == 0.0) return DBL2NUM(1.0);
4547 if (a == 0) {
4548 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4549 }
4550 if (a == 1) return DBL2NUM(1.0);
4551 if (a < 0 && dy != round(dy))
4552 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4553 return DBL2NUM(pow((double)a, dy));
4554 }
4555 else {
4556 return rb_num_coerce_bin(x, y, idPow);
4557 }
4558}
4559
4560/*
4561 * call-seq:
4562 * self ** numeric -> numeric_result
4563 *
4564 * Raises +self+ to the power of +numeric+:
4565 *
4566 * 2 ** 3 # => 8
4567 * 2 ** -3 # => (1/8)
4568 * -2 ** 3 # => -8
4569 * -2 ** -3 # => (-1/8)
4570 * 2 ** 3.3 # => 9.849155306759329
4571 * 2 ** Rational(3, 1) # => (8/1)
4572 * 2 ** Complex(3, 0) # => (8+0i)
4573 *
4574 */
4575 VALUE
4576rb_int_pow(VALUE x, VALUE y)
4577{
4578 if (FIXNUM_P(x)) {
4579 return fix_pow(x, y);
4580 }
4581 else if (RB_BIGNUM_TYPE_P(x)) {
4582 return rb_big_pow(x, y);
4583 }
4584 return Qnil;
4585}
4586
4587 VALUE
4588rb_num_pow(VALUE x, VALUE y)
4589{
4590 VALUE z = rb_int_pow(x, y);
4591 if (!NIL_P(z)) return z;
4592 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4593 if (SPECIAL_CONST_P(x)) return Qnil;
4594 switch (BUILTIN_TYPE(x)) {
4595 case T_COMPLEX:
4596 return rb_complex_pow(x, y);
4597 case T_RATIONAL:
4598 return rb_rational_pow(x, y);
4599 default:
4600 break;
4601 }
4602 return Qnil;
4603}
4604
4605static VALUE
4606fix_equal(VALUE x, VALUE y)
4607{
4608 if (x == y) return Qtrue;
4609 if (FIXNUM_P(y)) return Qfalse;
4610 else if (RB_BIGNUM_TYPE_P(y)) {
4611 return rb_big_eq(y, x);
4612 }
4613 else if (RB_FLOAT_TYPE_P(y)) {
4614 return rb_integer_float_eq(x, y);
4615 }
4616 else {
4617 return num_equal(x, y);
4618 }
4619}
4620
4621/*
4622 * call-seq:
4623 * self == other -> true or false
4624 *
4625 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4626 *
4627 * 1 == 2 #=> false
4628 * 1 == 1.0 #=> true
4629 *
4630 * Related: Integer#eql? (requires +other+ to be an \Integer).
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
5177 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
5401 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
5660/*
5661 * call-seq:
5662 * round(ndigits= 0, half: :up) -> integer
5663 *
5664 * Returns +self+ rounded to the nearest value with
5665 * a precision of +ndigits+ decimal digits.
5666 *
5667 * When +ndigits+ is negative, the returned value
5668 * has at least <tt>ndigits.abs</tt> trailing zeros:
5669 *
5670 * 555.round(-1) # => 560
5671 * 555.round(-2) # => 600
5672 * 555.round(-3) # => 1000
5673 * -555.round(-2) # => -600
5674 * 555.round(-4) # => 0
5675 *
5676 * Returns +self+ when +ndigits+ is zero or positive.
5677 *
5678 * 555.round # => 555
5679 * 555.round(1) # => 555
5680 * 555.round(50) # => 555
5681 *
5682 * If keyword argument +half+ is given,
5683 * and +self+ is equidistant from the two candidate values,
5684 * the rounding is according to the given +half+ value:
5685 *
5686 * - +:up+ or +nil+: round away from zero:
5687 *
5688 * 25.round(-1, half: :up) # => 30
5689 * (-25).round(-1, half: :up) # => -30
5690 *
5691 * - +:down+: round toward zero:
5692 *
5693 * 25.round(-1, half: :down) # => 20
5694 * (-25).round(-1, half: :down) # => -20
5695 *
5696 *
5697 * - +:even+: round toward the candidate whose last nonzero digit is even:
5698 *
5699 * 25.round(-1, half: :even) # => 20
5700 * 15.round(-1, half: :even) # => 20
5701 * (-25).round(-1, half: :even) # => -20
5702 *
5703 * Raises and exception if the value for +half+ is invalid.
5704 *
5705 * Related: Integer#truncate.
5706 *
5707 */
5708
5709static VALUE
5710int_round(int argc, VALUE* argv, VALUE num)
5711{
5712 int ndigits;
5713 int mode;
5714 VALUE nd, opt;
5715
5716 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5717 ndigits = NUM2INT(nd);
5718 mode = rb_num_get_rounding_option(opt);
5719 if (ndigits >= 0) {
5720 return num;
5721 }
5722 return rb_int_round(num, ndigits, mode);
5723}
5724
5725/*
5726 * call-seq:
5727 * floor(ndigits = 0) -> integer
5728 *
5729 * Returns the largest number less than or equal to +self+ with
5730 * a precision of +ndigits+ decimal digits.
5731 *
5732 * When +ndigits+ is negative, the returned value
5733 * has at least <tt>ndigits.abs</tt> trailing zeros:
5734 *
5735 * 555.floor(-1) # => 550
5736 * 555.floor(-2) # => 500
5737 * -555.floor(-2) # => -600
5738 * 555.floor(-3) # => 0
5739 *
5740 * Returns +self+ when +ndigits+ is zero or positive.
5741 *
5742 * 555.floor # => 555
5743 * 555.floor(50) # => 555
5744 *
5745 * Related: Integer#ceil.
5746 *
5747 */
5748
5749static VALUE
5750int_floor(int argc, VALUE* argv, VALUE num)
5751{
5752 int ndigits;
5753
5754 if (!rb_check_arity(argc, 0, 1)) return num;
5755 ndigits = NUM2INT(argv[0]);
5756 if (ndigits >= 0) {
5757 return num;
5758 }
5759 return rb_int_floor(num, ndigits);
5760}
5761
5762/*
5763 * call-seq:
5764 * ceil(ndigits = 0) -> integer
5765 *
5766 * Returns the smallest number greater than or equal to +self+ with
5767 * a precision of +ndigits+ decimal digits.
5768 *
5769 * When the precision is negative, the returned value is an integer
5770 * with at least <code>ndigits.abs</code> trailing zeros:
5771 *
5772 * 555.ceil(-1) # => 560
5773 * 555.ceil(-2) # => 600
5774 * -555.ceil(-2) # => -500
5775 * 555.ceil(-3) # => 1000
5776 *
5777 * Returns +self+ when +ndigits+ is zero or positive.
5778 *
5779 * 555.ceil # => 555
5780 * 555.ceil(50) # => 555
5781 *
5782 * Related: Integer#floor.
5783 *
5784 */
5785
5786static VALUE
5787int_ceil(int argc, VALUE* argv, VALUE num)
5788{
5789 int ndigits;
5790
5791 if (!rb_check_arity(argc, 0, 1)) return num;
5792 ndigits = NUM2INT(argv[0]);
5793 if (ndigits >= 0) {
5794 return num;
5795 }
5796 return rb_int_ceil(num, ndigits);
5797}
5798
5799/*
5800 * call-seq:
5801 * truncate(ndigits = 0) -> integer
5802 *
5803 * Returns +self+ truncated (toward zero) to
5804 * a precision of +ndigits+ decimal digits.
5805 *
5806 * When +ndigits+ is negative, the returned value
5807 * has at least <tt>ndigits.abs</tt> trailing zeros:
5808 *
5809 * 555.truncate(-1) # => 550
5810 * 555.truncate(-2) # => 500
5811 * -555.truncate(-2) # => -500
5812 *
5813 * Returns +self+ when +ndigits+ is zero or positive.
5814 *
5815 * 555.truncate # => 555
5816 * 555.truncate(50) # => 555
5817 *
5818 * Related: Integer#round.
5819 *
5820 */
5821
5822static VALUE
5823int_truncate(int argc, VALUE* argv, VALUE num)
5824{
5825 int ndigits;
5826
5827 if (!rb_check_arity(argc, 0, 1)) return num;
5828 ndigits = NUM2INT(argv[0]);
5829 if (ndigits >= 0) {
5830 return num;
5831 }
5832 return rb_int_truncate(num, ndigits);
5833}
5834
5835#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5836rettype \
5837prefix##_isqrt(argtype n) \
5838{ \
5839 if (!argtype##_IN_DOUBLE_P(n)) { \
5840 unsigned int b = bit_length(n); \
5841 argtype t; \
5842 rettype x = (rettype)(n >> (b/2+1)); \
5843 x |= ((rettype)1LU << (b-1)/2); \
5844 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5845 return x; \
5846 } \
5847 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5848}
5849
5850#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5851# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5852#else
5853# define RB_ULONG_IN_DOUBLE_P(n) 1
5854#endif
5855#define RB_ULONG_TO_DOUBLE(n) (double)(n)
5856#define RB_ULONG unsigned long
5857DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5858
5859#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5860# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5861# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5862# else
5863# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5864# endif
5865# ifdef ULL_TO_DOUBLE
5866# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
5867# else
5868# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
5869# endif
5870DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
5871#endif
5872
5873#define domain_error(msg) \
5874 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
5875
5876/*
5877 * call-seq:
5878 * Integer.sqrt(numeric) -> integer
5879 *
5880 * Returns the integer square root of the non-negative integer +n+,
5881 * which is the largest non-negative integer less than or equal to the
5882 * square root of +numeric+.
5883 *
5884 * Integer.sqrt(0) # => 0
5885 * Integer.sqrt(1) # => 1
5886 * Integer.sqrt(24) # => 4
5887 * Integer.sqrt(25) # => 5
5888 * Integer.sqrt(10**400) # => 10**200
5889 *
5890 * If +numeric+ is not an \Integer, it is converted to an \Integer:
5891 *
5892 * Integer.sqrt(Complex(4, 0)) # => 2
5893 * Integer.sqrt(Rational(4, 1)) # => 2
5894 * Integer.sqrt(4.0) # => 2
5895 * Integer.sqrt(3.14159) # => 1
5896 *
5897 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
5898 * except that the result of the latter code may differ from the true value
5899 * due to the limited precision of floating point arithmetic.
5900 *
5901 * Integer.sqrt(10**46) # => 100000000000000000000000
5902 * Math.sqrt(10**46).floor # => 99999999999999991611392
5903 *
5904 * Raises an exception if +numeric+ is negative.
5905 *
5906 */
5907
5908static VALUE
5909rb_int_s_isqrt(VALUE self, VALUE num)
5910{
5911 unsigned long n, sq;
5912 num = rb_to_int(num);
5913 if (FIXNUM_P(num)) {
5914 if (FIXNUM_NEGATIVE_P(num)) {
5915 domain_error("isqrt");
5916 }
5917 n = FIX2ULONG(num);
5918 sq = rb_ulong_isqrt(n);
5919 return LONG2FIX(sq);
5920 }
5921 else {
5922 size_t biglen;
5923 if (RBIGNUM_NEGATIVE_P(num)) {
5924 domain_error("isqrt");
5925 }
5926 biglen = BIGNUM_LEN(num);
5927 if (biglen == 0) return INT2FIX(0);
5928#if SIZEOF_BDIGIT <= SIZEOF_LONG
5929 /* short-circuit */
5930 if (biglen == 1) {
5931 n = BIGNUM_DIGITS(num)[0];
5932 sq = rb_ulong_isqrt(n);
5933 return ULONG2NUM(sq);
5934 }
5935#endif
5936 return rb_big_isqrt(num);
5937 }
5938}
5939
5940/*
5941 * call-seq:
5942 * Integer.try_convert(object) -> object, integer, or nil
5943 *
5944 * If +object+ is an \Integer object, returns +object+.
5945 * Integer.try_convert(1) # => 1
5946 *
5947 * Otherwise if +object+ responds to <tt>:to_int</tt>,
5948 * calls <tt>object.to_int</tt> and returns the result.
5949 * Integer.try_convert(1.25) # => 1
5950 *
5951 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
5952 * Integer.try_convert([]) # => nil
5953 *
5954 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
5955 */
5956static VALUE
5957int_s_try_convert(VALUE self, VALUE num)
5958{
5959 return rb_check_integer_type(num);
5960}
5961
5962/*
5963 * Document-class: ZeroDivisionError
5964 *
5965 * Raised when attempting to divide an integer by 0.
5966 *
5967 * 42 / 0 #=> ZeroDivisionError: divided by 0
5968 *
5969 * Note that only division by an exact 0 will raise the exception:
5970 *
5971 * 42 / 0.0 #=> Float::INFINITY
5972 * 42 / -0.0 #=> -Float::INFINITY
5973 * 0 / 0.0 #=> NaN
5974 */
5975
5976/*
5977 * Document-class: FloatDomainError
5978 *
5979 * Raised when attempting to convert special float values (in particular
5980 * +Infinity+ or +NaN+) to numerical classes which don't support them.
5981 *
5982 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
5983 */
5984
5985/*
5986 * Document-class: Numeric
5987 *
5988 * \Numeric is the class from which all higher-level numeric classes should inherit.
5989 *
5990 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
5991 * Integer are implemented as immediates, which means that each Integer is a single immutable
5992 * object which is always passed by value.
5993 *
5994 * a = 1
5995 * 1.object_id == a.object_id #=> true
5996 *
5997 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
5998 * by preventing instantiation. If duplication is attempted, the same instance is returned.
5999 *
6000 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6001 * 1.dup #=> 1
6002 * 1.object_id == 1.dup.object_id #=> true
6003 *
6004 * For this reason, \Numeric should be used when defining other numeric classes.
6005 *
6006 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6007 * Array containing an object that has been coerced into an instance of the new class
6008 * and +self+ (see #coerce).
6009 *
6010 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6011 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6012 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6013 * instances of other numeric classes.
6014 *
6015 * class Tally < Numeric
6016 * def initialize(string)
6017 * @string = string
6018 * end
6019 *
6020 * def to_s
6021 * @string
6022 * end
6023 *
6024 * def to_i
6025 * @string.size
6026 * end
6027 *
6028 * def coerce(other)
6029 * [self.class.new('|' * other.to_i), self]
6030 * end
6031 *
6032 * def <=>(other)
6033 * to_i <=> other.to_i
6034 * end
6035 *
6036 * def +(other)
6037 * self.class.new('|' * (to_i + other.to_i))
6038 * end
6039 *
6040 * def -(other)
6041 * self.class.new('|' * (to_i - other.to_i))
6042 * end
6043 *
6044 * def *(other)
6045 * self.class.new('|' * (to_i * other.to_i))
6046 * end
6047 *
6048 * def /(other)
6049 * self.class.new('|' * (to_i / other.to_i))
6050 * end
6051 * end
6052 *
6053 * tally = Tally.new('||')
6054 * puts tally * 2 #=> "||||"
6055 * puts tally > 1 #=> true
6056 *
6057 * == What's Here
6058 *
6059 * First, what's elsewhere. \Class \Numeric:
6060 *
6061 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6062 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6063 *
6064 * Here, class \Numeric provides methods for:
6065 *
6066 * - {Querying}[rdoc-ref:Numeric@Querying]
6067 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6068 * - {Converting}[rdoc-ref:Numeric@Converting]
6069 * - {Other}[rdoc-ref:Numeric@Other]
6070 *
6071 * === Querying
6072 *
6073 * - #finite?: Returns true unless +self+ is infinite or not a number.
6074 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6075 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6076 * - #integer?: Returns whether +self+ is an integer.
6077 * - #negative?: Returns whether +self+ is negative.
6078 * - #nonzero?: Returns whether +self+ is not zero.
6079 * - #positive?: Returns whether +self+ is positive.
6080 * - #real?: Returns whether +self+ is a real value.
6081 * - #zero?: Returns whether +self+ is zero.
6082 *
6083 * === Comparing
6084 *
6085 * - #<=>: Returns:
6086 *
6087 * - -1 if +self+ is less than the given value.
6088 * - 0 if +self+ is equal to the given value.
6089 * - 1 if +self+ is greater than the given value.
6090 * - +nil+ if +self+ and the given value are not comparable.
6091 *
6092 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6093 *
6094 * === Converting
6095 *
6096 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6097 * - #-@: Returns the value of +self+, negated.
6098 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6099 * - #abs2: Returns the square of +self+.
6100 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6101 * Math::PI otherwise.
6102 * - #ceil: Returns the smallest number greater than or equal to +self+,
6103 * to a given precision.
6104 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6105 * for the given other value.
6106 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6107 * - #denominator: Returns the denominator (always positive)
6108 * of the Rational representation of +self+.
6109 * - #div: Returns the value of +self+ divided by the given value
6110 * and converted to an integer.
6111 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6112 * from dividing +self+ the given divisor.
6113 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6114 * - #floor: Returns the largest number less than or equal to +self+,
6115 * to a given precision.
6116 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6117 * the given value.
6118 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6119 * - #numerator: Returns the numerator of the Rational representation of +self+;
6120 * has the same sign as +self+.
6121 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6122 * - #quo: Returns the value of +self+ divided by the given value.
6123 * - #real: Returns the real part of +self+.
6124 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6125 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6126 * - #round: Returns the value of +self+ rounded to the nearest value
6127 * for the given a precision.
6128 * - #to_c: Returns the Complex representation of +self+.
6129 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6130 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6131 *
6132 * === Other
6133 *
6134 * - #clone: Returns +self+; does not allow freezing.
6135 * - #dup (aliased as #+@): Returns +self+.
6136 * - #step: Invokes the given block with the sequence of specified numbers.
6137 *
6138 */
6139void
6140Init_Numeric(void)
6141{
6142#ifdef _UNICOSMP
6143 /* Turn off floating point exceptions for divide by zero, etc. */
6144 _set_Creg(0, 0);
6145#endif
6146 id_coerce = rb_intern_const("coerce");
6147 id_to = rb_intern_const("to");
6148 id_by = rb_intern_const("by");
6149
6150 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6151 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6152 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6153
6154 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6155 rb_include_module(rb_cNumeric, rb_mComparable);
6156 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6157 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6158 rb_define_method(rb_cNumeric, "dup", num_dup, 0);
6159
6160 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6161 rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
6162 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6163 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6164 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6165 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6166 rb_define_method(rb_cNumeric, "div", num_div, 1);
6167 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6168 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6169 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6170 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6171 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6172 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6173 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6174
6175 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6176 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6177
6178 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6179 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6180 rb_define_method(rb_cNumeric, "round", num_round, -1);
6181 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6182 rb_define_method(rb_cNumeric, "step", num_step, -1);
6183 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6184 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6185
6186 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6187 rb_undef_alloc_func(rb_cInteger);
6188 rb_undef_method(CLASS_OF(rb_cInteger), "new");
6189 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6190 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6191
6192 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6193 rb_define_alias(rb_cInteger, "inspect", "to_s");
6194 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6195 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6196 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6197 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6198 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6199 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6200 rb_define_method(rb_cInteger, "next", int_succ, 0);
6201 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6202 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6203 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6204 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6205 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6206 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6207 rb_define_method(rb_cInteger, "round", int_round, -1);
6208 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6209
6210 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6211 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6212 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6213 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6214 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6215 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6216 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6217 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6218 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6219 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6220 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6221
6222 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6223
6224 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6225 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6226 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6227 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6228 rb_define_method(rb_cInteger, "<", int_lt, 1);
6229 rb_define_method(rb_cInteger, "<=", int_le, 1);
6230
6231 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6232 rb_define_method(rb_cInteger, "|", int_or, 1);
6233 rb_define_method(rb_cInteger, "^", int_xor, 1);
6234 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6235
6236 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6237 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6238
6239 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6240
6241 rb_fix_to_s_static[0] = rb_fstring_literal("0");
6242 rb_fix_to_s_static[1] = rb_fstring_literal("1");
6243 rb_fix_to_s_static[2] = rb_fstring_literal("2");
6244 rb_fix_to_s_static[3] = rb_fstring_literal("3");
6245 rb_fix_to_s_static[4] = rb_fstring_literal("4");
6246 rb_fix_to_s_static[5] = rb_fstring_literal("5");
6247 rb_fix_to_s_static[6] = rb_fstring_literal("6");
6248 rb_fix_to_s_static[7] = rb_fstring_literal("7");
6249 rb_fix_to_s_static[8] = rb_fstring_literal("8");
6250 rb_fix_to_s_static[9] = rb_fstring_literal("9");
6251 for(int i = 0; i < 10; i++) {
6252 rb_gc_register_mark_object(rb_fix_to_s_static[i]);
6253 }
6254
6255 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6256
6257 rb_undef_alloc_func(rb_cFloat);
6258 rb_undef_method(CLASS_OF(rb_cFloat), "new");
6259
6260 /*
6261 * The base of the floating point, or number of unique digits used to
6262 * represent the number.
6263 *
6264 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6265 */
6266 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6267 /*
6268 * The number of base digits for the +double+ data type.
6269 *
6270 * Usually defaults to 53.
6271 */
6272 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6273 /*
6274 * The minimum number of significant decimal digits in a double-precision
6275 * floating point.
6276 *
6277 * Usually defaults to 15.
6278 */
6279 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6280 /*
6281 * The smallest possible exponent value in a double-precision floating
6282 * point.
6283 *
6284 * Usually defaults to -1021.
6285 */
6286 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6287 /*
6288 * The largest possible exponent value in a double-precision floating
6289 * point.
6290 *
6291 * Usually defaults to 1024.
6292 */
6293 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6294 /*
6295 * The smallest negative exponent in a double-precision floating point
6296 * where 10 raised to this power minus 1.
6297 *
6298 * Usually defaults to -307.
6299 */
6300 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6301 /*
6302 * The largest positive exponent in a double-precision floating point where
6303 * 10 raised to this power minus 1.
6304 *
6305 * Usually defaults to 308.
6306 */
6307 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6308 /*
6309 * The smallest positive normalized number in a double-precision floating point.
6310 *
6311 * Usually defaults to 2.2250738585072014e-308.
6312 *
6313 * If the platform supports denormalized numbers,
6314 * there are numbers between zero and Float::MIN.
6315 * 0.0.next_float returns the smallest positive floating point number
6316 * including denormalized numbers.
6317 */
6318 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6319 /*
6320 * The largest possible integer in a double-precision floating point number.
6321 *
6322 * Usually defaults to 1.7976931348623157e+308.
6323 */
6324 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6325 /*
6326 * The difference between 1 and the smallest double-precision floating
6327 * point number greater than 1.
6328 *
6329 * Usually defaults to 2.2204460492503131e-16.
6330 */
6331 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6332 /*
6333 * An expression representing positive infinity.
6334 */
6335 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6336 /*
6337 * An expression representing a value which is "not a number".
6338 */
6339 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6340
6341 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6342 rb_define_alias(rb_cFloat, "inspect", "to_s");
6343 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6344 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6345 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6346 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6347 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6348 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6349 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6350 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6351 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6352 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6353 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6354 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6355 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6356 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6357 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6358 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6359 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6360 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6361 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6362 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6363
6364 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6365 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6366 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6367 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6368 rb_define_method(rb_cFloat, "round", flo_round, -1);
6369 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6370
6371 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6372 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6373 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6374 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6375 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6376}
6377
6378#undef rb_float_value
6379double
6380rb_float_value(VALUE v)
6381{
6382 return rb_float_value_inline(v);
6383}
6384
6385#undef rb_float_new
6386 VALUE
6387rb_float_new(double d)
6388{
6389 return rb_float_new_inline(d);
6390}
6391
6392#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:1019
rb_include_module
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1177
rb_define_class
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:970
rb_singleton_class
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2284
rb_define_alias
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2332
rb_undef_method
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2156
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:2622
rb_block_given_p
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:866
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:2411
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
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:135
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_eNotImpError
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1354
rb_name_error
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2037
rb_eZeroDivError
VALUE rb_eZeroDivError
ZeroDivisionError exception.
Definition numeric.c:200
rb_eStandardError
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1341
rb_eRangeError
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1348
rb_eTypeError
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1344
rb_eFloatDomainError
VALUE rb_eFloatDomainError
FloatDomainError exception.
Definition numeric.c:201
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:3548
rb_any_to_s
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:634
rb_cInteger
VALUE rb_cInteger
Module class.
Definition numeric.c:198
rb_cNumeric
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:196
rb_obj_class
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:215
rb_inspect
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:645
rb_equal
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:147
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:830
rb_mComparable
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
rb_cFloat
VALUE rb_cFloat
Float class.
Definition numeric.c:197
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:3145
encoding.h
Encoding relates APIs.
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:3739
rb_funcall
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1121
RGENGC_WB_PROTECTED_FLOAT
#define RGENGC_WB_PROTECTED_FLOAT
This is a compile-time flag to enable/disable write barrier for struct RFloat.
Definition gc.h:550
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:206
rb_num2fix
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3381
rb_fix2str
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:3845
rb_dbl_cmp
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
Definition numeric.c:1662
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:499
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:484
rb_num_coerce_bin
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:477
rb_range_values
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1656
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_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_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:2530
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:2681
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:5266
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:5277
rb_undef_alloc_func
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1274
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:687
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:1695
rb_intern_const
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:276
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:953
rb_to_id
ID rb_to_id(VALUE str)
Definition string.c:12032
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:3690
len
int len
Length of the buffer.
Definition io.h:8
util.h
rb_num2uint
unsigned long rb_num2uint(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3295
rb_fix2int
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3289
rb_num2int
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3283
rb_fix2uint
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3301
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:1376
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:3210
rb_num2long
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3135
rb_num2ulong
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3204
RARRAY_LEN
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
RARRAY_LENINT
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:281
RARRAY_AREF
#define RARRAY_AREF(a, i)
Definition rarray.h:403
RARRAY_CONST_PTR
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
RBIGNUM_NEGATIVE_P
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
Definition rbignum.h:74
rb_obj_classname
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:417
rb_num2short
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
Definition numeric.c:3339
rb_num2ushort
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3357
rb_fix2short
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3348
rb_fix2ushort
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3367
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