Ruby: numeric.c Source File

Ruby 3.3.4p94 (2024-07-09 revision be1089c8ec5ba40e09b1553e36b3174bf4014d9d)

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