Correct order of listed methods
[ruby.git] / numeric.c
bloba36370b9a46e9c310bba006ce6cfcb3a57679203
1 /**********************************************************************
3 numeric.c -
5 $Author$
6 created at: Fri Aug 13 18:33:09 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/internal/config.h"
14 #include <assert.h>
15 #include <ctype.h>
16 #include <math.h>
17 #include <stdio.h>
19 #ifdef HAVE_FLOAT_H
20 #include <float.h>
21 #endif
23 #ifdef HAVE_IEEEFP_H
24 #include <ieeefp.h>
25 #endif
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"
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
77 #ifndef USE_RB_INFINITY
78 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
79 const union bytesequence4_or_float rb_infinity = {{0x00, 0x00, 0x80, 0x7f}};
80 #else
81 const union bytesequence4_or_float rb_infinity = {{0x7f, 0x80, 0x00, 0x00}};
82 #endif
84 #ifndef USE_RB_NAN
85 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
86 const union bytesequence4_or_float rb_nan = {{0x00, 0x00, 0xc0, 0x7f}};
87 #else
88 const union bytesequence4_or_float rb_nan = {{0x7f, 0xc0, 0x00, 0x00}};
89 #endif
91 #ifndef HAVE_ROUND
92 double
93 round(double x)
95 double f;
97 if (x > 0.0) {
98 f = floor(x);
99 x = f + (x - f >= 0.5);
101 else if (x < 0.0) {
102 f = ceil(x);
103 x = f - (f - x >= 0.5);
105 return x;
107 #endif
109 static double
110 round_half_up(double x, double s)
112 double f, xs = x * s;
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;
120 else {
121 if ((double)((f - 0.5) / s) >= x) f -= 1;
122 x = f;
124 return x;
127 static double
128 round_half_down(double x, double s)
130 double f, xs = x * s;
132 f = round(xs);
133 if (x > 0) {
134 if ((double)((f - 0.5) / s) >= x) f -= 1;
135 x = f;
137 else {
138 if ((double)((f + 0.5) / s) <= x) f += 1;
139 x = f;
141 return x;
144 static double
145 round_half_even(double x, double s)
147 double u, v, us, vs, f, d, uf;
149 v = modf(x, &u);
150 us = u * s;
151 vs = v * s;
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;
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;
177 return us + x;
180 static VALUE fix_lshift(long, unsigned long);
181 static VALUE fix_rshift(long, unsigned long);
182 static VALUE int_pow(long x, unsigned long y);
183 static VALUE rb_int_floor(VALUE num, int ndigits);
184 static VALUE rb_int_ceil(VALUE num, int ndigits);
185 static VALUE flo_to_i(VALUE num);
186 static int float_round_overflow(int ndigits, int binexp);
187 static int float_round_underflow(int ndigits, int binexp);
189 static 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
196 VALUE rb_cNumeric;
197 VALUE rb_cFloat;
198 VALUE rb_cInteger;
200 VALUE rb_eZeroDivError;
201 VALUE rb_eFloatDomainError;
203 static ID id_to, id_by;
205 void
206 rb_num_zerodiv(void)
208 rb_raise(rb_eZeroDivError, "divided by 0");
211 enum ruby_num_rounding_mode
212 rb_num_get_rounding_option(VALUE opts)
214 static ID round_kwds[1];
215 VALUE rounding;
216 VALUE str;
217 const char *s;
219 if (!NIL_P(opts)) {
220 if (!round_kwds[0]) {
221 round_kwds[0] = rb_intern_const("half");
223 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
224 if (SYMBOL_P(rounding)) {
225 str = rb_sym2str(rounding);
227 else if (NIL_P(rounding)) {
228 goto noopt;
230 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
231 str = rb_check_string_type(rounding);
232 if (NIL_P(str)) goto invalid;
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;
248 invalid:
249 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
251 noopt:
252 return RUBY_NUM_ROUND_DEFAULT;
255 /* experimental API */
257 rb_num_to_uint(VALUE val, unsigned int *ret)
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;
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
284 return NUMERR_TYPE;
287 #define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
289 static inline int
290 int_pos_p(VALUE num)
292 if (FIXNUM_P(num)) {
293 return FIXNUM_POSITIVE_P(num);
295 else if (RB_BIGNUM_TYPE_P(num)) {
296 return BIGNUM_POSITIVE_P(num);
298 rb_raise(rb_eTypeError, "not an Integer");
301 static inline int
302 int_neg_p(VALUE num)
304 if (FIXNUM_P(num)) {
305 return FIXNUM_NEGATIVE_P(num);
307 else if (RB_BIGNUM_TYPE_P(num)) {
308 return BIGNUM_NEGATIVE_P(num);
310 rb_raise(rb_eTypeError, "not an Integer");
314 rb_int_positive_p(VALUE num)
316 return int_pos_p(num);
320 rb_int_negative_p(VALUE num)
322 return int_neg_p(num);
326 rb_num_negative_p(VALUE num)
328 return rb_num_negative_int_p(num);
331 static VALUE
332 num_funcall_op_0(VALUE x, VALUE arg, int recursive)
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));
341 else if (name[0] && name[1] == '@' && !name[2]) {
342 rb_name_error(func, "%c%"PRIsVALUE,
343 name[0], x);
345 else {
346 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
347 ID2SYM(func), x);
350 return rb_funcallv(x, func, 0, 0);
353 static VALUE
354 num_funcall0(VALUE x, ID func)
356 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
359 NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
361 static void
362 num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
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);
369 else {
370 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
371 x, ID2SYM(func), y);
375 static VALUE
376 num_funcall_op_1(VALUE y, VALUE arg, int recursive)
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);
383 return rb_funcall(x, func, 1, y);
386 static VALUE
387 num_funcall1(VALUE x, ID func, VALUE y)
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);
396 * call-seq:
397 * coerce(other) -> array
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.
403 * Of the Core and Standard Library classes,
404 * Integer, Rational, and Complex use this implementation.
406 * Examples:
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.
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)]
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)]
426 * Raises an exception if any type conversion fails.
430 static VALUE
431 num_coerce(VALUE x, VALUE y)
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);
440 NORETURN(static void coerce_failed(VALUE x, VALUE y));
441 static void
442 coerce_failed(VALUE x, VALUE y)
444 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
445 y = rb_inspect(y);
447 else {
448 y = rb_obj_class(y);
450 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
451 y, rb_obj_class(x));
454 static int
455 do_coerce(VALUE *x, VALUE *y, int err)
457 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
458 if (UNDEF_P(ary)) {
459 if (err) {
460 coerce_failed(*x, *y);
462 return FALSE;
464 if (!err && NIL_P(ary)) {
465 return FALSE;
467 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
468 rb_raise(rb_eTypeError, "coerce must return [x, y]");
471 *x = RARRAY_AREF(ary, 0);
472 *y = RARRAY_AREF(ary, 1);
473 return TRUE;
476 VALUE
477 rb_num_coerce_bin(VALUE x, VALUE y, ID func)
479 do_coerce(&x, &y, TRUE);
480 return rb_funcall(x, func, 1, y);
483 VALUE
484 rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
486 if (do_coerce(&x, &y, FALSE))
487 return rb_funcall(x, func, 1, y);
488 return Qnil;
491 static VALUE
492 ensure_cmp(VALUE c, VALUE x, VALUE y)
494 if (NIL_P(c)) rb_cmperr(x, y);
495 return c;
498 VALUE
499 rb_num_coerce_relop(VALUE x, VALUE y, ID func)
501 VALUE x0 = x, y0 = y;
503 if (!do_coerce(&x, &y, FALSE)) {
504 rb_cmperr(x0, y0);
505 UNREACHABLE_RETURN(Qnil);
507 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
510 NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
513 * :nodoc:
515 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
517 * Numerics should be values; singleton_methods should not be added to them.
520 static VALUE
521 num_sadded(VALUE x, VALUE name)
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));
531 UNREACHABLE_RETURN(Qnil);
534 #if 0
536 * call-seq:
537 * clone(freeze: true) -> self
539 * Returns +self+.
541 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
543 * Related: Numeric#dup.
546 static VALUE
547 num_clone(int argc, VALUE *argv, VALUE x)
549 return rb_immutable_obj_clone(argc, argv, x);
551 #else
552 # define num_clone rb_immutable_obj_clone
553 #endif
556 * call-seq:
557 * i -> complex
559 * Returns <tt>Complex(0, self)</tt>:
561 * 2.i # => (0+2i)
562 * -2.i # => (0-2i)
563 * 2.0.i # => (0+2.0i)
564 * Rational(1, 2).i # => (0+(1/2)*i)
565 * Complex(3, 4).i # Raises NoMethodError.
569 static VALUE
570 num_imaginary(VALUE num)
572 return rb_complex_new(INT2FIX(0), num);
576 * call-seq:
577 * -self -> numeric
579 * Unary Minus---Returns the receiver, negated.
582 static VALUE
583 num_uminus(VALUE num)
585 VALUE zero;
587 zero = INT2FIX(0);
588 do_coerce(&zero, &num, TRUE);
590 return num_funcall1(zero, '-', num);
594 * call-seq:
595 * fdiv(other) -> float
597 * Returns the quotient <tt>self/other</tt> as a float,
598 * using method +/+ in the derived class of +self+.
599 * (\Numeric itself does not define method +/+.)
601 * Of the Core and Standard Library classes,
602 * only BigDecimal uses this implementation.
606 static VALUE
607 num_fdiv(VALUE x, VALUE y)
609 return rb_funcall(rb_Float(x), '/', 1, y);
613 * call-seq:
614 * div(other) -> integer
616 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
617 * using method +/+ in the derived class of +self+.
618 * (\Numeric itself does not define method +/+.)
620 * Of the Core and Standard Library classes,
621 * Only Float and Rational use this implementation.
625 static VALUE
626 num_div(VALUE x, VALUE y)
628 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
629 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
633 * call-seq:
634 * self % other -> real_numeric
636 * Returns +self+ modulo +other+ as a real number.
638 * Of the Core and Standard Library classes,
639 * only Rational uses this implementation.
641 * For Rational +r+ and real number +n+, these expressions are equivalent:
643 * r % n
644 * r-n*(r/n).floor
645 * r.divmod(n)[1]
647 * See Numeric#divmod.
649 * Examples:
651 * r = Rational(1, 2) # => (1/2)
652 * r2 = Rational(2, 3) # => (2/3)
653 * r % r2 # => (1/2)
654 * r % 2 # => (1/2)
655 * r % 2.0 # => 0.5
657 * r = Rational(301,100) # => (301/100)
658 * r2 = Rational(7,5) # => (7/5)
659 * r % r2 # => (21/100)
660 * r % -r2 # => (-119/100)
661 * (-r) % r2 # => (119/100)
662 * (-r) %-r2 # => (-21/100)
666 static VALUE
667 num_modulo(VALUE x, VALUE y)
669 VALUE q = num_funcall1(x, id_div, y);
670 return rb_funcall(x, '-', 1,
671 rb_funcall(y, '*', 1, q));
675 * call-seq:
676 * remainder(other) -> real_number
678 * Returns the remainder after dividing +self+ by +other+.
680 * Of the Core and Standard Library classes,
681 * only Float and Rational use this implementation.
683 * Examples:
685 * 11.0.remainder(4) # => 3.0
686 * 11.0.remainder(-4) # => 3.0
687 * -11.0.remainder(4) # => -3.0
688 * -11.0.remainder(-4) # => -3.0
690 * 12.0.remainder(4) # => 0.0
691 * 12.0.remainder(-4) # => 0.0
692 * -12.0.remainder(4) # => -0.0
693 * -12.0.remainder(-4) # => -0.0
695 * 13.0.remainder(4.0) # => 1.0
696 * 13.0.remainder(Rational(4, 1)) # => 1.0
698 * Rational(13, 1).remainder(4) # => (1/1)
699 * Rational(13, 1).remainder(-4) # => (1/1)
700 * Rational(-13, 1).remainder(4) # => (-1/1)
701 * Rational(-13, 1).remainder(-4) # => (-1/1)
705 static VALUE
706 num_remainder(VALUE x, VALUE y)
708 if (!rb_obj_is_kind_of(y, rb_cNumeric)) {
709 do_coerce(&x, &y, TRUE);
711 VALUE z = num_funcall1(x, '%', y);
713 if ((!rb_equal(z, INT2FIX(0))) &&
714 ((rb_num_negative_int_p(x) &&
715 rb_num_positive_int_p(y)) ||
716 (rb_num_positive_int_p(x) &&
717 rb_num_negative_int_p(y)))) {
718 if (RB_FLOAT_TYPE_P(y)) {
719 if (isinf(RFLOAT_VALUE(y))) {
720 return x;
723 return rb_funcall(z, '-', 1, y);
725 return z;
729 * call-seq:
730 * divmod(other) -> array
732 * Returns a 2-element array <tt>[q, r]</tt>, where
734 * q = (self/other).floor # Quotient
735 * r = self % other # Remainder
737 * Of the Core and Standard Library classes,
738 * only Rational uses this implementation.
740 * Examples:
742 * Rational(11, 1).divmod(4) # => [2, (3/1)]
743 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
744 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
745 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
747 * Rational(12, 1).divmod(4) # => [3, (0/1)]
748 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
749 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
750 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
752 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
753 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
756 static VALUE
757 num_divmod(VALUE x, VALUE y)
759 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
763 * call-seq:
764 * abs -> numeric
766 * Returns the absolute value of +self+.
768 * 12.abs #=> 12
769 * (-34.56).abs #=> 34.56
770 * -34.56.abs #=> 34.56
774 static VALUE
775 num_abs(VALUE num)
777 if (rb_num_negative_int_p(num)) {
778 return num_funcall0(num, idUMinus);
780 return num;
784 * call-seq:
785 * zero? -> true or false
787 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
789 * Of the Core and Standard Library classes,
790 * only Rational and Complex use this implementation.
794 static VALUE
795 num_zero_p(VALUE num)
797 return rb_equal(num, INT2FIX(0));
800 static bool
801 int_zero_p(VALUE num)
803 if (FIXNUM_P(num)) {
804 return FIXNUM_ZERO_P(num);
806 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
807 return rb_bigzero_p(num);
810 VALUE
811 rb_int_zero_p(VALUE num)
813 return RBOOL(int_zero_p(num));
817 * call-seq:
818 * nonzero? -> self or nil
820 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
821 * uses method <tt>zero?</tt> for the evaluation.
823 * The returned +self+ allows the method to be chained:
825 * a = %w[z Bb bB bb BB a aA Aa AA A]
826 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
827 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
829 * Of the Core and Standard Library classes,
830 * Integer, Float, Rational, and Complex use this implementation.
832 * Related: #zero?
836 static VALUE
837 num_nonzero_p(VALUE num)
839 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
840 return Qnil;
842 return num;
846 * call-seq:
847 * to_int -> integer
849 * Returns +self+ as an integer;
850 * converts using method +to_i+ in the derived class.
852 * Of the Core and Standard Library classes,
853 * only Rational and Complex use this implementation.
855 * Examples:
857 * Rational(1, 2).to_int # => 0
858 * Rational(2, 1).to_int # => 2
859 * Complex(2, 0).to_int # => 2
860 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
864 static VALUE
865 num_to_int(VALUE num)
867 return num_funcall0(num, id_to_i);
871 * call-seq:
872 * positive? -> true or false
874 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
878 static VALUE
879 num_positive_p(VALUE num)
881 const ID mid = '>';
883 if (FIXNUM_P(num)) {
884 if (method_basic_p(rb_cInteger))
885 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
887 else if (RB_BIGNUM_TYPE_P(num)) {
888 if (method_basic_p(rb_cInteger))
889 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
891 return rb_num_compare_with_zero(num, mid);
895 * call-seq:
896 * negative? -> true or false
898 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
902 static VALUE
903 num_negative_p(VALUE num)
905 return RBOOL(rb_num_negative_int_p(num));
909 /********************************************************************
911 * Document-class: Float
913 * A \Float object represents a sometimes-inexact real number using the native
914 * architecture's double-precision floating point representation.
916 * Floating point has a different arithmetic and is an inexact number.
917 * So you should know its esoteric system. See following:
919 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
920 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#-why-are-rubys-floats-imprecise
921 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
923 * You can create a \Float object explicitly with:
925 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
927 * You can convert certain objects to Floats with:
929 * - \Method #Float.
931 * == What's Here
933 * First, what's elsewhere. \Class \Float:
935 * - Inherits from
936 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
937 * and {class Object}[rdoc-ref:Object@What-27s+Here].
938 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
940 * Here, class \Float provides methods for:
942 * - {Querying}[rdoc-ref:Float@Querying]
943 * - {Comparing}[rdoc-ref:Float@Comparing]
944 * - {Converting}[rdoc-ref:Float@Converting]
946 * === Querying
948 * - #finite?: Returns whether +self+ is finite.
949 * - #hash: Returns the integer hash code for +self+.
950 * - #infinite?: Returns whether +self+ is infinite.
951 * - #nan?: Returns whether +self+ is a NaN (not-a-number).
953 * === Comparing
955 * - #<: Returns whether +self+ is less than the given value.
956 * - #<=: Returns whether +self+ is less than or equal to the given value.
957 * - #<=>: Returns a number indicating whether +self+ is less than, equal
958 * to, or greater than the given value.
959 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
960 * the given value.
961 * - #>: Returns whether +self+ is greater than the given value.
962 * - #>=: Returns whether +self+ is greater than or equal to the given value.
964 * === Converting
966 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
967 * - #*: Returns the product of +self+ and the given value.
968 * - #**: Returns the value of +self+ raised to the power of the given value.
969 * - #+: Returns the sum of +self+ and the given value.
970 * - #-: Returns the difference of +self+ and the given value.
971 * - #/: Returns the quotient of +self+ and the given value.
972 * - #ceil: Returns the smallest number greater than or equal to +self+.
973 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
974 * and +self+
975 * - #divmod: Returns a 2-element array containing the quotient and remainder
976 * results of dividing +self+ by the given value.
977 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
978 * - #floor: Returns the greatest number smaller than or equal to +self+.
979 * - #next_float: Returns the next-larger representable \Float.
980 * - #prev_float: Returns the next-smaller representable \Float.
981 * - #quo: Returns the quotient from dividing +self+ by the given value.
982 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
983 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
984 * - #to_s (aliased as #inspect): Returns a string containing the place-value
985 * representation of +self+ in the given radix.
986 * - #truncate: Returns +self+ truncated to a given precision.
990 VALUE
991 rb_float_new_in_heap(double d)
993 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0), sizeof(struct RFloat), 0);
995 #if SIZEOF_DOUBLE <= SIZEOF_VALUE
996 flt->float_value = d;
997 #else
998 union {
999 double d;
1000 rb_float_value_type v;
1001 } u = {d};
1002 flt->float_value = u.v;
1003 #endif
1004 OBJ_FREEZE((VALUE)flt);
1005 return (VALUE)flt;
1009 * call-seq:
1010 * to_s -> string
1012 * Returns a string containing a representation of +self+;
1013 * depending of the value of +self+, the string representation
1014 * may contain:
1016 * - A fixed-point number.
1017 * 3.14.to_s # => "3.14"
1018 * - A number in "scientific notation" (containing an exponent).
1019 * (10.1**50).to_s # => "1.644631821843879e+50"
1020 * - 'Infinity'.
1021 * (10.1**500).to_s # => "Infinity"
1022 * - '-Infinity'.
1023 * (-10.1**500).to_s # => "-Infinity"
1024 * - 'NaN' (indicating not-a-number).
1025 * (0.0/0.0).to_s # => "NaN"
1029 static VALUE
1030 flo_to_s(VALUE flt)
1032 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
1033 enum {float_dig = DBL_DIG+1};
1034 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
1035 double value = RFLOAT_VALUE(flt);
1036 VALUE s;
1037 char *p, *e;
1038 int sign, decpt, digs;
1040 if (isinf(value)) {
1041 static const char minf[] = "-Infinity";
1042 const int pos = (value > 0); /* skip "-" */
1043 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
1045 else if (isnan(value))
1046 return rb_usascii_str_new2("NaN");
1048 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
1049 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1050 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
1051 memcpy(buf, p, digs);
1052 free(p);
1053 if (decpt > 0) {
1054 if (decpt < digs) {
1055 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
1056 buf[decpt] = '.';
1057 rb_str_cat(s, buf, digs + 1);
1059 else if (decpt <= DBL_DIG) {
1060 long len;
1061 char *ptr;
1062 rb_str_cat(s, buf, digs);
1063 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
1064 ptr = RSTRING_PTR(s) + len;
1065 if (decpt > digs) {
1066 memset(ptr, '0', decpt - digs);
1067 ptr += decpt - digs;
1069 memcpy(ptr, ".0", 2);
1071 else {
1072 goto exp;
1075 else if (decpt > -4) {
1076 long len;
1077 char *ptr;
1078 rb_str_cat(s, "0.", 2);
1079 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1080 ptr = RSTRING_PTR(s);
1081 memset(ptr += len, '0', -decpt);
1082 memcpy(ptr -= decpt, buf, digs);
1084 else {
1085 goto exp;
1087 return s;
1089 exp:
1090 if (digs > 1) {
1091 memmove(buf + 2, buf + 1, digs - 1);
1093 else {
1094 buf[2] = '0';
1095 digs++;
1097 buf[1] = '.';
1098 rb_str_cat(s, buf, digs + 1);
1099 rb_str_catf(s, "e%+03d", decpt - 1);
1100 return s;
1104 * call-seq:
1105 * coerce(other) -> array
1107 * Returns a 2-element array containing +other+ converted to a \Float
1108 * and +self+:
1110 * f = 3.14 # => 3.14
1111 * f.coerce(2) # => [2.0, 3.14]
1112 * f.coerce(2.0) # => [2.0, 3.14]
1113 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1114 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1116 * Raises an exception if a type conversion fails.
1120 static VALUE
1121 flo_coerce(VALUE x, VALUE y)
1123 return rb_assoc_new(rb_Float(y), x);
1126 VALUE
1127 rb_float_uminus(VALUE flt)
1129 return DBL2NUM(-RFLOAT_VALUE(flt));
1133 * call-seq:
1134 * self + other -> numeric
1136 * Returns a new \Float which is the sum of +self+ and +other+:
1138 * f = 3.14
1139 * f + 1 # => 4.140000000000001
1140 * f + 1.0 # => 4.140000000000001
1141 * f + Rational(1, 1) # => 4.140000000000001
1142 * f + Complex(1, 0) # => (4.140000000000001+0i)
1146 VALUE
1147 rb_float_plus(VALUE x, VALUE y)
1149 if (FIXNUM_P(y)) {
1150 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1152 else if (RB_BIGNUM_TYPE_P(y)) {
1153 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1155 else if (RB_FLOAT_TYPE_P(y)) {
1156 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1158 else {
1159 return rb_num_coerce_bin(x, y, '+');
1164 * call-seq:
1165 * self - other -> numeric
1167 * Returns a new \Float which is the difference of +self+ and +other+:
1169 * f = 3.14
1170 * f - 1 # => 2.14
1171 * f - 1.0 # => 2.14
1172 * f - Rational(1, 1) # => 2.14
1173 * f - Complex(1, 0) # => (2.14+0i)
1177 VALUE
1178 rb_float_minus(VALUE x, VALUE y)
1180 if (FIXNUM_P(y)) {
1181 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1183 else if (RB_BIGNUM_TYPE_P(y)) {
1184 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1186 else if (RB_FLOAT_TYPE_P(y)) {
1187 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1189 else {
1190 return rb_num_coerce_bin(x, y, '-');
1195 * call-seq:
1196 * self * other -> numeric
1198 * Returns a new \Float which is the product of +self+ and +other+:
1200 * f = 3.14
1201 * f * 2 # => 6.28
1202 * f * 2.0 # => 6.28
1203 * f * Rational(1, 2) # => 1.57
1204 * f * Complex(2, 0) # => (6.28+0.0i)
1207 VALUE
1208 rb_float_mul(VALUE x, VALUE y)
1210 if (FIXNUM_P(y)) {
1211 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1213 else if (RB_BIGNUM_TYPE_P(y)) {
1214 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1216 else if (RB_FLOAT_TYPE_P(y)) {
1217 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1219 else {
1220 return rb_num_coerce_bin(x, y, '*');
1224 static double
1225 double_div_double(double x, double y)
1227 if (LIKELY(y != 0.0)) {
1228 return x / y;
1230 else if (x == 0.0) {
1231 return nan("");
1233 else {
1234 double z = signbit(y) ? -1.0 : 1.0;
1235 return x * z * HUGE_VAL;
1239 VALUE
1240 rb_flo_div_flo(VALUE x, VALUE y)
1242 double num = RFLOAT_VALUE(x);
1243 double den = RFLOAT_VALUE(y);
1244 double ret = double_div_double(num, den);
1245 return DBL2NUM(ret);
1249 * call-seq:
1250 * self / other -> numeric
1252 * Returns a new \Float which is the result of dividing +self+ by +other+:
1254 * f = 3.14
1255 * f / 2 # => 1.57
1256 * f / 2.0 # => 1.57
1257 * f / Rational(2, 1) # => 1.57
1258 * f / Complex(2, 0) # => (1.57+0.0i)
1262 VALUE
1263 rb_float_div(VALUE x, VALUE y)
1265 double num = RFLOAT_VALUE(x);
1266 double den;
1267 double ret;
1269 if (FIXNUM_P(y)) {
1270 den = FIX2LONG(y);
1272 else if (RB_BIGNUM_TYPE_P(y)) {
1273 den = rb_big2dbl(y);
1275 else if (RB_FLOAT_TYPE_P(y)) {
1276 den = RFLOAT_VALUE(y);
1278 else {
1279 return rb_num_coerce_bin(x, y, '/');
1282 ret = double_div_double(num, den);
1283 return DBL2NUM(ret);
1287 * call-seq:
1288 * quo(other) -> numeric
1290 * Returns the quotient from dividing +self+ by +other+:
1292 * f = 3.14
1293 * f.quo(2) # => 1.57
1294 * f.quo(-2) # => -1.57
1295 * f.quo(Rational(2, 1)) # => 1.57
1296 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1300 static VALUE
1301 flo_quo(VALUE x, VALUE y)
1303 return num_funcall1(x, '/', y);
1306 static void
1307 flodivmod(double x, double y, double *divp, double *modp)
1309 double div, mod;
1311 if (isnan(y)) {
1312 /* y is NaN so all results are NaN */
1313 if (modp) *modp = y;
1314 if (divp) *divp = y;
1315 return;
1317 if (y == 0.0) rb_num_zerodiv();
1318 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1319 mod = x;
1320 else {
1321 #ifdef HAVE_FMOD
1322 mod = fmod(x, y);
1323 #else
1324 double z;
1326 modf(x/y, &z);
1327 mod = x - z * y;
1328 #endif
1330 if (isinf(x) && !isinf(y))
1331 div = x;
1332 else {
1333 div = (x - mod) / y;
1334 if (modp && divp) div = round(div);
1336 if (y*mod < 0) {
1337 mod += y;
1338 div -= 1.0;
1340 if (modp) *modp = mod;
1341 if (divp) *divp = div;
1345 * Returns the modulo of division of x by y.
1346 * An error will be raised if y == 0.
1349 double
1350 ruby_float_mod(double x, double y)
1352 double mod;
1353 flodivmod(x, y, 0, &mod);
1354 return mod;
1358 * call-seq:
1359 * self % other -> float
1361 * Returns +self+ modulo +other+ as a float.
1363 * For float +f+ and real number +r+, these expressions are equivalent:
1365 * f % r
1366 * f-r*(f/r).floor
1367 * f.divmod(r)[1]
1369 * See Numeric#divmod.
1371 * Examples:
1373 * 10.0 % 2 # => 0.0
1374 * 10.0 % 3 # => 1.0
1375 * 10.0 % 4 # => 2.0
1377 * 10.0 % -2 # => 0.0
1378 * 10.0 % -3 # => -2.0
1379 * 10.0 % -4 # => -2.0
1381 * 10.0 % 4.0 # => 2.0
1382 * 10.0 % Rational(4, 1) # => 2.0
1386 static VALUE
1387 flo_mod(VALUE x, VALUE y)
1389 double fy;
1391 if (FIXNUM_P(y)) {
1392 fy = (double)FIX2LONG(y);
1394 else if (RB_BIGNUM_TYPE_P(y)) {
1395 fy = rb_big2dbl(y);
1397 else if (RB_FLOAT_TYPE_P(y)) {
1398 fy = RFLOAT_VALUE(y);
1400 else {
1401 return rb_num_coerce_bin(x, y, '%');
1403 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1406 static VALUE
1407 dbl2ival(double d)
1409 if (FIXABLE(d)) {
1410 return LONG2FIX((long)d);
1412 return rb_dbl2big(d);
1416 * call-seq:
1417 * divmod(other) -> array
1419 * Returns a 2-element array <tt>[q, r]</tt>, where
1421 * q = (self/other).floor # Quotient
1422 * r = self % other # Remainder
1424 * Examples:
1426 * 11.0.divmod(4) # => [2, 3.0]
1427 * 11.0.divmod(-4) # => [-3, -1.0]
1428 * -11.0.divmod(4) # => [-3, 1.0]
1429 * -11.0.divmod(-4) # => [2, -3.0]
1431 * 12.0.divmod(4) # => [3, 0.0]
1432 * 12.0.divmod(-4) # => [-3, 0.0]
1433 * -12.0.divmod(4) # => [-3, -0.0]
1434 * -12.0.divmod(-4) # => [3, -0.0]
1436 * 13.0.divmod(4.0) # => [3, 1.0]
1437 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1441 static VALUE
1442 flo_divmod(VALUE x, VALUE y)
1444 double fy, div, mod;
1445 volatile VALUE a, b;
1447 if (FIXNUM_P(y)) {
1448 fy = (double)FIX2LONG(y);
1450 else if (RB_BIGNUM_TYPE_P(y)) {
1451 fy = rb_big2dbl(y);
1453 else if (RB_FLOAT_TYPE_P(y)) {
1454 fy = RFLOAT_VALUE(y);
1456 else {
1457 return rb_num_coerce_bin(x, y, id_divmod);
1459 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1460 a = dbl2ival(div);
1461 b = DBL2NUM(mod);
1462 return rb_assoc_new(a, b);
1466 * call-seq:
1467 * self ** other -> numeric
1469 * Raises +self+ to the power of +other+:
1471 * f = 3.14
1472 * f ** 2 # => 9.8596
1473 * f ** -2 # => 0.1014239928597509
1474 * f ** 2.1 # => 11.054834900588839
1475 * f ** Rational(2, 1) # => 9.8596
1476 * f ** Complex(2, 0) # => (9.8596+0i)
1480 VALUE
1481 rb_float_pow(VALUE x, VALUE y)
1483 double dx, dy;
1484 if (y == INT2FIX(2)) {
1485 dx = RFLOAT_VALUE(x);
1486 return DBL2NUM(dx * dx);
1488 else if (FIXNUM_P(y)) {
1489 dx = RFLOAT_VALUE(x);
1490 dy = (double)FIX2LONG(y);
1492 else if (RB_BIGNUM_TYPE_P(y)) {
1493 dx = RFLOAT_VALUE(x);
1494 dy = rb_big2dbl(y);
1496 else if (RB_FLOAT_TYPE_P(y)) {
1497 dx = RFLOAT_VALUE(x);
1498 dy = RFLOAT_VALUE(y);
1499 if (dx < 0 && dy != round(dy))
1500 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1502 else {
1503 return rb_num_coerce_bin(x, y, idPow);
1505 return DBL2NUM(pow(dx, dy));
1509 * call-seq:
1510 * eql?(other) -> true or false
1512 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1514 * Of the Core and Standard Library classes,
1515 * only Integer, Rational, and Complex use this implementation.
1517 * Examples:
1519 * 1.eql?(1) # => true
1520 * 1.eql?(1.0) # => false
1521 * 1.eql?(Rational(1, 1)) # => false
1522 * 1.eql?(Complex(1, 0)) # => false
1524 * \Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1525 * while <tt>==</tt> does not.
1529 static VALUE
1530 num_eql(VALUE x, VALUE y)
1532 if (TYPE(x) != TYPE(y)) return Qfalse;
1534 if (RB_BIGNUM_TYPE_P(x)) {
1535 return rb_big_eql(x, y);
1538 return rb_equal(x, y);
1542 * call-seq:
1543 * self <=> other -> zero or nil
1545 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1547 * No subclass in the Ruby Core or Standard Library uses this implementation.
1551 static VALUE
1552 num_cmp(VALUE x, VALUE y)
1554 if (x == y) return INT2FIX(0);
1555 return Qnil;
1558 static VALUE
1559 num_equal(VALUE x, VALUE y)
1561 VALUE result;
1562 if (x == y) return Qtrue;
1563 result = num_funcall1(y, id_eq, x);
1564 return RBOOL(RTEST(result));
1568 * call-seq:
1569 * self == other -> true or false
1571 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1573 * 2.0 == 2 # => true
1574 * 2.0 == 2.0 # => true
1575 * 2.0 == Rational(2, 1) # => true
1576 * 2.0 == Complex(2, 0) # => true
1578 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1580 * Related: Float#eql? (requires +other+ to be a \Float).
1584 VALUE
1585 rb_float_equal(VALUE x, VALUE y)
1587 volatile double a, b;
1589 if (RB_INTEGER_TYPE_P(y)) {
1590 return rb_integer_float_eq(y, x);
1592 else if (RB_FLOAT_TYPE_P(y)) {
1593 b = RFLOAT_VALUE(y);
1594 #if MSC_VERSION_BEFORE(1300)
1595 if (isnan(b)) return Qfalse;
1596 #endif
1598 else {
1599 return num_equal(x, y);
1601 a = RFLOAT_VALUE(x);
1602 #if MSC_VERSION_BEFORE(1300)
1603 if (isnan(a)) return Qfalse;
1604 #endif
1605 return RBOOL(a == b);
1608 #define flo_eq rb_float_equal
1609 static VALUE rb_dbl_hash(double d);
1612 * call-seq:
1613 * hash -> integer
1615 * Returns the integer hash value for +self+.
1617 * See also Object#hash.
1620 static VALUE
1621 flo_hash(VALUE num)
1623 return rb_dbl_hash(RFLOAT_VALUE(num));
1626 static VALUE
1627 rb_dbl_hash(double d)
1629 return ST2FIX(rb_dbl_long_hash(d));
1632 VALUE
1633 rb_dbl_cmp(double a, double b)
1635 if (isnan(a) || isnan(b)) return Qnil;
1636 if (a == b) return INT2FIX(0);
1637 if (a > b) return INT2FIX(1);
1638 if (a < b) return INT2FIX(-1);
1639 return Qnil;
1643 * call-seq:
1644 * self <=> other -> -1, 0, +1, or nil
1646 * Returns a value that depends on the numeric relation
1647 * between +self+ and +other+:
1649 * - -1, if +self+ is less than +other+.
1650 * - 0, if +self+ is equal to +other+.
1651 * - 1, if +self+ is greater than +other+.
1652 * - +nil+, if the two values are incommensurate.
1654 * Examples:
1656 * 2.0 <=> 2 # => 0
1657 * 2.0 <=> 2.0 # => 0
1658 * 2.0 <=> Rational(2, 1) # => 0
1659 * 2.0 <=> Complex(2, 0) # => 0
1660 * 2.0 <=> 1.9 # => 1
1661 * 2.0 <=> 2.1 # => -1
1662 * 2.0 <=> 'foo' # => nil
1664 * This is the basis for the tests in the Comparable module.
1666 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1670 static VALUE
1671 flo_cmp(VALUE x, VALUE y)
1673 double a, b;
1674 VALUE i;
1676 a = RFLOAT_VALUE(x);
1677 if (isnan(a)) return Qnil;
1678 if (RB_INTEGER_TYPE_P(y)) {
1679 VALUE rel = rb_integer_float_cmp(y, x);
1680 if (FIXNUM_P(rel))
1681 return LONG2FIX(-FIX2LONG(rel));
1682 return rel;
1684 else if (RB_FLOAT_TYPE_P(y)) {
1685 b = RFLOAT_VALUE(y);
1687 else {
1688 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1689 if (RTEST(i)) {
1690 int j = rb_cmpint(i, x, y);
1691 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1692 return INT2FIX(j);
1694 if (a > 0.0) return INT2FIX(1);
1695 return INT2FIX(-1);
1697 return rb_num_coerce_cmp(x, y, id_cmp);
1699 return rb_dbl_cmp(a, b);
1703 rb_float_cmp(VALUE x, VALUE y)
1705 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1709 * call-seq:
1710 * self > other -> true or false
1712 * Returns +true+ if +self+ is numerically greater than +other+:
1714 * 2.0 > 1 # => true
1715 * 2.0 > 1.0 # => true
1716 * 2.0 > Rational(1, 2) # => true
1717 * 2.0 > 2.0 # => false
1719 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1723 VALUE
1724 rb_float_gt(VALUE x, VALUE y)
1726 double a, b;
1728 a = RFLOAT_VALUE(x);
1729 if (RB_INTEGER_TYPE_P(y)) {
1730 VALUE rel = rb_integer_float_cmp(y, x);
1731 if (FIXNUM_P(rel))
1732 return RBOOL(-FIX2LONG(rel) > 0);
1733 return Qfalse;
1735 else if (RB_FLOAT_TYPE_P(y)) {
1736 b = RFLOAT_VALUE(y);
1737 #if MSC_VERSION_BEFORE(1300)
1738 if (isnan(b)) return Qfalse;
1739 #endif
1741 else {
1742 return rb_num_coerce_relop(x, y, '>');
1744 #if MSC_VERSION_BEFORE(1300)
1745 if (isnan(a)) return Qfalse;
1746 #endif
1747 return RBOOL(a > b);
1751 * call-seq:
1752 * self >= other -> true or false
1754 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1756 * 2.0 >= 1 # => true
1757 * 2.0 >= 1.0 # => true
1758 * 2.0 >= Rational(1, 2) # => true
1759 * 2.0 >= 2.0 # => true
1760 * 2.0 >= 2.1 # => false
1762 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1766 static VALUE
1767 flo_ge(VALUE x, VALUE y)
1769 double a, b;
1771 a = RFLOAT_VALUE(x);
1772 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1773 VALUE rel = rb_integer_float_cmp(y, x);
1774 if (FIXNUM_P(rel))
1775 return RBOOL(-FIX2LONG(rel) >= 0);
1776 return Qfalse;
1778 else if (RB_FLOAT_TYPE_P(y)) {
1779 b = RFLOAT_VALUE(y);
1780 #if MSC_VERSION_BEFORE(1300)
1781 if (isnan(b)) return Qfalse;
1782 #endif
1784 else {
1785 return rb_num_coerce_relop(x, y, idGE);
1787 #if MSC_VERSION_BEFORE(1300)
1788 if (isnan(a)) return Qfalse;
1789 #endif
1790 return RBOOL(a >= b);
1794 * call-seq:
1795 * self < other -> true or false
1797 * Returns +true+ if +self+ is numerically less than +other+:
1799 * 2.0 < 3 # => true
1800 * 2.0 < 3.0 # => true
1801 * 2.0 < Rational(3, 1) # => true
1802 * 2.0 < 2.0 # => false
1804 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1808 static VALUE
1809 flo_lt(VALUE x, VALUE y)
1811 double a, b;
1813 a = RFLOAT_VALUE(x);
1814 if (RB_INTEGER_TYPE_P(y)) {
1815 VALUE rel = rb_integer_float_cmp(y, x);
1816 if (FIXNUM_P(rel))
1817 return RBOOL(-FIX2LONG(rel) < 0);
1818 return Qfalse;
1820 else if (RB_FLOAT_TYPE_P(y)) {
1821 b = RFLOAT_VALUE(y);
1822 #if MSC_VERSION_BEFORE(1300)
1823 if (isnan(b)) return Qfalse;
1824 #endif
1826 else {
1827 return rb_num_coerce_relop(x, y, '<');
1829 #if MSC_VERSION_BEFORE(1300)
1830 if (isnan(a)) return Qfalse;
1831 #endif
1832 return RBOOL(a < b);
1836 * call-seq:
1837 * self <= other -> true or false
1839 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1841 * 2.0 <= 3 # => true
1842 * 2.0 <= 3.0 # => true
1843 * 2.0 <= Rational(3, 1) # => true
1844 * 2.0 <= 2.0 # => true
1845 * 2.0 <= 1.0 # => false
1847 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1851 static VALUE
1852 flo_le(VALUE x, VALUE y)
1854 double a, b;
1856 a = RFLOAT_VALUE(x);
1857 if (RB_INTEGER_TYPE_P(y)) {
1858 VALUE rel = rb_integer_float_cmp(y, x);
1859 if (FIXNUM_P(rel))
1860 return RBOOL(-FIX2LONG(rel) <= 0);
1861 return Qfalse;
1863 else if (RB_FLOAT_TYPE_P(y)) {
1864 b = RFLOAT_VALUE(y);
1865 #if MSC_VERSION_BEFORE(1300)
1866 if (isnan(b)) return Qfalse;
1867 #endif
1869 else {
1870 return rb_num_coerce_relop(x, y, idLE);
1872 #if MSC_VERSION_BEFORE(1300)
1873 if (isnan(a)) return Qfalse;
1874 #endif
1875 return RBOOL(a <= b);
1879 * call-seq:
1880 * eql?(other) -> true or false
1882 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1883 * +false+ otherwise:
1885 * 2.0.eql?(2.0) # => true
1886 * 2.0.eql?(1.0) # => false
1887 * 2.0.eql?(1) # => false
1888 * 2.0.eql?(Rational(2, 1)) # => false
1889 * 2.0.eql?(Complex(2, 0)) # => false
1891 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1893 * Related: Float#== (performs type conversions).
1896 VALUE
1897 rb_float_eql(VALUE x, VALUE y)
1899 if (RB_FLOAT_TYPE_P(y)) {
1900 double a = RFLOAT_VALUE(x);
1901 double b = RFLOAT_VALUE(y);
1902 #if MSC_VERSION_BEFORE(1300)
1903 if (isnan(a) || isnan(b)) return Qfalse;
1904 #endif
1905 return RBOOL(a == b);
1907 return Qfalse;
1910 #define flo_eql rb_float_eql
1912 VALUE
1913 rb_float_abs(VALUE flt)
1915 double val = fabs(RFLOAT_VALUE(flt));
1916 return DBL2NUM(val);
1920 * call-seq:
1921 * nan? -> true or false
1923 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1925 * f = -1.0 #=> -1.0
1926 * f.nan? #=> false
1927 * f = 0.0/0.0 #=> NaN
1928 * f.nan? #=> true
1931 static VALUE
1932 flo_is_nan_p(VALUE num)
1934 double value = RFLOAT_VALUE(num);
1936 return RBOOL(isnan(value));
1940 * call-seq:
1941 * infinite? -> -1, 1, or nil
1943 * Returns:
1945 * - 1, if +self+ is <tt>Infinity</tt>.
1946 * - -1 if +self+ is <tt>-Infinity</tt>.
1947 * - +nil+, otherwise.
1949 * Examples:
1951 * f = 1.0/0.0 # => Infinity
1952 * f.infinite? # => 1
1953 * f = -1.0/0.0 # => -Infinity
1954 * f.infinite? # => -1
1955 * f = 1.0 # => 1.0
1956 * f.infinite? # => nil
1957 * f = 0.0/0.0 # => NaN
1958 * f.infinite? # => nil
1962 VALUE
1963 rb_flo_is_infinite_p(VALUE num)
1965 double value = RFLOAT_VALUE(num);
1967 if (isinf(value)) {
1968 return INT2FIX( value < 0 ? -1 : 1 );
1971 return Qnil;
1975 * call-seq:
1976 * finite? -> true or false
1978 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1979 * +false+ otherwise:
1981 * f = 2.0 # => 2.0
1982 * f.finite? # => true
1983 * f = 1.0/0.0 # => Infinity
1984 * f.finite? # => false
1985 * f = -1.0/0.0 # => -Infinity
1986 * f.finite? # => false
1987 * f = 0.0/0.0 # => NaN
1988 * f.finite? # => false
1992 VALUE
1993 rb_flo_is_finite_p(VALUE num)
1995 double value = RFLOAT_VALUE(num);
1997 return RBOOL(isfinite(value));
2000 static VALUE
2001 flo_nextafter(VALUE flo, double value)
2003 double x, y;
2004 x = NUM2DBL(flo);
2005 y = nextafter(x, value);
2006 return DBL2NUM(y);
2010 * call-seq:
2011 * next_float -> float
2013 * Returns the next-larger representable \Float.
2015 * These examples show the internally stored values (64-bit hexadecimal)
2016 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2018 * f = 0.0 # 0x0000000000000000
2019 * f.next_float # 0x0000000000000001
2021 * f = 0.01 # 0x3f847ae147ae147b
2022 * f.next_float # 0x3f847ae147ae147c
2024 * In the remaining examples here, the output is shown in the usual way
2025 * (result +to_s+):
2027 * 0.01.next_float # => 0.010000000000000002
2028 * 1.0.next_float # => 1.0000000000000002
2029 * 100.0.next_float # => 100.00000000000001
2031 * f = 0.01
2032 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2034 * Output:
2036 * 0 0x1.47ae147ae147bp-7 0.01
2037 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2038 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2039 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2041 * f = 0.0; 100.times { f += 0.1 }
2042 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2043 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2044 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2045 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2046 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2047 * "%a" % 10 # => "0x1.4p+3"
2048 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2050 * Related: Float#prev_float
2053 static VALUE
2054 flo_next_float(VALUE vx)
2056 return flo_nextafter(vx, HUGE_VAL);
2060 * call-seq:
2061 * float.prev_float -> float
2063 * Returns the next-smaller representable \Float.
2065 * These examples show the internally stored values (64-bit hexadecimal)
2066 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2068 * f = 5e-324 # 0x0000000000000001
2069 * f.prev_float # 0x0000000000000000
2071 * f = 0.01 # 0x3f847ae147ae147b
2072 * f.prev_float # 0x3f847ae147ae147a
2074 * In the remaining examples here, the output is shown in the usual way
2075 * (result +to_s+):
2077 * 0.01.prev_float # => 0.009999999999999998
2078 * 1.0.prev_float # => 0.9999999999999999
2079 * 100.0.prev_float # => 99.99999999999999
2081 * f = 0.01
2082 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2084 * Output:
2086 * 0 0x1.47ae147ae147bp-7 0.01
2087 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2088 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2089 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2091 * Related: Float#next_float.
2094 static VALUE
2095 flo_prev_float(VALUE vx)
2097 return flo_nextafter(vx, -HUGE_VAL);
2100 VALUE
2101 rb_float_floor(VALUE num, int ndigits)
2103 double number;
2104 number = RFLOAT_VALUE(num);
2105 if (number == 0.0) {
2106 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2108 if (ndigits > 0) {
2109 int binexp;
2110 double f, mul, res;
2111 frexp(number, &binexp);
2112 if (float_round_overflow(ndigits, binexp)) return num;
2113 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2114 return DBL2NUM(0.0);
2115 f = pow(10, ndigits);
2116 mul = floor(number * f);
2117 res = (mul + 1) / f;
2118 if (res > number)
2119 res = mul / f;
2120 return DBL2NUM(res);
2122 else {
2123 num = dbl2ival(floor(number));
2124 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2125 return num;
2129 static int
2130 flo_ndigits(int argc, VALUE *argv)
2132 if (rb_check_arity(argc, 0, 1)) {
2133 return NUM2INT(argv[0]);
2135 return 0;
2139 * :markup: markdown
2141 * call-seq:
2142 * floor(ndigits = 0) -> float or integer
2144 * Returns a float or integer that is a "floor" value for `self`,
2145 * as specified by `ndigits`,
2146 * which must be an
2147 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2149 * When `self` is zero,
2150 * returns a zero value:
2151 * a float if `ndigits` is positive,
2152 * an integer otherwise:
2154 * ```
2155 * f = 0.0 # => 0.0
2156 * f.floor(20) # => 0.0
2157 * f.floor(0) # => 0
2158 * f.floor(-20) # => 0
2159 * ```
2161 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2162 * digits after the decimal point (as available):
2164 * ```
2165 * f = 12345.6789
2166 * f.floor(1) # => 12345.6
2167 * f.floor(3) # => 12345.678
2168 * f.floor(30) # => 12345.6789
2169 * f = -12345.6789
2170 * f.floor(1) # => -12345.7
2171 * f.floor(3) # => -12345.679
2172 * f.floor(30) # => -12345.6789
2173 * ```
2175 * When `self` is non-zero and `ndigits` is non-positive,
2176 * returns an integer value based on a computed granularity:
2178 * - The granularity is `10 ** ndigits.abs`.
2179 * - The returned value is the largest multiple of the granularity
2180 * that is less than or equal to `self`.
2182 * Examples with positive `self`:
2184 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2185 * |--------:|------------:|--------------------------:|
2186 * | 0 | 1 | 12345 |
2187 * | -1 | 10 | 12340 |
2188 * | -2 | 100 | 12300 |
2189 * | -3 | 1000 | 12000 |
2190 * | -4 | 10000 | 10000 |
2191 * | -5 | 100000 | 0 |
2193 * Examples with negative `self`:
2195 * | ndigits | Granularity | -12345.6789.floor(ndigits) |
2196 * |--------:|------------:|---------------------------:|
2197 * | 0 | 1 | -12346 |
2198 * | -1 | 10 | -12350 |
2199 * | -2 | 100 | -12400 |
2200 * | -3 | 1000 | -13000 |
2201 * | -4 | 10000 | -20000 |
2202 * | -5 | 100000 | -100000 |
2203 * | -6 | 1000000 | -1000000 |
2205 * Note that the limited precision of floating-point arithmetic
2206 * may lead to surprising results:
2208 * ```
2209 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2210 * ```
2212 * Related: Float#ceil.
2216 static VALUE
2217 flo_floor(int argc, VALUE *argv, VALUE num)
2219 int ndigits = flo_ndigits(argc, argv);
2220 return rb_float_floor(num, ndigits);
2224 * :markup: markdown
2226 * call-seq:
2227 * ceil(ndigits = 0) -> float or integer
2229 * Returns a numeric that is a "ceiling" value for `self`,
2230 * as specified by the given `ndigits`,
2231 * which must be an
2232 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2234 * When `ndigits` is positive, returns a Float with `ndigits`
2235 * decimal digits after the decimal point
2236 * (as available, but no fewer than 1):
2238 * ```
2239 * f = 12345.6789
2240 * f.ceil(1) # => 12345.7
2241 * f.ceil(3) # => 12345.679
2242 * f.ceil(30) # => 12345.6789
2243 * f = -12345.6789
2244 * f.ceil(1) # => -12345.6
2245 * f.ceil(3) # => -12345.678
2246 * f.ceil(30) # => -12345.6789
2247 * f = 0.0
2248 * f.ceil(1) # => 0.0
2249 * f.ceil(100) # => 0.0
2250 * ```
2252 * When `ndigits` is non-positive,
2253 * returns an Integer based on a computed granularity:
2255 * - The granularity is `10 ** ndigits.abs`.
2256 * - The returned value is the largest multiple of the granularity
2257 * that is less than or equal to `self`.
2259 * Examples with positive `self`:
2261 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2262 * |--------:|------------:|-------------------------:|
2263 * | 0 | 1 | 12346 |
2264 * | -1 | 10 | 12350 |
2265 * | -2 | 100 | 12400 |
2266 * | -3 | 1000 | 13000 |
2267 * | -4 | 10000 | 20000 |
2268 * | -5 | 100000 | 100000 |
2270 * Examples with negative `self`:
2272 * | ndigits | Granularity | -12345.6789.ceil(ndigits) |
2273 * |--------:|------------:|--------------------------:|
2274 * | 0 | 1 | -12345 |
2275 * | -1 | 10 | -12340 |
2276 * | -2 | 100 | -12300 |
2277 * | -3 | 1000 | -12000 |
2278 * | -4 | 10000 | -10000 |
2279 * | -5 | 100000 | 0 |
2281 * When `self` is zero and `ndigits` is non-positive,
2282 * returns Integer zero:
2284 * ```
2285 * 0.0.ceil(0) # => 0
2286 * 0.0.ceil(-1) # => 0
2287 * 0.0.ceil(-2) # => 0
2288 * ```
2290 * Note that the limited precision of floating-point arithmetic
2291 * may lead to surprising results:
2293 * ```
2294 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2295 * ```
2297 * Related: Float#floor.
2301 static VALUE
2302 flo_ceil(int argc, VALUE *argv, VALUE num)
2304 int ndigits = flo_ndigits(argc, argv);
2305 return rb_float_ceil(num, ndigits);
2308 VALUE
2309 rb_float_ceil(VALUE num, int ndigits)
2311 double number, f;
2313 number = RFLOAT_VALUE(num);
2314 if (number == 0.0) {
2315 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2317 if (ndigits > 0) {
2318 int binexp;
2319 frexp(number, &binexp);
2320 if (float_round_overflow(ndigits, binexp)) return num;
2321 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2322 return DBL2NUM(0.0);
2323 f = pow(10, ndigits);
2324 f = ceil(number * f) / f;
2325 return DBL2NUM(f);
2327 else {
2328 num = dbl2ival(ceil(number));
2329 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2330 return num;
2334 static int
2335 int_round_zero_p(VALUE num, int ndigits)
2337 long bytes;
2338 /* If 10**N / 2 > num, then return 0 */
2339 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2340 if (FIXNUM_P(num)) {
2341 bytes = sizeof(long);
2343 else if (RB_BIGNUM_TYPE_P(num)) {
2344 bytes = rb_big_size(num);
2346 else {
2347 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2349 return (-0.415241 * ndigits - 0.125 > bytes);
2352 static SIGNED_VALUE
2353 int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2355 SIGNED_VALUE z = +(x + y / 2) / y;
2356 if ((z * y - x) * 2 == y) {
2357 z &= ~1;
2359 return z * y;
2362 static SIGNED_VALUE
2363 int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2365 return (x + y / 2) / y * y;
2368 static SIGNED_VALUE
2369 int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2371 return (x + y / 2 - 1) / y * y;
2374 static int
2375 int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2377 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2380 static int
2381 int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2383 return int_pos_p(num);
2386 static int
2387 int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2389 return int_neg_p(num);
2393 * Assumes num is an \Integer, ndigits <= 0
2395 static VALUE
2396 rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2398 VALUE n, f, h, r;
2400 if (int_round_zero_p(num, ndigits)) {
2401 return INT2FIX(0);
2404 f = int_pow(10, -ndigits);
2405 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2406 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2407 int neg = x < 0;
2408 if (neg) x = -x;
2409 x = ROUND_CALL(mode, int_round, (x, y));
2410 if (neg) x = -x;
2411 return LONG2NUM(x);
2413 if (RB_FLOAT_TYPE_P(f)) {
2414 /* then int_pow overflow */
2415 return INT2FIX(0);
2417 h = rb_int_idiv(f, INT2FIX(2));
2418 r = rb_int_modulo(num, f);
2419 n = rb_int_minus(num, r);
2420 r = rb_int_cmp(r, h);
2421 if (FIXNUM_POSITIVE_P(r) ||
2422 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2423 n = rb_int_plus(n, f);
2425 return n;
2428 static VALUE
2429 rb_int_floor(VALUE num, int ndigits)
2431 VALUE f = int_pow(10, -ndigits);
2432 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2433 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2434 int neg = x < 0;
2435 if (neg) x = -x + y - 1;
2436 x = x / y * y;
2437 if (neg) x = -x;
2438 return LONG2NUM(x);
2440 else {
2441 bool neg = int_neg_p(num);
2442 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2443 num = rb_int_mul(rb_int_div(num, f), f);
2444 if (neg) num = rb_int_uminus(num);
2445 return num;
2449 static VALUE
2450 rb_int_ceil(VALUE num, int ndigits)
2452 VALUE f = int_pow(10, -ndigits);
2453 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2454 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2455 int neg = x < 0;
2456 if (neg) x = -x;
2457 else x += y - 1;
2458 x = (x / y) * y;
2459 if (neg) x = -x;
2460 return LONG2NUM(x);
2462 else {
2463 bool neg = int_neg_p(num);
2464 if (neg)
2465 num = rb_int_uminus(num);
2466 else
2467 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2468 num = rb_int_mul(rb_int_div(num, f), f);
2469 if (neg) num = rb_int_uminus(num);
2470 return num;
2474 VALUE
2475 rb_int_truncate(VALUE num, int ndigits)
2477 VALUE f;
2478 VALUE m;
2480 if (int_round_zero_p(num, ndigits))
2481 return INT2FIX(0);
2482 f = int_pow(10, -ndigits);
2483 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2484 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2485 int neg = x < 0;
2486 if (neg) x = -x;
2487 x = x / y * y;
2488 if (neg) x = -x;
2489 return LONG2NUM(x);
2491 if (RB_FLOAT_TYPE_P(f)) {
2492 /* then int_pow overflow */
2493 return INT2FIX(0);
2495 m = rb_int_modulo(num, f);
2496 if (int_neg_p(num)) {
2497 return rb_int_plus(num, rb_int_minus(f, m));
2499 else {
2500 return rb_int_minus(num, m);
2505 * call-seq:
2506 * round(ndigits = 0, half: :up) -> integer or float
2508 * Returns +self+ rounded to the nearest value with
2509 * a precision of +ndigits+ decimal digits.
2511 * When +ndigits+ is non-negative, returns a float with +ndigits+
2512 * after the decimal point (as available):
2514 * f = 12345.6789
2515 * f.round(1) # => 12345.7
2516 * f.round(3) # => 12345.679
2517 * f = -12345.6789
2518 * f.round(1) # => -12345.7
2519 * f.round(3) # => -12345.679
2521 * When +ndigits+ is negative, returns an integer
2522 * with at least <tt>ndigits.abs</tt> trailing zeros:
2524 * f = 12345.6789
2525 * f.round(0) # => 12346
2526 * f.round(-3) # => 12000
2527 * f = -12345.6789
2528 * f.round(0) # => -12346
2529 * f.round(-3) # => -12000
2531 * If keyword argument +half+ is given,
2532 * and +self+ is equidistant from the two candidate values,
2533 * the rounding is according to the given +half+ value:
2535 * - +:up+ or +nil+: round away from zero:
2537 * 2.5.round(half: :up) # => 3
2538 * 3.5.round(half: :up) # => 4
2539 * (-2.5).round(half: :up) # => -3
2541 * - +:down+: round toward zero:
2543 * 2.5.round(half: :down) # => 2
2544 * 3.5.round(half: :down) # => 3
2545 * (-2.5).round(half: :down) # => -2
2547 * - +:even+: round toward the candidate whose last nonzero digit is even:
2549 * 2.5.round(half: :even) # => 2
2550 * 3.5.round(half: :even) # => 4
2551 * (-2.5).round(half: :even) # => -2
2553 * Raises and exception if the value for +half+ is invalid.
2555 * Related: Float#truncate.
2559 static VALUE
2560 flo_round(int argc, VALUE *argv, VALUE num)
2562 double number, f, x;
2563 VALUE nd, opt;
2564 int ndigits = 0;
2565 enum ruby_num_rounding_mode mode;
2567 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2568 ndigits = NUM2INT(nd);
2570 mode = rb_num_get_rounding_option(opt);
2571 number = RFLOAT_VALUE(num);
2572 if (number == 0.0) {
2573 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2575 if (ndigits < 0) {
2576 return rb_int_round(flo_to_i(num), ndigits, mode);
2578 if (ndigits == 0) {
2579 x = ROUND_CALL(mode, round, (number, 1.0));
2580 return dbl2ival(x);
2582 if (isfinite(number)) {
2583 int binexp;
2584 frexp(number, &binexp);
2585 if (float_round_overflow(ndigits, binexp)) return num;
2586 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2587 if (ndigits > 14) {
2588 /* In this case, pow(10, ndigits) may not be accurate. */
2589 return rb_flo_round_by_rational(argc, argv, num);
2591 f = pow(10, ndigits);
2592 x = ROUND_CALL(mode, round, (number, f));
2593 return DBL2NUM(x / f);
2595 return num;
2598 static int
2599 float_round_overflow(int ndigits, int binexp)
2601 enum {float_dig = DBL_DIG+2};
2603 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2604 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2605 Recall that up to float_dig digits can be needed to represent a double,
2606 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2607 will be an integer and thus the result is the original number.
2608 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2609 if ndigits + exp < 0, the result is 0.
2610 We have:
2611 2 ** (binexp-1) <= |number| < 2 ** binexp
2612 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2613 If binexp >= 0, and since log_2(10) = 3.322259:
2614 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2615 floor(binexp/4) <= exp <= ceil(binexp/3)
2616 If binexp <= 0, swap the /4 and the /3
2617 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2618 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2620 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2621 return TRUE;
2623 return FALSE;
2626 static int
2627 float_round_underflow(int ndigits, int binexp)
2629 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2630 return TRUE;
2632 return FALSE;
2636 * call-seq:
2637 * to_i -> integer
2639 * Returns +self+ truncated to an Integer.
2641 * 1.2.to_i # => 1
2642 * (-1.2).to_i # => -1
2644 * Note that the limited precision of floating-point arithmetic
2645 * may lead to surprising results:
2647 * (0.3 / 0.1).to_i # => 2 (!)
2651 static VALUE
2652 flo_to_i(VALUE num)
2654 double f = RFLOAT_VALUE(num);
2656 if (f > 0.0) f = floor(f);
2657 if (f < 0.0) f = ceil(f);
2659 return dbl2ival(f);
2663 * call-seq:
2664 * truncate(ndigits = 0) -> float or integer
2666 * Returns +self+ truncated (toward zero) to
2667 * a precision of +ndigits+ decimal digits.
2669 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2670 * after the decimal point (as available):
2672 * f = 12345.6789
2673 * f.truncate(1) # => 12345.6
2674 * f.truncate(3) # => 12345.678
2675 * f = -12345.6789
2676 * f.truncate(1) # => -12345.6
2677 * f.truncate(3) # => -12345.678
2679 * When +ndigits+ is negative, returns an integer
2680 * with at least <tt>ndigits.abs</tt> trailing zeros:
2682 * f = 12345.6789
2683 * f.truncate(0) # => 12345
2684 * f.truncate(-3) # => 12000
2685 * f = -12345.6789
2686 * f.truncate(0) # => -12345
2687 * f.truncate(-3) # => -12000
2689 * Note that the limited precision of floating-point arithmetic
2690 * may lead to surprising results:
2692 * (0.3 / 0.1).truncate #=> 2 (!)
2694 * Related: Float#round.
2697 static VALUE
2698 flo_truncate(int argc, VALUE *argv, VALUE num)
2700 if (signbit(RFLOAT_VALUE(num)))
2701 return flo_ceil(argc, argv, num);
2702 else
2703 return flo_floor(argc, argv, num);
2707 * call-seq:
2708 * floor(ndigits = 0) -> float or integer
2710 * Returns the largest float or integer that is less than or equal to +self+,
2711 * as specified by the given `ndigits`,
2712 * which must be an
2713 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2715 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2717 * Related: #ceil, Float#floor.
2720 static VALUE
2721 num_floor(int argc, VALUE *argv, VALUE num)
2723 return flo_floor(argc, argv, rb_Float(num));
2727 * call-seq:
2728 * ceil(ndigits = 0) -> float or integer
2730 * Returns the smallest float or integer that is greater than or equal to +self+,
2731 * as specified by the given `ndigits`,
2732 * which must be an
2733 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2735 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2737 * Related: #floor, Float#ceil.
2740 static VALUE
2741 num_ceil(int argc, VALUE *argv, VALUE num)
2743 return flo_ceil(argc, argv, rb_Float(num));
2747 * call-seq:
2748 * round(digits = 0) -> integer or float
2750 * Returns +self+ rounded to the nearest value with
2751 * a precision of +digits+ decimal digits.
2753 * \Numeric implements this by converting +self+ to a Float and
2754 * invoking Float#round.
2757 static VALUE
2758 num_round(int argc, VALUE* argv, VALUE num)
2760 return flo_round(argc, argv, rb_Float(num));
2764 * call-seq:
2765 * truncate(digits = 0) -> integer or float
2767 * Returns +self+ truncated (toward zero) to
2768 * a precision of +digits+ decimal digits.
2770 * \Numeric implements this by converting +self+ to a Float and
2771 * invoking Float#truncate.
2774 static VALUE
2775 num_truncate(int argc, VALUE *argv, VALUE num)
2777 return flo_truncate(argc, argv, rb_Float(num));
2780 double
2781 ruby_float_step_size(double beg, double end, double unit, int excl)
2783 const double epsilon = DBL_EPSILON;
2784 double d, n, err;
2786 if (unit == 0) {
2787 return HUGE_VAL;
2789 if (isinf(unit)) {
2790 return unit > 0 ? beg <= end : beg >= end;
2792 n= (end - beg)/unit;
2793 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2794 if (err>0.5) err=0.5;
2795 if (excl) {
2796 if (n<=0) return 0;
2797 if (n<1)
2798 n = 0;
2799 else
2800 n = floor(n - err);
2801 d = +((n + 1) * unit) + beg;
2802 if (beg < end) {
2803 if (d < end)
2804 n++;
2806 else if (beg > end) {
2807 if (d > end)
2808 n++;
2811 else {
2812 if (n<0) return 0;
2813 n = floor(n + err);
2814 d = +((n + 1) * unit) + beg;
2815 if (beg < end) {
2816 if (d <= end)
2817 n++;
2819 else if (beg > end) {
2820 if (d >= end)
2821 n++;
2824 return n+1;
2828 ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2830 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2831 double unit = NUM2DBL(step);
2832 double beg = NUM2DBL(from);
2833 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2834 double n = ruby_float_step_size(beg, end, unit, excl);
2835 long i;
2837 if (isinf(unit)) {
2838 /* if unit is infinity, i*unit+beg is NaN */
2839 if (n) rb_yield(DBL2NUM(beg));
2841 else if (unit == 0) {
2842 VALUE val = DBL2NUM(beg);
2843 for (;;)
2844 rb_yield(val);
2846 else {
2847 for (i=0; i<n; i++) {
2848 double d = i*unit+beg;
2849 if (unit >= 0 ? end < d : d < end) d = end;
2850 rb_yield(DBL2NUM(d));
2853 return TRUE;
2855 return FALSE;
2858 VALUE
2859 ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2861 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2862 long delta, diff;
2864 diff = FIX2LONG(step);
2865 if (diff == 0) {
2866 return DBL2NUM(HUGE_VAL);
2868 delta = FIX2LONG(to) - FIX2LONG(from);
2869 if (diff < 0) {
2870 diff = -diff;
2871 delta = -delta;
2873 if (excl) {
2874 delta--;
2876 if (delta < 0) {
2877 return INT2FIX(0);
2879 return ULONG2NUM(delta / diff + 1UL);
2881 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2882 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2884 if (isinf(n)) return DBL2NUM(n);
2885 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2886 return rb_dbl2big(n);
2888 else {
2889 VALUE result;
2890 ID cmp = '>';
2891 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2892 case 0: return DBL2NUM(HUGE_VAL);
2893 case -1: cmp = '<'; break;
2895 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2896 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2897 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2898 result = rb_funcall(result, '+', 1, INT2FIX(1));
2900 return result;
2904 static int
2905 num_step_negative_p(VALUE num)
2907 const ID mid = '<';
2908 VALUE zero = INT2FIX(0);
2909 VALUE r;
2911 if (FIXNUM_P(num)) {
2912 if (method_basic_p(rb_cInteger))
2913 return (SIGNED_VALUE)num < 0;
2915 else if (RB_BIGNUM_TYPE_P(num)) {
2916 if (method_basic_p(rb_cInteger))
2917 return BIGNUM_NEGATIVE_P(num);
2920 r = rb_check_funcall(num, '>', 1, &zero);
2921 if (UNDEF_P(r)) {
2922 coerce_failed(num, INT2FIX(0));
2924 return !RTEST(r);
2927 static int
2928 num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2930 VALUE hash;
2932 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2933 if (!NIL_P(hash)) {
2934 ID keys[2];
2935 VALUE values[2];
2936 keys[0] = id_to;
2937 keys[1] = id_by;
2938 rb_get_kwargs(hash, keys, 0, 2, values);
2939 if (!UNDEF_P(values[0])) {
2940 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2941 *to = values[0];
2943 if (!UNDEF_P(values[1])) {
2944 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2945 *by = values[1];
2949 return argc;
2952 static int
2953 num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2955 int desc;
2956 if (!UNDEF_P(by)) {
2957 *step = by;
2959 else {
2960 /* compatibility */
2961 if (argc > 1 && NIL_P(*step)) {
2962 rb_raise(rb_eTypeError, "step must be numeric");
2965 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2966 rb_raise(rb_eArgError, "step can't be 0");
2968 if (NIL_P(*step)) {
2969 *step = INT2FIX(1);
2971 desc = num_step_negative_p(*step);
2972 if (fix_nil && NIL_P(*to)) {
2973 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2975 return desc;
2978 static int
2979 num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2981 VALUE by = Qundef;
2982 argc = num_step_extract_args(argc, argv, to, step, &by);
2983 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2986 static VALUE
2987 num_step_size(VALUE from, VALUE args, VALUE eobj)
2989 VALUE to, step;
2990 int argc = args ? RARRAY_LENINT(args) : 0;
2991 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2993 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2995 return ruby_num_interval_step_size(from, to, step, FALSE);
2999 * call-seq:
3000 * step(to = nil, by = 1) {|n| ... } -> self
3001 * step(to = nil, by = 1) -> enumerator
3002 * step(to = nil, by: 1) {|n| ... } -> self
3003 * step(to = nil, by: 1) -> enumerator
3004 * step(by: 1, to: ) {|n| ... } -> self
3005 * step(by: 1, to: ) -> enumerator
3006 * step(by: , to: nil) {|n| ... } -> self
3007 * step(by: , to: nil) -> enumerator
3009 * Generates a sequence of numbers; with a block given, traverses the sequence.
3011 * Of the Core and Standard Library classes,
3012 * Integer, Float, and Rational use this implementation.
3014 * A quick example:
3016 * squares = []
3017 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
3018 * squares # => [1, 9, 25, 49, 81]
3020 * The generated sequence:
3022 * - Begins with +self+.
3023 * - Continues at intervals of +by+ (which may not be zero).
3024 * - Ends with the last number that is within or equal to +to+;
3025 * that is, less than or equal to +to+ if +by+ is positive,
3026 * greater than or equal to +to+ if +by+ is negative.
3027 * If +to+ is +nil+, the sequence is of infinite length.
3029 * If a block is given, calls the block with each number in the sequence;
3030 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
3032 * <b>Keyword Arguments</b>
3034 * With keyword arguments +by+ and +to+,
3035 * their values (or defaults) determine the step and limit:
3037 * # Both keywords given.
3038 * squares = []
3039 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
3040 * squares # => [16, 36, 64, 100]
3041 * cubes = []
3042 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
3043 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
3044 * squares = []
3045 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
3046 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3048 * squares = []
3049 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
3050 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3052 * # Only keyword to given.
3053 * squares = []
3054 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
3055 * squares # => [16, 25, 36, 49, 64, 81, 100]
3056 * # Only by given.
3058 * # Only keyword by given
3059 * squares = []
3060 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3061 * squares # => [16, 36, 64, 100, 144]
3063 * # No block given.
3064 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3065 * e.class # => Enumerator::ArithmeticSequence
3067 * <b>Positional Arguments</b>
3069 * With optional positional arguments +to+ and +by+,
3070 * their values (or defaults) determine the step and limit:
3072 * squares = []
3073 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3074 * squares # => [16, 36, 64, 100]
3075 * squares = []
3076 * 4.step(10) {|i| squares.push(i*i) }
3077 * squares # => [16, 25, 36, 49, 64, 81, 100]
3078 * squares = []
3079 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3080 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3082 * <b>Implementation Notes</b>
3084 * If all the arguments are integers, the loop operates using an integer
3085 * counter.
3087 * If any of the arguments are floating point numbers, all are converted
3088 * to floats, and the loop is executed
3089 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3090 * where <i>n = (limit - self)/step</i>.
3094 static VALUE
3095 num_step(int argc, VALUE *argv, VALUE from)
3097 VALUE to, step;
3098 int desc, inf;
3100 if (!rb_block_given_p()) {
3101 VALUE by = Qundef;
3103 num_step_extract_args(argc, argv, &to, &step, &by);
3104 if (!UNDEF_P(by)) {
3105 step = by;
3107 if (NIL_P(step)) {
3108 step = INT2FIX(1);
3110 else if (rb_equal(step, INT2FIX(0))) {
3111 rb_raise(rb_eArgError, "step can't be 0");
3113 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3114 rb_obj_is_kind_of(step, rb_cNumeric)) {
3115 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3116 num_step_size, from, to, step, FALSE);
3119 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3122 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3123 if (rb_equal(step, INT2FIX(0))) {
3124 inf = 1;
3126 else if (RB_FLOAT_TYPE_P(to)) {
3127 double f = RFLOAT_VALUE(to);
3128 inf = isinf(f) && (signbit(f) ? desc : !desc);
3130 else inf = 0;
3132 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3133 long i = FIX2LONG(from);
3134 long diff = FIX2LONG(step);
3136 if (inf) {
3137 for (;; i += diff)
3138 rb_yield(LONG2FIX(i));
3140 else {
3141 long end = FIX2LONG(to);
3143 if (desc) {
3144 for (; i >= end; i += diff)
3145 rb_yield(LONG2FIX(i));
3147 else {
3148 for (; i <= end; i += diff)
3149 rb_yield(LONG2FIX(i));
3153 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3154 VALUE i = from;
3156 if (inf) {
3157 for (;; i = rb_funcall(i, '+', 1, step))
3158 rb_yield(i);
3160 else {
3161 ID cmp = desc ? '<' : '>';
3163 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3164 rb_yield(i);
3167 return from;
3170 static char *
3171 out_of_range_float(char (*pbuf)[24], VALUE val)
3173 char *const buf = *pbuf;
3174 char *s;
3176 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3177 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3178 return buf;
3181 #define FLOAT_OUT_OF_RANGE(val, type) do { \
3182 char buf[24]; \
3183 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3184 out_of_range_float(&buf, (val))); \
3185 } while (0)
3187 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3188 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3189 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3190 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3191 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3192 LONG_MIN <= (n): \
3193 LONG_MIN_MINUS_ONE < (n))
3195 long
3196 rb_num2long(VALUE val)
3198 again:
3199 if (NIL_P(val)) {
3200 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3203 if (FIXNUM_P(val)) return FIX2LONG(val);
3205 else if (RB_FLOAT_TYPE_P(val)) {
3206 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3207 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3208 return (long)RFLOAT_VALUE(val);
3210 else {
3211 FLOAT_OUT_OF_RANGE(val, "integer");
3214 else if (RB_BIGNUM_TYPE_P(val)) {
3215 return rb_big2long(val);
3217 else {
3218 val = rb_to_int(val);
3219 goto again;
3223 static unsigned long
3224 rb_num2ulong_internal(VALUE val, int *wrap_p)
3226 again:
3227 if (NIL_P(val)) {
3228 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3231 if (FIXNUM_P(val)) {
3232 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3233 if (wrap_p)
3234 *wrap_p = l < 0;
3235 return (unsigned long)l;
3237 else if (RB_FLOAT_TYPE_P(val)) {
3238 double d = RFLOAT_VALUE(val);
3239 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3240 if (wrap_p)
3241 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3242 if (0 <= d)
3243 return (unsigned long)d;
3244 return (unsigned long)(long)d;
3246 else {
3247 FLOAT_OUT_OF_RANGE(val, "integer");
3250 else if (RB_BIGNUM_TYPE_P(val)) {
3252 unsigned long ul = rb_big2ulong(val);
3253 if (wrap_p)
3254 *wrap_p = BIGNUM_NEGATIVE_P(val);
3255 return ul;
3258 else {
3259 val = rb_to_int(val);
3260 goto again;
3264 unsigned long
3265 rb_num2ulong(VALUE val)
3267 return rb_num2ulong_internal(val, NULL);
3270 void
3271 rb_out_of_int(SIGNED_VALUE num)
3273 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3274 num, num < 0 ? "small" : "big");
3277 #if SIZEOF_INT < SIZEOF_LONG
3278 static void
3279 check_int(long num)
3281 if ((long)(int)num != num) {
3282 rb_out_of_int(num);
3286 static void
3287 check_uint(unsigned long num, int sign)
3289 if (sign) {
3290 /* minus */
3291 if (num < (unsigned long)INT_MIN)
3292 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3294 else {
3295 /* plus */
3296 if (UINT_MAX < num)
3297 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3301 long
3302 rb_num2int(VALUE val)
3304 long num = rb_num2long(val);
3306 check_int(num);
3307 return num;
3310 long
3311 rb_fix2int(VALUE val)
3313 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3315 check_int(num);
3316 return num;
3319 unsigned long
3320 rb_num2uint(VALUE val)
3322 int wrap;
3323 unsigned long num = rb_num2ulong_internal(val, &wrap);
3325 check_uint(num, wrap);
3326 return num;
3329 unsigned long
3330 rb_fix2uint(VALUE val)
3332 unsigned long num;
3334 if (!FIXNUM_P(val)) {
3335 return rb_num2uint(val);
3337 num = FIX2ULONG(val);
3339 check_uint(num, FIXNUM_NEGATIVE_P(val));
3340 return num;
3342 #else
3343 long
3344 rb_num2int(VALUE val)
3346 return rb_num2long(val);
3349 long
3350 rb_fix2int(VALUE val)
3352 return FIX2INT(val);
3355 unsigned long
3356 rb_num2uint(VALUE val)
3358 return rb_num2ulong(val);
3361 unsigned long
3362 rb_fix2uint(VALUE val)
3364 return RB_FIX2ULONG(val);
3366 #endif
3368 NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3369 static void
3370 rb_out_of_short(SIGNED_VALUE num)
3372 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3373 num, num < 0 ? "small" : "big");
3376 static void
3377 check_short(long num)
3379 if ((long)(short)num != num) {
3380 rb_out_of_short(num);
3384 static void
3385 check_ushort(unsigned long num, int sign)
3387 if (sign) {
3388 /* minus */
3389 if (num < (unsigned long)SHRT_MIN)
3390 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3392 else {
3393 /* plus */
3394 if (USHRT_MAX < num)
3395 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3399 short
3400 rb_num2short(VALUE val)
3402 long num = rb_num2long(val);
3404 check_short(num);
3405 return num;
3408 short
3409 rb_fix2short(VALUE val)
3411 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3413 check_short(num);
3414 return num;
3417 unsigned short
3418 rb_num2ushort(VALUE val)
3420 int wrap;
3421 unsigned long num = rb_num2ulong_internal(val, &wrap);
3423 check_ushort(num, wrap);
3424 return num;
3427 unsigned short
3428 rb_fix2ushort(VALUE val)
3430 unsigned long num;
3432 if (!FIXNUM_P(val)) {
3433 return rb_num2ushort(val);
3435 num = FIX2ULONG(val);
3437 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3438 return num;
3441 VALUE
3442 rb_num2fix(VALUE val)
3444 long v;
3446 if (FIXNUM_P(val)) return val;
3448 v = rb_num2long(val);
3449 if (!FIXABLE(v))
3450 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3451 return LONG2FIX(v);
3454 #if HAVE_LONG_LONG
3456 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3457 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3458 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3459 #ifndef ULLONG_MAX
3460 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3461 #endif
3462 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3463 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3464 LLONG_MIN <= (n): \
3465 LLONG_MIN_MINUS_ONE < (n))
3467 LONG_LONG
3468 rb_num2ll(VALUE val)
3470 if (NIL_P(val)) {
3471 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3474 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3476 else if (RB_FLOAT_TYPE_P(val)) {
3477 double d = RFLOAT_VALUE(val);
3478 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3479 return (LONG_LONG)d;
3481 else {
3482 FLOAT_OUT_OF_RANGE(val, "long long");
3485 else if (RB_BIGNUM_TYPE_P(val)) {
3486 return rb_big2ll(val);
3488 else if (RB_TYPE_P(val, T_STRING)) {
3489 rb_raise(rb_eTypeError, "no implicit conversion from string");
3491 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3492 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3495 val = rb_to_int(val);
3496 return NUM2LL(val);
3499 unsigned LONG_LONG
3500 rb_num2ull(VALUE val)
3502 if (NIL_P(val)) {
3503 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3505 else if (FIXNUM_P(val)) {
3506 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3508 else if (RB_FLOAT_TYPE_P(val)) {
3509 double d = RFLOAT_VALUE(val);
3510 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3511 if (0 <= d)
3512 return (unsigned LONG_LONG)d;
3513 return (unsigned LONG_LONG)(LONG_LONG)d;
3515 else {
3516 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3519 else if (RB_BIGNUM_TYPE_P(val)) {
3520 return rb_big2ull(val);
3522 else {
3523 val = rb_to_int(val);
3524 return NUM2ULL(val);
3528 #endif /* HAVE_LONG_LONG */
3530 /********************************************************************
3532 * Document-class: Integer
3534 * An \Integer object represents an integer value.
3536 * You can create an \Integer object explicitly with:
3538 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3540 * You can convert certain objects to Integers with:
3542 * - \Method #Integer.
3544 * An attempt to add a singleton method to an instance of this class
3545 * causes an exception to be raised.
3547 * == What's Here
3549 * First, what's elsewhere. \Class \Integer:
3551 * - Inherits from
3552 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3553 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3554 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3556 * Here, class \Integer provides methods for:
3558 * - {Querying}[rdoc-ref:Integer@Querying]
3559 * - {Comparing}[rdoc-ref:Integer@Comparing]
3560 * - {Converting}[rdoc-ref:Integer@Converting]
3561 * - {Other}[rdoc-ref:Integer@Other]
3563 * === Querying
3565 * - #allbits?: Returns whether all bits in +self+ are set.
3566 * - #anybits?: Returns whether any bits in +self+ are set.
3567 * - #nobits?: Returns whether no bits in +self+ are set.
3569 * === Comparing
3571 * - #<: Returns whether +self+ is less than the given value.
3572 * - #<=: Returns whether +self+ is less than or equal to the given value.
3573 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3574 * to, or greater than the given value.
3575 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3576 * value.
3577 * - #>: Returns whether +self+ is greater than the given value.
3578 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3580 * === Converting
3582 * - ::sqrt: Returns the integer square root of the given value.
3583 * - ::try_convert: Returns the given value converted to an \Integer.
3584 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3585 * - #&: Returns the bitwise AND of +self+ and the given value.
3586 * - #*: Returns the product of +self+ and the given value.
3587 * - #**: Returns the value of +self+ raised to the power of the given value.
3588 * - #+: Returns the sum of +self+ and the given value.
3589 * - #-: Returns the difference of +self+ and the given value.
3590 * - #/: Returns the quotient of +self+ and the given value.
3591 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3592 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3593 * - #[]: Returns a slice of bits from +self+.
3594 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3595 * - #|: Returns the bitwise OR of +self+ and the given value.
3596 * - #ceil: Returns the smallest number greater than or equal to +self+.
3597 * - #chr: Returns a 1-character string containing the character
3598 * represented by the value of +self+.
3599 * - #digits: Returns an array of integers representing the base-radix digits
3600 * of +self+.
3601 * - #div: Returns the integer result of dividing +self+ by the given value.
3602 * - #divmod: Returns a 2-element array containing the quotient and remainder
3603 * results of dividing +self+ by the given value.
3604 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3605 * - #floor: Returns the greatest number smaller than or equal to +self+.
3606 * - #pow: Returns the modular exponentiation of +self+.
3607 * - #pred: Returns the integer predecessor of +self+.
3608 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3609 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3610 * - #succ (aliased as #next): Returns the integer successor of +self+.
3611 * - #to_f: Returns +self+ converted to a Float.
3612 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3613 * representation of +self+ in the given radix.
3614 * - #truncate: Returns +self+ truncated to the given precision.
3616 * === Other
3618 * - #downto: Calls the given block with each integer value from +self+
3619 * down to the given value.
3620 * - #times: Calls the given block +self+ times with each integer
3621 * in <tt>(0..self-1)</tt>.
3622 * - #upto: Calls the given block with each integer value from +self+
3623 * up to the given value.
3627 VALUE
3628 rb_int_odd_p(VALUE num)
3630 if (FIXNUM_P(num)) {
3631 return RBOOL(num & 2);
3633 else {
3634 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3635 return rb_big_odd_p(num);
3639 static VALUE
3640 int_even_p(VALUE num)
3642 if (FIXNUM_P(num)) {
3643 return RBOOL((num & 2) == 0);
3645 else {
3646 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3647 return rb_big_even_p(num);
3651 VALUE
3652 rb_int_even_p(VALUE num)
3654 return int_even_p(num);
3658 * call-seq:
3659 * allbits?(mask) -> true or false
3661 * Returns +true+ if all bits that are set (=1) in +mask+
3662 * are also set in +self+; returns +false+ otherwise.
3664 * Example values:
3666 * 0b1010101 self
3667 * 0b1010100 mask
3668 * 0b1010100 self & mask
3669 * true self.allbits?(mask)
3671 * 0b1010100 self
3672 * 0b1010101 mask
3673 * 0b1010100 self & mask
3674 * false self.allbits?(mask)
3676 * Related: Integer#anybits?, Integer#nobits?.
3680 static VALUE
3681 int_allbits_p(VALUE num, VALUE mask)
3683 mask = rb_to_int(mask);
3684 return rb_int_equal(rb_int_and(num, mask), mask);
3688 * call-seq:
3689 * anybits?(mask) -> true or false
3691 * Returns +true+ if any bit that is set (=1) in +mask+
3692 * is also set in +self+; returns +false+ otherwise.
3694 * Example values:
3696 * 0b10000010 self
3697 * 0b11111111 mask
3698 * 0b10000010 self & mask
3699 * true self.anybits?(mask)
3701 * 0b00000000 self
3702 * 0b11111111 mask
3703 * 0b00000000 self & mask
3704 * false self.anybits?(mask)
3706 * Related: Integer#allbits?, Integer#nobits?.
3710 static VALUE
3711 int_anybits_p(VALUE num, VALUE mask)
3713 mask = rb_to_int(mask);
3714 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3718 * call-seq:
3719 * nobits?(mask) -> true or false
3721 * Returns +true+ if no bit that is set (=1) in +mask+
3722 * is also set in +self+; returns +false+ otherwise.
3724 * Example values:
3726 * 0b11110000 self
3727 * 0b00001111 mask
3728 * 0b00000000 self & mask
3729 * true self.nobits?(mask)
3731 * 0b00000001 self
3732 * 0b11111111 mask
3733 * 0b00000001 self & mask
3734 * false self.nobits?(mask)
3736 * Related: Integer#allbits?, Integer#anybits?.
3740 static VALUE
3741 int_nobits_p(VALUE num, VALUE mask)
3743 mask = rb_to_int(mask);
3744 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3748 * call-seq:
3749 * succ -> next_integer
3751 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3753 * 1.succ #=> 2
3754 * -1.succ #=> 0
3756 * Related: Integer#pred (predecessor value).
3759 VALUE
3760 rb_int_succ(VALUE num)
3762 if (FIXNUM_P(num)) {
3763 long i = FIX2LONG(num) + 1;
3764 return LONG2NUM(i);
3766 if (RB_BIGNUM_TYPE_P(num)) {
3767 return rb_big_plus(num, INT2FIX(1));
3769 return num_funcall1(num, '+', INT2FIX(1));
3772 #define int_succ rb_int_succ
3775 * call-seq:
3776 * pred -> next_integer
3778 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3780 * 1.pred #=> 0
3781 * -1.pred #=> -2
3783 * Related: Integer#succ (successor value).
3787 static VALUE
3788 rb_int_pred(VALUE num)
3790 if (FIXNUM_P(num)) {
3791 long i = FIX2LONG(num) - 1;
3792 return LONG2NUM(i);
3794 if (RB_BIGNUM_TYPE_P(num)) {
3795 return rb_big_minus(num, INT2FIX(1));
3797 return num_funcall1(num, '-', INT2FIX(1));
3800 #define int_pred rb_int_pred
3802 VALUE
3803 rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3805 int n;
3806 VALUE str;
3807 switch (n = rb_enc_codelen(code, enc)) {
3808 case ONIGERR_INVALID_CODE_POINT_VALUE:
3809 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3810 break;
3811 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3812 case 0:
3813 rb_raise(rb_eRangeError, "%u out of char range", code);
3814 break;
3816 str = rb_enc_str_new(0, n, enc);
3817 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3818 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3819 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3821 return str;
3824 /* call-seq:
3825 * chr -> string
3826 * chr(encoding) -> string
3828 * Returns a 1-character string containing the character
3829 * represented by the value of +self+, according to the given +encoding+.
3831 * 65.chr # => "A"
3832 * 0.chr # => "\x00"
3833 * 255.chr # => "\xFF"
3834 * string = 255.chr(Encoding::UTF_8)
3835 * string.encoding # => Encoding::UTF_8
3837 * Raises an exception if +self+ is negative.
3839 * Related: Integer#ord.
3843 static VALUE
3844 int_chr(int argc, VALUE *argv, VALUE num)
3846 char c;
3847 unsigned int i;
3848 rb_encoding *enc;
3850 if (rb_num_to_uint(num, &i) == 0) {
3852 else if (FIXNUM_P(num)) {
3853 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3855 else {
3856 rb_raise(rb_eRangeError, "bignum out of char range");
3859 switch (argc) {
3860 case 0:
3861 if (0xff < i) {
3862 enc = rb_default_internal_encoding();
3863 if (!enc) {
3864 rb_raise(rb_eRangeError, "%u out of char range", i);
3866 goto decode;
3868 c = (char)i;
3869 if (i < 0x80) {
3870 return rb_usascii_str_new(&c, 1);
3872 else {
3873 return rb_str_new(&c, 1);
3875 case 1:
3876 break;
3877 default:
3878 rb_error_arity(argc, 0, 1);
3880 enc = rb_to_encoding(argv[0]);
3881 if (!enc) enc = rb_ascii8bit_encoding();
3882 decode:
3883 return rb_enc_uint_chr(i, enc);
3887 * Fixnum
3890 static VALUE
3891 fix_uminus(VALUE num)
3893 return LONG2NUM(-FIX2LONG(num));
3896 VALUE
3897 rb_int_uminus(VALUE num)
3899 if (FIXNUM_P(num)) {
3900 return fix_uminus(num);
3902 else {
3903 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3904 return rb_big_uminus(num);
3908 VALUE
3909 rb_fix2str(VALUE x, int base)
3911 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3912 long val = FIX2LONG(x);
3913 unsigned long u;
3914 int neg = 0;
3916 if (base < 2 || 36 < base) {
3917 rb_raise(rb_eArgError, "invalid radix %d", base);
3919 #if SIZEOF_LONG < SIZEOF_VOIDP
3920 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3921 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
3922 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
3923 rb_bug("Unnormalized Fixnum value %p", (void *)x);
3925 # else
3926 /* should do something like above code, but currently ruby does not know */
3927 /* such platforms */
3928 # endif
3929 #endif
3930 if (val == 0) {
3931 return rb_usascii_str_new2("0");
3933 if (val < 0) {
3934 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3935 neg = 1;
3937 else {
3938 u = val;
3940 do {
3941 *--b = ruby_digitmap[(int)(u % base)];
3942 } while (u /= base);
3943 if (neg) {
3944 *--b = '-';
3947 return rb_usascii_str_new(b, e - b);
3950 static VALUE rb_fix_to_s_static[10];
3952 VALUE
3953 rb_fix_to_s(VALUE x)
3955 long i = FIX2LONG(x);
3956 if (i >= 0 && i < 10) {
3957 return rb_fix_to_s_static[i];
3959 return rb_fix2str(x, 10);
3963 * call-seq:
3964 * to_s(base = 10) -> string
3966 * Returns a string containing the place-value representation of +self+
3967 * in radix +base+ (in 2..36).
3969 * 12345.to_s # => "12345"
3970 * 12345.to_s(2) # => "11000000111001"
3971 * 12345.to_s(8) # => "30071"
3972 * 12345.to_s(10) # => "12345"
3973 * 12345.to_s(16) # => "3039"
3974 * 12345.to_s(36) # => "9ix"
3975 * 78546939656932.to_s(36) # => "rubyrules"
3977 * Raises an exception if +base+ is out of range.
3980 VALUE
3981 rb_int_to_s(int argc, VALUE *argv, VALUE x)
3983 int base;
3985 if (rb_check_arity(argc, 0, 1))
3986 base = NUM2INT(argv[0]);
3987 else
3988 base = 10;
3989 return rb_int2str(x, base);
3992 VALUE
3993 rb_int2str(VALUE x, int base)
3995 if (FIXNUM_P(x)) {
3996 return rb_fix2str(x, base);
3998 else if (RB_BIGNUM_TYPE_P(x)) {
3999 return rb_big2str(x, base);
4002 return rb_any_to_s(x);
4005 static VALUE
4006 fix_plus(VALUE x, VALUE y)
4008 if (FIXNUM_P(y)) {
4009 return rb_fix_plus_fix(x, y);
4011 else if (RB_BIGNUM_TYPE_P(y)) {
4012 return rb_big_plus(y, x);
4014 else if (RB_FLOAT_TYPE_P(y)) {
4015 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4017 else if (RB_TYPE_P(y, T_COMPLEX)) {
4018 return rb_complex_plus(y, x);
4020 else {
4021 return rb_num_coerce_bin(x, y, '+');
4025 VALUE
4026 rb_fix_plus(VALUE x, VALUE y)
4028 return fix_plus(x, y);
4032 * call-seq:
4033 * self + numeric -> numeric_result
4035 * Performs addition:
4037 * 2 + 2 # => 4
4038 * -2 + 2 # => 0
4039 * -2 + -2 # => -4
4040 * 2 + 2.0 # => 4.0
4041 * 2 + Rational(2, 1) # => (4/1)
4042 * 2 + Complex(2, 0) # => (4+0i)
4046 VALUE
4047 rb_int_plus(VALUE x, VALUE y)
4049 if (FIXNUM_P(x)) {
4050 return fix_plus(x, y);
4052 else if (RB_BIGNUM_TYPE_P(x)) {
4053 return rb_big_plus(x, y);
4055 return rb_num_coerce_bin(x, y, '+');
4058 static VALUE
4059 fix_minus(VALUE x, VALUE y)
4061 if (FIXNUM_P(y)) {
4062 return rb_fix_minus_fix(x, y);
4064 else if (RB_BIGNUM_TYPE_P(y)) {
4065 x = rb_int2big(FIX2LONG(x));
4066 return rb_big_minus(x, y);
4068 else if (RB_FLOAT_TYPE_P(y)) {
4069 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4071 else {
4072 return rb_num_coerce_bin(x, y, '-');
4077 * call-seq:
4078 * self - numeric -> numeric_result
4080 * Performs subtraction:
4082 * 4 - 2 # => 2
4083 * -4 - 2 # => -6
4084 * -4 - -2 # => -2
4085 * 4 - 2.0 # => 2.0
4086 * 4 - Rational(2, 1) # => (2/1)
4087 * 4 - Complex(2, 0) # => (2+0i)
4091 VALUE
4092 rb_int_minus(VALUE x, VALUE y)
4094 if (FIXNUM_P(x)) {
4095 return fix_minus(x, y);
4097 else if (RB_BIGNUM_TYPE_P(x)) {
4098 return rb_big_minus(x, y);
4100 return rb_num_coerce_bin(x, y, '-');
4104 #define SQRT_LONG_MAX HALF_LONG_MSB
4105 /*tests if N*N would overflow*/
4106 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4108 static VALUE
4109 fix_mul(VALUE x, VALUE y)
4111 if (FIXNUM_P(y)) {
4112 return rb_fix_mul_fix(x, y);
4114 else if (RB_BIGNUM_TYPE_P(y)) {
4115 switch (x) {
4116 case INT2FIX(0): return x;
4117 case INT2FIX(1): return y;
4119 return rb_big_mul(y, x);
4121 else if (RB_FLOAT_TYPE_P(y)) {
4122 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4124 else if (RB_TYPE_P(y, T_COMPLEX)) {
4125 return rb_complex_mul(y, x);
4127 else {
4128 return rb_num_coerce_bin(x, y, '*');
4133 * call-seq:
4134 * self * numeric -> numeric_result
4136 * Performs multiplication:
4138 * 4 * 2 # => 8
4139 * 4 * -2 # => -8
4140 * -4 * 2 # => -8
4141 * 4 * 2.0 # => 8.0
4142 * 4 * Rational(1, 3) # => (4/3)
4143 * 4 * Complex(2, 0) # => (8+0i)
4146 VALUE
4147 rb_int_mul(VALUE x, VALUE y)
4149 if (FIXNUM_P(x)) {
4150 return fix_mul(x, y);
4152 else if (RB_BIGNUM_TYPE_P(x)) {
4153 return rb_big_mul(x, y);
4155 return rb_num_coerce_bin(x, y, '*');
4158 static double
4159 fix_fdiv_double(VALUE x, VALUE y)
4161 if (FIXNUM_P(y)) {
4162 long iy = FIX2LONG(y);
4163 #if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4164 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4165 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4167 #endif
4168 return double_div_double(FIX2LONG(x), iy);
4170 else if (RB_BIGNUM_TYPE_P(y)) {
4171 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4173 else if (RB_FLOAT_TYPE_P(y)) {
4174 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4176 else {
4177 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4181 double
4182 rb_int_fdiv_double(VALUE x, VALUE y)
4184 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) {
4185 VALUE gcd = rb_gcd(x, y);
4186 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4187 x = rb_int_idiv(x, gcd);
4188 y = rb_int_idiv(y, gcd);
4191 if (FIXNUM_P(x)) {
4192 return fix_fdiv_double(x, y);
4194 else if (RB_BIGNUM_TYPE_P(x)) {
4195 return rb_big_fdiv_double(x, y);
4197 else {
4198 return nan("");
4203 * call-seq:
4204 * fdiv(numeric) -> float
4206 * Returns the Float result of dividing +self+ by +numeric+:
4208 * 4.fdiv(2) # => 2.0
4209 * 4.fdiv(-2) # => -2.0
4210 * -4.fdiv(2) # => -2.0
4211 * 4.fdiv(2.0) # => 2.0
4212 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4214 * Raises an exception if +numeric+ cannot be converted to a Float.
4218 VALUE
4219 rb_int_fdiv(VALUE x, VALUE y)
4221 if (RB_INTEGER_TYPE_P(x)) {
4222 return DBL2NUM(rb_int_fdiv_double(x, y));
4224 return Qnil;
4227 static VALUE
4228 fix_divide(VALUE x, VALUE y, ID op)
4230 if (FIXNUM_P(y)) {
4231 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4232 return rb_fix_div_fix(x, y);
4234 else if (RB_BIGNUM_TYPE_P(y)) {
4235 x = rb_int2big(FIX2LONG(x));
4236 return rb_big_div(x, y);
4238 else if (RB_FLOAT_TYPE_P(y)) {
4239 if (op == '/') {
4240 double d = FIX2LONG(x);
4241 return rb_flo_div_flo(DBL2NUM(d), y);
4243 else {
4244 VALUE v;
4245 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4246 v = fix_divide(x, y, '/');
4247 return flo_floor(0, 0, v);
4250 else {
4251 if (RB_TYPE_P(y, T_RATIONAL) &&
4252 op == '/' && FIX2LONG(x) == 1)
4253 return rb_rational_reciprocal(y);
4254 return rb_num_coerce_bin(x, y, op);
4258 static VALUE
4259 fix_div(VALUE x, VALUE y)
4261 return fix_divide(x, y, '/');
4265 * call-seq:
4266 * self / numeric -> numeric_result
4268 * Performs division; for integer +numeric+, truncates the result to an integer:
4270 * 4 / 3 # => 1
4271 * 4 / -3 # => -2
4272 * -4 / 3 # => -2
4273 * -4 / -3 # => 1
4275 * For other +numeric+, returns non-integer result:
4277 * 4 / 3.0 # => 1.3333333333333333
4278 * 4 / Rational(3, 1) # => (4/3)
4279 * 4 / Complex(3, 0) # => ((4/3)+0i)
4283 VALUE
4284 rb_int_div(VALUE x, VALUE y)
4286 if (FIXNUM_P(x)) {
4287 return fix_div(x, y);
4289 else if (RB_BIGNUM_TYPE_P(x)) {
4290 return rb_big_div(x, y);
4292 return Qnil;
4295 static VALUE
4296 fix_idiv(VALUE x, VALUE y)
4298 return fix_divide(x, y, id_div);
4302 * call-seq:
4303 * div(numeric) -> integer
4305 * Performs integer division; returns the integer result of dividing +self+
4306 * by +numeric+:
4308 * 4.div(3) # => 1
4309 * 4.div(-3) # => -2
4310 * -4.div(3) # => -2
4311 * -4.div(-3) # => 1
4312 * 4.div(3.0) # => 1
4313 * 4.div(Rational(3, 1)) # => 1
4315 * Raises an exception if +numeric+ does not have method +div+.
4319 VALUE
4320 rb_int_idiv(VALUE x, VALUE y)
4322 if (FIXNUM_P(x)) {
4323 return fix_idiv(x, y);
4325 else if (RB_BIGNUM_TYPE_P(x)) {
4326 return rb_big_idiv(x, y);
4328 return num_div(x, y);
4331 static VALUE
4332 fix_mod(VALUE x, VALUE y)
4334 if (FIXNUM_P(y)) {
4335 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4336 return rb_fix_mod_fix(x, y);
4338 else if (RB_BIGNUM_TYPE_P(y)) {
4339 x = rb_int2big(FIX2LONG(x));
4340 return rb_big_modulo(x, y);
4342 else if (RB_FLOAT_TYPE_P(y)) {
4343 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4345 else {
4346 return rb_num_coerce_bin(x, y, '%');
4351 * call-seq:
4352 * self % other -> real_number
4354 * Returns +self+ modulo +other+ as a real number.
4356 * For integer +n+ and real number +r+, these expressions are equivalent:
4358 * n % r
4359 * n-r*(n/r).floor
4360 * n.divmod(r)[1]
4362 * See Numeric#divmod.
4364 * Examples:
4366 * 10 % 2 # => 0
4367 * 10 % 3 # => 1
4368 * 10 % 4 # => 2
4370 * 10 % -2 # => 0
4371 * 10 % -3 # => -2
4372 * 10 % -4 # => -2
4374 * 10 % 3.0 # => 1.0
4375 * 10 % Rational(3, 1) # => (1/1)
4378 VALUE
4379 rb_int_modulo(VALUE x, VALUE y)
4381 if (FIXNUM_P(x)) {
4382 return fix_mod(x, y);
4384 else if (RB_BIGNUM_TYPE_P(x)) {
4385 return rb_big_modulo(x, y);
4387 return num_modulo(x, y);
4391 * call-seq:
4392 * remainder(other) -> real_number
4394 * Returns the remainder after dividing +self+ by +other+.
4396 * Examples:
4398 * 11.remainder(4) # => 3
4399 * 11.remainder(-4) # => 3
4400 * -11.remainder(4) # => -3
4401 * -11.remainder(-4) # => -3
4403 * 12.remainder(4) # => 0
4404 * 12.remainder(-4) # => 0
4405 * -12.remainder(4) # => 0
4406 * -12.remainder(-4) # => 0
4408 * 13.remainder(4.0) # => 1.0
4409 * 13.remainder(Rational(4, 1)) # => (1/1)
4413 static VALUE
4414 int_remainder(VALUE x, VALUE y)
4416 if (FIXNUM_P(x)) {
4417 if (FIXNUM_P(y)) {
4418 VALUE z = fix_mod(x, y);
4419 RUBY_ASSERT(FIXNUM_P(z));
4420 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4421 z = fix_minus(z, y);
4422 return z;
4424 else if (!RB_BIGNUM_TYPE_P(y)) {
4425 return num_remainder(x, y);
4427 x = rb_int2big(FIX2LONG(x));
4429 else if (!RB_BIGNUM_TYPE_P(x)) {
4430 return Qnil;
4432 return rb_big_remainder(x, y);
4435 static VALUE
4436 fix_divmod(VALUE x, VALUE y)
4438 if (FIXNUM_P(y)) {
4439 VALUE div, mod;
4440 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4441 rb_fix_divmod_fix(x, y, &div, &mod);
4442 return rb_assoc_new(div, mod);
4444 else if (RB_BIGNUM_TYPE_P(y)) {
4445 x = rb_int2big(FIX2LONG(x));
4446 return rb_big_divmod(x, y);
4448 else if (RB_FLOAT_TYPE_P(y)) {
4450 double div, mod;
4451 volatile VALUE a, b;
4453 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4454 a = dbl2ival(div);
4455 b = DBL2NUM(mod);
4456 return rb_assoc_new(a, b);
4459 else {
4460 return rb_num_coerce_bin(x, y, id_divmod);
4465 * call-seq:
4466 * divmod(other) -> array
4468 * Returns a 2-element array <tt>[q, r]</tt>, where
4470 * q = (self/other).floor # Quotient
4471 * r = self % other # Remainder
4473 * Examples:
4475 * 11.divmod(4) # => [2, 3]
4476 * 11.divmod(-4) # => [-3, -1]
4477 * -11.divmod(4) # => [-3, 1]
4478 * -11.divmod(-4) # => [2, -3]
4480 * 12.divmod(4) # => [3, 0]
4481 * 12.divmod(-4) # => [-3, 0]
4482 * -12.divmod(4) # => [-3, 0]
4483 * -12.divmod(-4) # => [3, 0]
4485 * 13.divmod(4.0) # => [3, 1.0]
4486 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4489 VALUE
4490 rb_int_divmod(VALUE x, VALUE y)
4492 if (FIXNUM_P(x)) {
4493 return fix_divmod(x, y);
4495 else if (RB_BIGNUM_TYPE_P(x)) {
4496 return rb_big_divmod(x, y);
4498 return Qnil;
4502 * call-seq:
4503 * self ** numeric -> numeric_result
4505 * Raises +self+ to the power of +numeric+:
4507 * 2 ** 3 # => 8
4508 * 2 ** -3 # => (1/8)
4509 * -2 ** 3 # => -8
4510 * -2 ** -3 # => (-1/8)
4511 * 2 ** 3.3 # => 9.849155306759329
4512 * 2 ** Rational(3, 1) # => (8/1)
4513 * 2 ** Complex(3, 0) # => (8+0i)
4517 static VALUE
4518 int_pow(long x, unsigned long y)
4520 int neg = x < 0;
4521 long z = 1;
4523 if (y == 0) return INT2FIX(1);
4524 if (y == 1) return LONG2NUM(x);
4525 if (neg) x = -x;
4526 if (y & 1)
4527 z = x;
4528 else
4529 neg = 0;
4530 y &= ~1;
4531 do {
4532 while (y % 2 == 0) {
4533 if (!FIT_SQRT_LONG(x)) {
4534 goto bignum;
4536 x = x * x;
4537 y >>= 1;
4540 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4541 goto bignum;
4543 z = x * z;
4545 } while (--y);
4546 if (neg) z = -z;
4547 return LONG2NUM(z);
4549 VALUE v;
4550 bignum:
4551 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4552 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4553 return v;
4554 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4555 return v;
4558 VALUE
4559 rb_int_positive_pow(long x, unsigned long y)
4561 return int_pow(x, y);
4564 static VALUE
4565 fix_pow_inverted(VALUE x, VALUE minusb)
4567 if (x == INT2FIX(0)) {
4568 rb_num_zerodiv();
4569 UNREACHABLE_RETURN(Qundef);
4571 else {
4572 VALUE y = rb_int_pow(x, minusb);
4574 if (RB_FLOAT_TYPE_P(y)) {
4575 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4576 return DBL2NUM(1.0 / d);
4578 else {
4579 return rb_rational_raw(INT2FIX(1), y);
4584 static VALUE
4585 fix_pow(VALUE x, VALUE y)
4587 long a = FIX2LONG(x);
4589 if (FIXNUM_P(y)) {
4590 long b = FIX2LONG(y);
4592 if (a == 1) return INT2FIX(1);
4593 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4594 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4595 if (b == 0) return INT2FIX(1);
4596 if (b == 1) return x;
4597 if (a == 0) return INT2FIX(0);
4598 return int_pow(a, b);
4600 else if (RB_BIGNUM_TYPE_P(y)) {
4601 if (a == 1) return INT2FIX(1);
4602 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4603 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4604 if (a == 0) return INT2FIX(0);
4605 x = rb_int2big(FIX2LONG(x));
4606 return rb_big_pow(x, y);
4608 else if (RB_FLOAT_TYPE_P(y)) {
4609 double dy = RFLOAT_VALUE(y);
4610 if (dy == 0.0) return DBL2NUM(1.0);
4611 if (a == 0) {
4612 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4614 if (a == 1) return DBL2NUM(1.0);
4615 if (a < 0 && dy != round(dy))
4616 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4617 return DBL2NUM(pow((double)a, dy));
4619 else {
4620 return rb_num_coerce_bin(x, y, idPow);
4625 * call-seq:
4626 * self ** numeric -> numeric_result
4628 * Raises +self+ to the power of +numeric+:
4630 * 2 ** 3 # => 8
4631 * 2 ** -3 # => (1/8)
4632 * -2 ** 3 # => -8
4633 * -2 ** -3 # => (-1/8)
4634 * 2 ** 3.3 # => 9.849155306759329
4635 * 2 ** Rational(3, 1) # => (8/1)
4636 * 2 ** Complex(3, 0) # => (8+0i)
4639 VALUE
4640 rb_int_pow(VALUE x, VALUE y)
4642 if (FIXNUM_P(x)) {
4643 return fix_pow(x, y);
4645 else if (RB_BIGNUM_TYPE_P(x)) {
4646 return rb_big_pow(x, y);
4648 return Qnil;
4651 VALUE
4652 rb_num_pow(VALUE x, VALUE y)
4654 VALUE z = rb_int_pow(x, y);
4655 if (!NIL_P(z)) return z;
4656 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4657 if (SPECIAL_CONST_P(x)) return Qnil;
4658 switch (BUILTIN_TYPE(x)) {
4659 case T_COMPLEX:
4660 return rb_complex_pow(x, y);
4661 case T_RATIONAL:
4662 return rb_rational_pow(x, y);
4663 default:
4664 break;
4666 return Qnil;
4669 static VALUE
4670 fix_equal(VALUE x, VALUE y)
4672 if (x == y) return Qtrue;
4673 if (FIXNUM_P(y)) return Qfalse;
4674 else if (RB_BIGNUM_TYPE_P(y)) {
4675 return rb_big_eq(y, x);
4677 else if (RB_FLOAT_TYPE_P(y)) {
4678 return rb_integer_float_eq(x, y);
4680 else {
4681 return num_equal(x, y);
4686 * call-seq:
4687 * self == other -> true or false
4689 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4691 * 1 == 2 #=> false
4692 * 1 == 1.0 #=> true
4694 * Related: Integer#eql? (requires +other+ to be an \Integer).
4697 VALUE
4698 rb_int_equal(VALUE x, VALUE y)
4700 if (FIXNUM_P(x)) {
4701 return fix_equal(x, y);
4703 else if (RB_BIGNUM_TYPE_P(x)) {
4704 return rb_big_eq(x, y);
4706 return Qnil;
4709 static VALUE
4710 fix_cmp(VALUE x, VALUE y)
4712 if (x == y) return INT2FIX(0);
4713 if (FIXNUM_P(y)) {
4714 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4715 return INT2FIX(-1);
4717 else if (RB_BIGNUM_TYPE_P(y)) {
4718 VALUE cmp = rb_big_cmp(y, x);
4719 switch (cmp) {
4720 case INT2FIX(+1): return INT2FIX(-1);
4721 case INT2FIX(-1): return INT2FIX(+1);
4723 return cmp;
4725 else if (RB_FLOAT_TYPE_P(y)) {
4726 return rb_integer_float_cmp(x, y);
4728 else {
4729 return rb_num_coerce_cmp(x, y, id_cmp);
4734 * call-seq:
4735 * self <=> other -> -1, 0, +1, or nil
4737 * Returns:
4739 * - -1, if +self+ is less than +other+.
4740 * - 0, if +self+ is equal to +other+.
4741 * - 1, if +self+ is greater then +other+.
4742 * - +nil+, if +self+ and +other+ are incomparable.
4744 * Examples:
4746 * 1 <=> 2 # => -1
4747 * 1 <=> 1 # => 0
4748 * 1 <=> 0 # => 1
4749 * 1 <=> 'foo' # => nil
4751 * 1 <=> 1.0 # => 0
4752 * 1 <=> Rational(1, 1) # => 0
4753 * 1 <=> Complex(1, 0) # => 0
4755 * This method is the basis for comparisons in module Comparable.
4759 VALUE
4760 rb_int_cmp(VALUE x, VALUE y)
4762 if (FIXNUM_P(x)) {
4763 return fix_cmp(x, y);
4765 else if (RB_BIGNUM_TYPE_P(x)) {
4766 return rb_big_cmp(x, y);
4768 else {
4769 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
4773 static VALUE
4774 fix_gt(VALUE x, VALUE y)
4776 if (FIXNUM_P(y)) {
4777 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4779 else if (RB_BIGNUM_TYPE_P(y)) {
4780 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4782 else if (RB_FLOAT_TYPE_P(y)) {
4783 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
4785 else {
4786 return rb_num_coerce_relop(x, y, '>');
4791 * call-seq:
4792 * self > other -> true or false
4794 * Returns +true+ if the value of +self+ is greater than that of +other+:
4796 * 1 > 0 # => true
4797 * 1 > 1 # => false
4798 * 1 > 2 # => false
4799 * 1 > 0.5 # => true
4800 * 1 > Rational(1, 2) # => true
4802 * Raises an exception if the comparison cannot be made.
4806 VALUE
4807 rb_int_gt(VALUE x, VALUE y)
4809 if (FIXNUM_P(x)) {
4810 return fix_gt(x, y);
4812 else if (RB_BIGNUM_TYPE_P(x)) {
4813 return rb_big_gt(x, y);
4815 return Qnil;
4818 static VALUE
4819 fix_ge(VALUE x, VALUE y)
4821 if (FIXNUM_P(y)) {
4822 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
4824 else if (RB_BIGNUM_TYPE_P(y)) {
4825 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
4827 else if (RB_FLOAT_TYPE_P(y)) {
4828 VALUE rel = rb_integer_float_cmp(x, y);
4829 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
4831 else {
4832 return rb_num_coerce_relop(x, y, idGE);
4837 * call-seq:
4838 * self >= real -> true or false
4840 * Returns +true+ if the value of +self+ is greater than or equal to
4841 * that of +other+:
4843 * 1 >= 0 # => true
4844 * 1 >= 1 # => true
4845 * 1 >= 2 # => false
4846 * 1 >= 0.5 # => true
4847 * 1 >= Rational(1, 2) # => true
4849 * Raises an exception if the comparison cannot be made.
4853 VALUE
4854 rb_int_ge(VALUE x, VALUE y)
4856 if (FIXNUM_P(x)) {
4857 return fix_ge(x, y);
4859 else if (RB_BIGNUM_TYPE_P(x)) {
4860 return rb_big_ge(x, y);
4862 return Qnil;
4865 static VALUE
4866 fix_lt(VALUE x, VALUE y)
4868 if (FIXNUM_P(y)) {
4869 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
4871 else if (RB_BIGNUM_TYPE_P(y)) {
4872 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
4874 else if (RB_FLOAT_TYPE_P(y)) {
4875 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
4877 else {
4878 return rb_num_coerce_relop(x, y, '<');
4883 * call-seq:
4884 * self < other -> true or false
4886 * Returns +true+ if the value of +self+ is less than that of +other+:
4888 * 1 < 0 # => false
4889 * 1 < 1 # => false
4890 * 1 < 2 # => true
4891 * 1 < 0.5 # => false
4892 * 1 < Rational(1, 2) # => false
4894 * Raises an exception if the comparison cannot be made.
4898 static VALUE
4899 int_lt(VALUE x, VALUE y)
4901 if (FIXNUM_P(x)) {
4902 return fix_lt(x, y);
4904 else if (RB_BIGNUM_TYPE_P(x)) {
4905 return rb_big_lt(x, y);
4907 return Qnil;
4910 static VALUE
4911 fix_le(VALUE x, VALUE y)
4913 if (FIXNUM_P(y)) {
4914 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
4916 else if (RB_BIGNUM_TYPE_P(y)) {
4917 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
4919 else if (RB_FLOAT_TYPE_P(y)) {
4920 VALUE rel = rb_integer_float_cmp(x, y);
4921 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
4923 else {
4924 return rb_num_coerce_relop(x, y, idLE);
4929 * call-seq:
4930 * self <= real -> true or false
4932 * Returns +true+ if the value of +self+ is less than or equal to
4933 * that of +other+:
4935 * 1 <= 0 # => false
4936 * 1 <= 1 # => true
4937 * 1 <= 2 # => true
4938 * 1 <= 0.5 # => false
4939 * 1 <= Rational(1, 2) # => false
4941 * Raises an exception if the comparison cannot be made.
4945 static VALUE
4946 int_le(VALUE x, VALUE y)
4948 if (FIXNUM_P(x)) {
4949 return fix_le(x, y);
4951 else if (RB_BIGNUM_TYPE_P(x)) {
4952 return rb_big_le(x, y);
4954 return Qnil;
4957 static VALUE
4958 fix_comp(VALUE num)
4960 return ~num | FIXNUM_FLAG;
4963 VALUE
4964 rb_int_comp(VALUE num)
4966 if (FIXNUM_P(num)) {
4967 return fix_comp(num);
4969 else if (RB_BIGNUM_TYPE_P(num)) {
4970 return rb_big_comp(num);
4972 return Qnil;
4975 static VALUE
4976 num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
4978 ID func = (ID)((VALUE *)arg)[0];
4979 VALUE x = ((VALUE *)arg)[1];
4980 if (recursive) {
4981 num_funcall_op_1_recursion(x, func, y);
4983 return rb_check_funcall(x, func, 1, &y);
4986 VALUE
4987 rb_num_coerce_bit(VALUE x, VALUE y, ID func)
4989 VALUE ret, args[3];
4991 args[0] = (VALUE)func;
4992 args[1] = x;
4993 args[2] = y;
4994 do_coerce(&args[1], &args[2], TRUE);
4995 ret = rb_exec_recursive_paired(num_funcall_bit_1,
4996 args[2], args[1], (VALUE)args);
4997 if (UNDEF_P(ret)) {
4998 /* show the original object, not coerced object */
4999 coerce_failed(x, y);
5001 return ret;
5004 static VALUE
5005 fix_and(VALUE x, VALUE y)
5007 if (FIXNUM_P(y)) {
5008 long val = FIX2LONG(x) & FIX2LONG(y);
5009 return LONG2NUM(val);
5012 if (RB_BIGNUM_TYPE_P(y)) {
5013 return rb_big_and(y, x);
5016 return rb_num_coerce_bit(x, y, '&');
5020 * call-seq:
5021 * self & other -> integer
5023 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5024 * in +self+ and +other+ are 1, 0 otherwise:
5026 * "%04b" % (0b0101 & 0b0110) # => "0100"
5028 * Raises an exception if +other+ is not an \Integer.
5030 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5034 VALUE
5035 rb_int_and(VALUE x, VALUE y)
5037 if (FIXNUM_P(x)) {
5038 return fix_and(x, y);
5040 else if (RB_BIGNUM_TYPE_P(x)) {
5041 return rb_big_and(x, y);
5043 return Qnil;
5046 static VALUE
5047 fix_or(VALUE x, VALUE y)
5049 if (FIXNUM_P(y)) {
5050 long val = FIX2LONG(x) | FIX2LONG(y);
5051 return LONG2NUM(val);
5054 if (RB_BIGNUM_TYPE_P(y)) {
5055 return rb_big_or(y, x);
5058 return rb_num_coerce_bit(x, y, '|');
5062 * call-seq:
5063 * self | other -> integer
5065 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5066 * in +self+ or +other+ is 1, 0 otherwise:
5068 * "%04b" % (0b0101 | 0b0110) # => "0111"
5070 * Raises an exception if +other+ is not an \Integer.
5072 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5076 static VALUE
5077 int_or(VALUE x, VALUE y)
5079 if (FIXNUM_P(x)) {
5080 return fix_or(x, y);
5082 else if (RB_BIGNUM_TYPE_P(x)) {
5083 return rb_big_or(x, y);
5085 return Qnil;
5088 static VALUE
5089 fix_xor(VALUE x, VALUE y)
5091 if (FIXNUM_P(y)) {
5092 long val = FIX2LONG(x) ^ FIX2LONG(y);
5093 return LONG2NUM(val);
5096 if (RB_BIGNUM_TYPE_P(y)) {
5097 return rb_big_xor(y, x);
5100 return rb_num_coerce_bit(x, y, '^');
5104 * call-seq:
5105 * self ^ other -> integer
5107 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5108 * in +self+ and +other+ are different, 0 otherwise:
5110 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5112 * Raises an exception if +other+ is not an \Integer.
5114 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5118 static VALUE
5119 int_xor(VALUE x, VALUE y)
5121 if (FIXNUM_P(x)) {
5122 return fix_xor(x, y);
5124 else if (RB_BIGNUM_TYPE_P(x)) {
5125 return rb_big_xor(x, y);
5127 return Qnil;
5130 static VALUE
5131 rb_fix_lshift(VALUE x, VALUE y)
5133 long val, width;
5135 val = NUM2LONG(x);
5136 if (!val) return (rb_to_int(y), INT2FIX(0));
5137 if (!FIXNUM_P(y))
5138 return rb_big_lshift(rb_int2big(val), y);
5139 width = FIX2LONG(y);
5140 if (width < 0)
5141 return fix_rshift(val, (unsigned long)-width);
5142 return fix_lshift(val, width);
5145 static VALUE
5146 fix_lshift(long val, unsigned long width)
5148 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5149 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5150 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5152 val = val << width;
5153 return LONG2NUM(val);
5157 * call-seq:
5158 * self << count -> integer
5160 * Returns +self+ with bits shifted +count+ positions to the left,
5161 * or to the right if +count+ is negative:
5163 * n = 0b11110000
5164 * "%08b" % (n << 1) # => "111100000"
5165 * "%08b" % (n << 3) # => "11110000000"
5166 * "%08b" % (n << -1) # => "01111000"
5167 * "%08b" % (n << -3) # => "00011110"
5169 * Related: Integer#>>.
5173 VALUE
5174 rb_int_lshift(VALUE x, VALUE y)
5176 if (FIXNUM_P(x)) {
5177 return rb_fix_lshift(x, y);
5179 else if (RB_BIGNUM_TYPE_P(x)) {
5180 return rb_big_lshift(x, y);
5182 return Qnil;
5185 static VALUE
5186 rb_fix_rshift(VALUE x, VALUE y)
5188 long i, val;
5190 val = FIX2LONG(x);
5191 if (!val) return (rb_to_int(y), INT2FIX(0));
5192 if (!FIXNUM_P(y))
5193 return rb_big_rshift(rb_int2big(val), y);
5194 i = FIX2LONG(y);
5195 if (i == 0) return x;
5196 if (i < 0)
5197 return fix_lshift(val, (unsigned long)-i);
5198 return fix_rshift(val, i);
5201 static VALUE
5202 fix_rshift(long val, unsigned long i)
5204 if (i >= sizeof(long)*CHAR_BIT-1) {
5205 if (val < 0) return INT2FIX(-1);
5206 return INT2FIX(0);
5208 val = RSHIFT(val, i);
5209 return LONG2FIX(val);
5213 * call-seq:
5214 * self >> count -> integer
5216 * Returns +self+ with bits shifted +count+ positions to the right,
5217 * or to the left if +count+ is negative:
5219 * n = 0b11110000
5220 * "%08b" % (n >> 1) # => "01111000"
5221 * "%08b" % (n >> 3) # => "00011110"
5222 * "%08b" % (n >> -1) # => "111100000"
5223 * "%08b" % (n >> -3) # => "11110000000"
5225 * Related: Integer#<<.
5229 VALUE
5230 rb_int_rshift(VALUE x, VALUE y)
5232 if (FIXNUM_P(x)) {
5233 return rb_fix_rshift(x, y);
5235 else if (RB_BIGNUM_TYPE_P(x)) {
5236 return rb_big_rshift(x, y);
5238 return Qnil;
5241 VALUE
5242 rb_fix_aref(VALUE fix, VALUE idx)
5244 long val = FIX2LONG(fix);
5245 long i;
5247 idx = rb_to_int(idx);
5248 if (!FIXNUM_P(idx)) {
5249 idx = rb_big_norm(idx);
5250 if (!FIXNUM_P(idx)) {
5251 if (!BIGNUM_SIGN(idx) || val >= 0)
5252 return INT2FIX(0);
5253 return INT2FIX(1);
5256 i = FIX2LONG(idx);
5258 if (i < 0) return INT2FIX(0);
5259 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5260 if (val < 0) return INT2FIX(1);
5261 return INT2FIX(0);
5263 if (val & (1L<<i))
5264 return INT2FIX(1);
5265 return INT2FIX(0);
5269 /* copied from "r_less" in range.c */
5270 /* compares _a_ and _b_ and returns:
5271 * < 0: a < b
5272 * = 0: a = b
5273 * > 0: a > b or non-comparable
5275 static int
5276 compare_indexes(VALUE a, VALUE b)
5278 VALUE r = rb_funcall(a, id_cmp, 1, b);
5280 if (NIL_P(r))
5281 return INT_MAX;
5282 return rb_cmpint(r, a, b);
5285 static VALUE
5286 generate_mask(VALUE len)
5288 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5291 static VALUE
5292 int_aref1(VALUE num, VALUE arg)
5294 VALUE orig_num = num, beg, end;
5295 int excl;
5297 if (rb_range_values(arg, &beg, &end, &excl)) {
5298 if (NIL_P(beg)) {
5299 /* beginless range */
5300 if (!RTEST(num_negative_p(end))) {
5301 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5302 VALUE mask = generate_mask(end);
5303 if (int_zero_p(rb_int_and(num, mask))) {
5304 return INT2FIX(0);
5306 else {
5307 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5310 else {
5311 return INT2FIX(0);
5314 num = rb_int_rshift(num, beg);
5316 int cmp = compare_indexes(beg, end);
5317 if (!NIL_P(end) && cmp < 0) {
5318 VALUE len = rb_int_minus(end, beg);
5319 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5320 VALUE mask = generate_mask(len);
5321 num = rb_int_and(num, mask);
5323 else if (cmp == 0) {
5324 if (excl) return INT2FIX(0);
5325 num = orig_num;
5326 arg = beg;
5327 goto one_bit;
5329 return num;
5332 one_bit:
5333 if (FIXNUM_P(num)) {
5334 return rb_fix_aref(num, arg);
5336 else if (RB_BIGNUM_TYPE_P(num)) {
5337 return rb_big_aref(num, arg);
5339 return Qnil;
5342 static VALUE
5343 int_aref2(VALUE num, VALUE beg, VALUE len)
5345 num = rb_int_rshift(num, beg);
5346 VALUE mask = generate_mask(len);
5347 num = rb_int_and(num, mask);
5348 return num;
5352 * call-seq:
5353 * self[offset] -> 0 or 1
5354 * self[offset, size] -> integer
5355 * self[range] -> integer
5357 * Returns a slice of bits from +self+.
5359 * With argument +offset+, returns the bit at the given offset,
5360 * where offset 0 refers to the least significant bit:
5362 * n = 0b10 # => 2
5363 * n[0] # => 0
5364 * n[1] # => 1
5365 * n[2] # => 0
5366 * n[3] # => 0
5368 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5369 * Thus, negative index always returns zero:
5371 * 255[-1] # => 0
5373 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5374 * beginning at +offset+ and including bits of greater significance:
5376 * n = 0b111000 # => 56
5377 * "%010b" % n[0, 10] # => "0000111000"
5378 * "%010b" % n[4, 10] # => "0000000011"
5380 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5381 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5383 * n = 0b111000 # => 56
5384 * "%010b" % n[0..9] # => "0000111000"
5385 * "%010b" % n[4..9] # => "0000000011"
5387 * Raises an exception if the slice cannot be constructed.
5390 static VALUE
5391 int_aref(int const argc, VALUE * const argv, VALUE const num)
5393 rb_check_arity(argc, 1, 2);
5394 if (argc == 2) {
5395 return int_aref2(num, argv[0], argv[1]);
5397 return int_aref1(num, argv[0]);
5399 return Qnil;
5403 * call-seq:
5404 * to_f -> float
5406 * Converts +self+ to a Float:
5408 * 1.to_f # => 1.0
5409 * -1.to_f # => -1.0
5411 * If the value of +self+ does not fit in a Float,
5412 * the result is infinity:
5414 * (10**400).to_f # => Infinity
5415 * (-10**400).to_f # => -Infinity
5419 static VALUE
5420 int_to_f(VALUE num)
5422 double val;
5424 if (FIXNUM_P(num)) {
5425 val = (double)FIX2LONG(num);
5427 else if (RB_BIGNUM_TYPE_P(num)) {
5428 val = rb_big2dbl(num);
5430 else {
5431 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5434 return DBL2NUM(val);
5437 static VALUE
5438 fix_abs(VALUE fix)
5440 long i = FIX2LONG(fix);
5442 if (i < 0) i = -i;
5444 return LONG2NUM(i);
5447 VALUE
5448 rb_int_abs(VALUE num)
5450 if (FIXNUM_P(num)) {
5451 return fix_abs(num);
5453 else if (RB_BIGNUM_TYPE_P(num)) {
5454 return rb_big_abs(num);
5456 return Qnil;
5459 static VALUE
5460 fix_size(VALUE fix)
5462 return INT2FIX(sizeof(long));
5465 VALUE
5466 rb_int_size(VALUE num)
5468 if (FIXNUM_P(num)) {
5469 return fix_size(num);
5471 else if (RB_BIGNUM_TYPE_P(num)) {
5472 return rb_big_size_m(num);
5474 return Qnil;
5477 static VALUE
5478 rb_fix_bit_length(VALUE fix)
5480 long v = FIX2LONG(fix);
5481 if (v < 0)
5482 v = ~v;
5483 return LONG2FIX(bit_length(v));
5486 VALUE
5487 rb_int_bit_length(VALUE num)
5489 if (FIXNUM_P(num)) {
5490 return rb_fix_bit_length(num);
5492 else if (RB_BIGNUM_TYPE_P(num)) {
5493 return rb_big_bit_length(num);
5495 return Qnil;
5498 static VALUE
5499 rb_fix_digits(VALUE fix, long base)
5501 VALUE digits;
5502 long x = FIX2LONG(fix);
5504 RUBY_ASSERT(x >= 0);
5506 if (base < 2)
5507 rb_raise(rb_eArgError, "invalid radix %ld", base);
5509 if (x == 0)
5510 return rb_ary_new_from_args(1, INT2FIX(0));
5512 digits = rb_ary_new();
5513 while (x >= base) {
5514 long q = x % base;
5515 rb_ary_push(digits, LONG2NUM(q));
5516 x /= base;
5518 rb_ary_push(digits, LONG2NUM(x));
5520 return digits;
5523 static VALUE
5524 rb_int_digits_bigbase(VALUE num, VALUE base)
5526 VALUE digits, bases;
5528 RUBY_ASSERT(!rb_num_negative_p(num));
5530 if (RB_BIGNUM_TYPE_P(base))
5531 base = rb_big_norm(base);
5533 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5534 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5535 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5536 rb_raise(rb_eArgError, "negative radix");
5538 if (FIXNUM_P(base) && FIXNUM_P(num))
5539 return rb_fix_digits(num, FIX2LONG(base));
5541 if (FIXNUM_P(num))
5542 return rb_ary_new_from_args(1, num);
5544 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5545 digits = rb_ary_new();
5546 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5547 VALUE qr = rb_int_divmod(num, base);
5548 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5549 num = RARRAY_AREF(qr, 0);
5551 return digits;
5554 bases = rb_ary_new();
5555 for (VALUE b = base; int_lt(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5556 rb_ary_push(bases, b);
5558 digits = rb_ary_new_from_args(1, num);
5559 while (RARRAY_LEN(bases)) {
5560 VALUE b = rb_ary_pop(bases);
5561 long i, last_idx = RARRAY_LEN(digits) - 1;
5562 for(i = last_idx; i >= 0; i--) {
5563 VALUE n = RARRAY_AREF(digits, i);
5564 VALUE divmod = rb_int_divmod(n, b);
5565 VALUE div = RARRAY_AREF(divmod, 0);
5566 VALUE mod = RARRAY_AREF(divmod, 1);
5567 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5568 rb_ary_store(digits, 2 * i, mod);
5572 return digits;
5576 * call-seq:
5577 * digits(base = 10) -> array_of_integers
5579 * Returns an array of integers representing the +base+-radix
5580 * digits of +self+;
5581 * the first element of the array represents the least significant digit:
5583 * 12345.digits # => [5, 4, 3, 2, 1]
5584 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5585 * 12345.digits(100) # => [45, 23, 1]
5587 * Raises an exception if +self+ is negative or +base+ is less than 2.
5591 static VALUE
5592 rb_int_digits(int argc, VALUE *argv, VALUE num)
5594 VALUE base_value;
5595 long base;
5597 if (rb_num_negative_p(num))
5598 rb_raise(rb_eMathDomainError, "out of domain");
5600 if (rb_check_arity(argc, 0, 1)) {
5601 base_value = rb_to_int(argv[0]);
5602 if (!RB_INTEGER_TYPE_P(base_value))
5603 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5604 rb_obj_classname(argv[0]));
5605 if (RB_BIGNUM_TYPE_P(base_value))
5606 return rb_int_digits_bigbase(num, base_value);
5608 base = FIX2LONG(base_value);
5609 if (base < 0)
5610 rb_raise(rb_eArgError, "negative radix");
5611 else if (base < 2)
5612 rb_raise(rb_eArgError, "invalid radix %ld", base);
5614 else
5615 base = 10;
5617 if (FIXNUM_P(num))
5618 return rb_fix_digits(num, base);
5619 else if (RB_BIGNUM_TYPE_P(num))
5620 return rb_int_digits_bigbase(num, LONG2FIX(base));
5622 return Qnil;
5625 static VALUE
5626 int_upto_size(VALUE from, VALUE args, VALUE eobj)
5628 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5632 * call-seq:
5633 * upto(limit) {|i| ... } -> self
5634 * upto(limit) -> enumerator
5636 * Calls the given block with each integer value from +self+ up to +limit+;
5637 * returns +self+:
5639 * a = []
5640 * 5.upto(10) {|i| a << i } # => 5
5641 * a # => [5, 6, 7, 8, 9, 10]
5642 * a = []
5643 * -5.upto(0) {|i| a << i } # => -5
5644 * a # => [-5, -4, -3, -2, -1, 0]
5645 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5647 * With no block given, returns an Enumerator.
5651 static VALUE
5652 int_upto(VALUE from, VALUE to)
5654 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5655 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5656 long i, end;
5658 end = FIX2LONG(to);
5659 for (i = FIX2LONG(from); i <= end; i++) {
5660 rb_yield(LONG2FIX(i));
5663 else {
5664 VALUE i = from, c;
5666 while (!(c = rb_funcall(i, '>', 1, to))) {
5667 rb_yield(i);
5668 i = rb_funcall(i, '+', 1, INT2FIX(1));
5670 ensure_cmp(c, i, to);
5672 return from;
5675 static VALUE
5676 int_downto_size(VALUE from, VALUE args, VALUE eobj)
5678 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5682 * call-seq:
5683 * downto(limit) {|i| ... } -> self
5684 * downto(limit) -> enumerator
5686 * Calls the given block with each integer value from +self+ down to +limit+;
5687 * returns +self+:
5689 * a = []
5690 * 10.downto(5) {|i| a << i } # => 10
5691 * a # => [10, 9, 8, 7, 6, 5]
5692 * a = []
5693 * 0.downto(-5) {|i| a << i } # => 0
5694 * a # => [0, -1, -2, -3, -4, -5]
5695 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5697 * With no block given, returns an Enumerator.
5701 static VALUE
5702 int_downto(VALUE from, VALUE to)
5704 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5705 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5706 long i, end;
5708 end = FIX2LONG(to);
5709 for (i=FIX2LONG(from); i >= end; i--) {
5710 rb_yield(LONG2FIX(i));
5713 else {
5714 VALUE i = from, c;
5716 while (!(c = rb_funcall(i, '<', 1, to))) {
5717 rb_yield(i);
5718 i = rb_funcall(i, '-', 1, INT2FIX(1));
5720 if (NIL_P(c)) rb_cmperr(i, to);
5722 return from;
5725 static VALUE
5726 int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5728 return int_neg_p(num) ? INT2FIX(0) : num;
5732 * call-seq:
5733 * round(ndigits= 0, half: :up) -> integer
5735 * Returns +self+ rounded to the nearest value with
5736 * a precision of +ndigits+ decimal digits.
5738 * When +ndigits+ is negative, the returned value
5739 * has at least <tt>ndigits.abs</tt> trailing zeros:
5741 * 555.round(-1) # => 560
5742 * 555.round(-2) # => 600
5743 * 555.round(-3) # => 1000
5744 * -555.round(-2) # => -600
5745 * 555.round(-4) # => 0
5747 * Returns +self+ when +ndigits+ is zero or positive.
5749 * 555.round # => 555
5750 * 555.round(1) # => 555
5751 * 555.round(50) # => 555
5753 * If keyword argument +half+ is given,
5754 * and +self+ is equidistant from the two candidate values,
5755 * the rounding is according to the given +half+ value:
5757 * - +:up+ or +nil+: round away from zero:
5759 * 25.round(-1, half: :up) # => 30
5760 * (-25).round(-1, half: :up) # => -30
5762 * - +:down+: round toward zero:
5764 * 25.round(-1, half: :down) # => 20
5765 * (-25).round(-1, half: :down) # => -20
5768 * - +:even+: round toward the candidate whose last nonzero digit is even:
5770 * 25.round(-1, half: :even) # => 20
5771 * 15.round(-1, half: :even) # => 20
5772 * (-25).round(-1, half: :even) # => -20
5774 * Raises and exception if the value for +half+ is invalid.
5776 * Related: Integer#truncate.
5780 static VALUE
5781 int_round(int argc, VALUE* argv, VALUE num)
5783 int ndigits;
5784 int mode;
5785 VALUE nd, opt;
5787 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5788 ndigits = NUM2INT(nd);
5789 mode = rb_num_get_rounding_option(opt);
5790 if (ndigits >= 0) {
5791 return num;
5793 return rb_int_round(num, ndigits, mode);
5797 * :markup: markdown
5799 * call-seq:
5800 * floor(ndigits = 0) -> integer
5802 * Returns an integer that is a "floor" value for `self`,
5803 * as specified by the given `ndigits`,
5804 * which must be an
5805 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5807 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5809 * ```
5810 * 0.floor(2) # => 0
5811 * 0.floor(-2) # => 0
5812 * ```
5814 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5816 * ```
5817 * 555.floor # => 555
5818 * 555.floor(50) # => 555
5819 * ```
5821 * - When `self` is non-zero and `ndigits` is negative,
5822 * returns a value based on a computed granularity:
5824 * - The granularity is `10 ** ndigits.abs`.
5825 * - The returned value is the largest multiple of the granularity
5826 * that is less than or equal to `self`.
5828 * Examples with positive `self`:
5830 * | ndigits | Granularity | 1234.floor(ndigits) |
5831 * |--------:|------------:|--------------------:|
5832 * | -1 | 10 | 1230 |
5833 * | -2 | 100 | 1200 |
5834 * | -3 | 1000 | 1000 |
5835 * | -4 | 10000 | 0 |
5836 * | -5 | 100000 | 0 |
5838 * Examples with negative `self`:
5840 * | ndigits | Granularity | -1234.floor(ndigits) |
5841 * |--------:|------------:|---------------------:|
5842 * | -1 | 10 | -1240 |
5843 * | -2 | 100 | -1300 |
5844 * | -3 | 1000 | -2000 |
5845 * | -4 | 10000 | -10000 |
5846 * | -5 | 100000 | -100000 |
5848 * Related: Integer#ceil.
5852 static VALUE
5853 int_floor(int argc, VALUE* argv, VALUE num)
5855 int ndigits;
5857 if (!rb_check_arity(argc, 0, 1)) return num;
5858 ndigits = NUM2INT(argv[0]);
5859 if (ndigits >= 0) {
5860 return num;
5862 return rb_int_floor(num, ndigits);
5866 * :markup: markdown
5868 * call-seq:
5869 * ceil(ndigits = 0) -> integer
5871 * Returns an integer that is a "ceiling" value for `self`,
5872 * as specified by the given `ndigits`,
5873 * which must be an
5874 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5876 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5878 * ```
5879 * 0.ceil(2) # => 0
5880 * 0.ceil(-2) # => 0
5881 * ```
5883 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5885 * ```
5886 * 555.ceil # => 555
5887 * 555.ceil(50) # => 555
5888 * ```
5890 * - When `self` is non-zero and `ndigits` is negative,
5891 * returns a value based on a computed granularity:
5893 * - The granularity is `10 ** ndigits.abs`.
5894 * - The returned value is the smallest multiple of the granularity
5895 * that is greater than or equal to `self`.
5897 * Examples with positive `self`:
5899 * | ndigits | Granularity | 1234.ceil(ndigits) |
5900 * |--------:|------------:|-------------------:|
5901 * | -1 | 10 | 1240 |
5902 * | -2 | 100 | 1300 |
5903 * | -3 | 1000 | 2000 |
5904 * | -4 | 10000 | 10000 |
5905 * | -5 | 100000 | 100000 |
5907 * Examples with negative `self`:
5909 * | ndigits | Granularity | -1234.ceil(ndigits) |
5910 * |--------:|------------:|--------------------:|
5911 * | -1 | 10 | -1230 |
5912 * | -2 | 100 | -1200 |
5913 * | -3 | 1000 | -1000 |
5914 * | -4 | 10000 | 0 |
5915 * | -5 | 100000 | 0 |
5917 * Related: Integer#floor.
5920 static VALUE
5921 int_ceil(int argc, VALUE* argv, VALUE num)
5923 int ndigits;
5925 if (!rb_check_arity(argc, 0, 1)) return num;
5926 ndigits = NUM2INT(argv[0]);
5927 if (ndigits >= 0) {
5928 return num;
5930 return rb_int_ceil(num, ndigits);
5934 * call-seq:
5935 * truncate(ndigits = 0) -> integer
5937 * Returns +self+ truncated (toward zero) to
5938 * a precision of +ndigits+ decimal digits.
5940 * When +ndigits+ is negative, the returned value
5941 * has at least <tt>ndigits.abs</tt> trailing zeros:
5943 * 555.truncate(-1) # => 550
5944 * 555.truncate(-2) # => 500
5945 * -555.truncate(-2) # => -500
5947 * Returns +self+ when +ndigits+ is zero or positive.
5949 * 555.truncate # => 555
5950 * 555.truncate(50) # => 555
5952 * Related: Integer#round.
5956 static VALUE
5957 int_truncate(int argc, VALUE* argv, VALUE num)
5959 int ndigits;
5961 if (!rb_check_arity(argc, 0, 1)) return num;
5962 ndigits = NUM2INT(argv[0]);
5963 if (ndigits >= 0) {
5964 return num;
5966 return rb_int_truncate(num, ndigits);
5969 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5970 rettype \
5971 prefix##_isqrt(argtype n) \
5973 if (!argtype##_IN_DOUBLE_P(n)) { \
5974 unsigned int b = bit_length(n); \
5975 argtype t; \
5976 rettype x = (rettype)(n >> (b/2+1)); \
5977 x |= ((rettype)1LU << (b-1)/2); \
5978 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5979 return x; \
5981 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5984 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5985 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5986 #else
5987 # define RB_ULONG_IN_DOUBLE_P(n) 1
5988 #endif
5989 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5990 #define RB_ULONG unsigned long
5991 DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5993 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5994 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5995 # define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5996 # else
5997 # define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5998 # endif
5999 # ifdef ULL_TO_DOUBLE
6000 # define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6001 # else
6002 # define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6003 # endif
6004 DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6005 #endif
6007 #define domain_error(msg) \
6008 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6011 * call-seq:
6012 * Integer.sqrt(numeric) -> integer
6014 * Returns the integer square root of the non-negative integer +n+,
6015 * which is the largest non-negative integer less than or equal to the
6016 * square root of +numeric+.
6018 * Integer.sqrt(0) # => 0
6019 * Integer.sqrt(1) # => 1
6020 * Integer.sqrt(24) # => 4
6021 * Integer.sqrt(25) # => 5
6022 * Integer.sqrt(10**400) # => 10**200
6024 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6026 * Integer.sqrt(Complex(4, 0)) # => 2
6027 * Integer.sqrt(Rational(4, 1)) # => 2
6028 * Integer.sqrt(4.0) # => 2
6029 * Integer.sqrt(3.14159) # => 1
6031 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6032 * except that the result of the latter code may differ from the true value
6033 * due to the limited precision of floating point arithmetic.
6035 * Integer.sqrt(10**46) # => 100000000000000000000000
6036 * Math.sqrt(10**46).floor # => 99999999999999991611392
6038 * Raises an exception if +numeric+ is negative.
6042 static VALUE
6043 rb_int_s_isqrt(VALUE self, VALUE num)
6045 unsigned long n, sq;
6046 num = rb_to_int(num);
6047 if (FIXNUM_P(num)) {
6048 if (FIXNUM_NEGATIVE_P(num)) {
6049 domain_error("isqrt");
6051 n = FIX2ULONG(num);
6052 sq = rb_ulong_isqrt(n);
6053 return LONG2FIX(sq);
6055 else {
6056 size_t biglen;
6057 if (RBIGNUM_NEGATIVE_P(num)) {
6058 domain_error("isqrt");
6060 biglen = BIGNUM_LEN(num);
6061 if (biglen == 0) return INT2FIX(0);
6062 #if SIZEOF_BDIGIT <= SIZEOF_LONG
6063 /* short-circuit */
6064 if (biglen == 1) {
6065 n = BIGNUM_DIGITS(num)[0];
6066 sq = rb_ulong_isqrt(n);
6067 return ULONG2NUM(sq);
6069 #endif
6070 return rb_big_isqrt(num);
6075 * call-seq:
6076 * Integer.try_convert(object) -> object, integer, or nil
6078 * If +object+ is an \Integer object, returns +object+.
6079 * Integer.try_convert(1) # => 1
6081 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6082 * calls <tt>object.to_int</tt> and returns the result.
6083 * Integer.try_convert(1.25) # => 1
6085 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6086 * Integer.try_convert([]) # => nil
6088 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6090 static VALUE
6091 int_s_try_convert(VALUE self, VALUE num)
6093 return rb_check_integer_type(num);
6097 * Document-class: ZeroDivisionError
6099 * Raised when attempting to divide an integer by 0.
6101 * 42 / 0 #=> ZeroDivisionError: divided by 0
6103 * Note that only division by an exact 0 will raise the exception:
6105 * 42 / 0.0 #=> Float::INFINITY
6106 * 42 / -0.0 #=> -Float::INFINITY
6107 * 0 / 0.0 #=> NaN
6111 * Document-class: FloatDomainError
6113 * Raised when attempting to convert special float values (in particular
6114 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6116 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6120 * Document-class: Numeric
6122 * \Numeric is the class from which all higher-level numeric classes should inherit.
6124 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6125 * Integer are implemented as immediates, which means that each Integer is a single immutable
6126 * object which is always passed by value.
6128 * a = 1
6129 * 1.object_id == a.object_id #=> true
6131 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6132 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6134 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6135 * 1.dup #=> 1
6136 * 1.object_id == 1.dup.object_id #=> true
6138 * For this reason, \Numeric should be used when defining other numeric classes.
6140 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6141 * Array containing an object that has been coerced into an instance of the new class
6142 * and +self+ (see #coerce).
6144 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6145 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6146 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6147 * instances of other numeric classes.
6149 * class Tally < Numeric
6150 * def initialize(string)
6151 * @string = string
6152 * end
6154 * def to_s
6155 * @string
6156 * end
6158 * def to_i
6159 * @string.size
6160 * end
6162 * def coerce(other)
6163 * [self.class.new('|' * other.to_i), self]
6164 * end
6166 * def <=>(other)
6167 * to_i <=> other.to_i
6168 * end
6170 * def +(other)
6171 * self.class.new('|' * (to_i + other.to_i))
6172 * end
6174 * def -(other)
6175 * self.class.new('|' * (to_i - other.to_i))
6176 * end
6178 * def *(other)
6179 * self.class.new('|' * (to_i * other.to_i))
6180 * end
6182 * def /(other)
6183 * self.class.new('|' * (to_i / other.to_i))
6184 * end
6185 * end
6187 * tally = Tally.new('||')
6188 * puts tally * 2 #=> "||||"
6189 * puts tally > 1 #=> true
6191 * == What's Here
6193 * First, what's elsewhere. \Class \Numeric:
6195 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6196 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6198 * Here, class \Numeric provides methods for:
6200 * - {Querying}[rdoc-ref:Numeric@Querying]
6201 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6202 * - {Converting}[rdoc-ref:Numeric@Converting]
6203 * - {Other}[rdoc-ref:Numeric@Other]
6205 * === Querying
6207 * - #finite?: Returns true unless +self+ is infinite or not a number.
6208 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6209 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6210 * - #integer?: Returns whether +self+ is an integer.
6211 * - #negative?: Returns whether +self+ is negative.
6212 * - #nonzero?: Returns whether +self+ is not zero.
6213 * - #positive?: Returns whether +self+ is positive.
6214 * - #real?: Returns whether +self+ is a real value.
6215 * - #zero?: Returns whether +self+ is zero.
6217 * === Comparing
6219 * - #<=>: Returns:
6221 * - -1 if +self+ is less than the given value.
6222 * - 0 if +self+ is equal to the given value.
6223 * - 1 if +self+ is greater than the given value.
6224 * - +nil+ if +self+ and the given value are not comparable.
6226 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6228 * === Converting
6230 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6231 * - #-@: Returns the value of +self+, negated.
6232 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6233 * - #abs2: Returns the square of +self+.
6234 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6235 * Math::PI otherwise.
6236 * - #ceil: Returns the smallest number greater than or equal to +self+,
6237 * to a given precision.
6238 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6239 * for the given other value.
6240 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6241 * - #denominator: Returns the denominator (always positive)
6242 * of the Rational representation of +self+.
6243 * - #div: Returns the value of +self+ divided by the given value
6244 * and converted to an integer.
6245 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6246 * from dividing +self+ the given divisor.
6247 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6248 * - #floor: Returns the largest number less than or equal to +self+,
6249 * to a given precision.
6250 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6251 * the given value.
6252 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6253 * - #numerator: Returns the numerator of the Rational representation of +self+;
6254 * has the same sign as +self+.
6255 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6256 * - #quo: Returns the value of +self+ divided by the given value.
6257 * - #real: Returns the real part of +self+.
6258 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6259 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6260 * - #round: Returns the value of +self+ rounded to the nearest value
6261 * for the given a precision.
6262 * - #to_c: Returns the Complex representation of +self+.
6263 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6264 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6266 * === Other
6268 * - #clone: Returns +self+; does not allow freezing.
6269 * - #dup (aliased as #+@): Returns +self+.
6270 * - #step: Invokes the given block with the sequence of specified numbers.
6273 void
6274 Init_Numeric(void)
6276 #ifdef _UNICOSMP
6277 /* Turn off floating point exceptions for divide by zero, etc. */
6278 _set_Creg(0, 0);
6279 #endif
6280 id_coerce = rb_intern_const("coerce");
6281 id_to = rb_intern_const("to");
6282 id_by = rb_intern_const("by");
6284 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6285 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6286 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6288 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6289 rb_include_module(rb_cNumeric, rb_mComparable);
6290 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6291 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6293 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6294 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6295 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6296 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6297 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6298 rb_define_method(rb_cNumeric, "div", num_div, 1);
6299 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6300 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6301 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6302 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6303 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6304 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6305 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6307 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6308 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6310 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6311 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6312 rb_define_method(rb_cNumeric, "round", num_round, -1);
6313 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6314 rb_define_method(rb_cNumeric, "step", num_step, -1);
6315 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6316 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6318 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6319 rb_undef_alloc_func(rb_cInteger);
6320 rb_undef_method(CLASS_OF(rb_cInteger), "new");
6321 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6322 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6324 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6325 rb_define_alias(rb_cInteger, "inspect", "to_s");
6326 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6327 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6328 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6329 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6330 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6331 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6332 rb_define_method(rb_cInteger, "next", int_succ, 0);
6333 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6334 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6335 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6336 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6337 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6338 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6339 rb_define_method(rb_cInteger, "round", int_round, -1);
6340 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6342 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6343 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6344 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6345 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6346 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6347 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6348 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6349 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6350 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6351 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6352 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6354 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6356 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6357 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6358 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6359 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6360 rb_define_method(rb_cInteger, "<", int_lt, 1);
6361 rb_define_method(rb_cInteger, "<=", int_le, 1);
6363 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6364 rb_define_method(rb_cInteger, "|", int_or, 1);
6365 rb_define_method(rb_cInteger, "^", int_xor, 1);
6366 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6368 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6369 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6371 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6373 #define fix_to_s_static(n) do { \
6374 VALUE lit = rb_fstring_literal(#n); \
6375 rb_fix_to_s_static[n] = lit; \
6376 rb_vm_register_global_object(lit); \
6377 RB_GC_GUARD(lit); \
6378 } while (0)
6380 fix_to_s_static(0);
6381 fix_to_s_static(1);
6382 fix_to_s_static(2);
6383 fix_to_s_static(3);
6384 fix_to_s_static(4);
6385 fix_to_s_static(5);
6386 fix_to_s_static(6);
6387 fix_to_s_static(7);
6388 fix_to_s_static(8);
6389 fix_to_s_static(9);
6391 #undef fix_to_s_static
6393 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6395 rb_undef_alloc_func(rb_cFloat);
6396 rb_undef_method(CLASS_OF(rb_cFloat), "new");
6399 * The base of the floating point, or number of unique digits used to
6400 * represent the number.
6402 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6404 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6406 * The number of base digits for the +double+ data type.
6408 * Usually defaults to 53.
6410 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6412 * The minimum number of significant decimal digits in a double-precision
6413 * floating point.
6415 * Usually defaults to 15.
6417 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6419 * The smallest possible exponent value in a double-precision floating
6420 * point.
6422 * Usually defaults to -1021.
6424 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6426 * The largest possible exponent value in a double-precision floating
6427 * point.
6429 * Usually defaults to 1024.
6431 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6433 * The smallest negative exponent in a double-precision floating point
6434 * where 10 raised to this power minus 1.
6436 * Usually defaults to -307.
6438 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6440 * The largest positive exponent in a double-precision floating point where
6441 * 10 raised to this power minus 1.
6443 * Usually defaults to 308.
6445 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6447 * The smallest positive normalized number in a double-precision floating point.
6449 * Usually defaults to 2.2250738585072014e-308.
6451 * If the platform supports denormalized numbers,
6452 * there are numbers between zero and Float::MIN.
6453 * 0.0.next_float returns the smallest positive floating point number
6454 * including denormalized numbers.
6456 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6458 * The largest possible integer in a double-precision floating point number.
6460 * Usually defaults to 1.7976931348623157e+308.
6462 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6464 * The difference between 1 and the smallest double-precision floating
6465 * point number greater than 1.
6467 * Usually defaults to 2.2204460492503131e-16.
6469 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6471 * An expression representing positive infinity.
6473 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6475 * An expression representing a value which is "not a number".
6477 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6479 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6480 rb_define_alias(rb_cFloat, "inspect", "to_s");
6481 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6482 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6483 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6484 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6485 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6486 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6487 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6488 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6489 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6490 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6491 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6492 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6493 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6494 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6495 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6496 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6497 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6498 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6499 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6500 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6502 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6503 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6504 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6505 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6506 rb_define_method(rb_cFloat, "round", flo_round, -1);
6507 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6509 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6510 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6511 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6512 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6513 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6516 #undef rb_float_value
6517 double
6518 rb_float_value(VALUE v)
6520 return rb_float_value_inline(v);
6523 #undef rb_float_new
6524 VALUE
6525 rb_float_new(double d)
6527 return rb_float_new_inline(d);
6530 #include "numeric.rbinc"