[ruby/digest] [DOC] Update document to use `rb_digest_make_metadata`
[ruby.git] / numeric.c
blob4db0834ae3fd9233cf01ceab914ff3bf571bb490
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
555 #if 0
557 * call-seq:
558 * dup -> self
560 * Returns +self+.
562 * Related: Numeric#clone.
565 static VALUE
566 num_dup(VALUE x)
568 return x;
570 #else
571 # define num_dup num_uplus
572 #endif
575 * call-seq:
576 * +self -> self
578 * Returns +self+.
582 static VALUE
583 num_uplus(VALUE num)
585 return num;
589 * call-seq:
590 * i -> complex
592 * Returns <tt>Complex(0, self)</tt>:
594 * 2.i # => (0+2i)
595 * -2.i # => (0-2i)
596 * 2.0.i # => (0+2.0i)
597 * Rational(1, 2).i # => (0+(1/2)*i)
598 * Complex(3, 4).i # Raises NoMethodError.
602 static VALUE
603 num_imaginary(VALUE num)
605 return rb_complex_new(INT2FIX(0), num);
609 * call-seq:
610 * -self -> numeric
612 * Unary Minus---Returns the receiver, negated.
615 static VALUE
616 num_uminus(VALUE num)
618 VALUE zero;
620 zero = INT2FIX(0);
621 do_coerce(&zero, &num, TRUE);
623 return num_funcall1(zero, '-', num);
627 * call-seq:
628 * fdiv(other) -> float
630 * Returns the quotient <tt>self/other</tt> as a float,
631 * using method +/+ in the derived class of +self+.
632 * (\Numeric itself does not define method +/+.)
634 * Of the Core and Standard Library classes,
635 * only BigDecimal uses this implementation.
639 static VALUE
640 num_fdiv(VALUE x, VALUE y)
642 return rb_funcall(rb_Float(x), '/', 1, y);
646 * call-seq:
647 * div(other) -> integer
649 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
650 * using method +/+ in the derived class of +self+.
651 * (\Numeric itself does not define method +/+.)
653 * Of the Core and Standard Library classes,
654 * Only Float and Rational use this implementation.
658 static VALUE
659 num_div(VALUE x, VALUE y)
661 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
662 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
666 * call-seq:
667 * self % other -> real_numeric
669 * Returns +self+ modulo +other+ as a real number.
671 * Of the Core and Standard Library classes,
672 * only Rational uses this implementation.
674 * For Rational +r+ and real number +n+, these expressions are equivalent:
676 * r % n
677 * r-n*(r/n).floor
678 * r.divmod(n)[1]
680 * See Numeric#divmod.
682 * Examples:
684 * r = Rational(1, 2) # => (1/2)
685 * r2 = Rational(2, 3) # => (2/3)
686 * r % r2 # => (1/2)
687 * r % 2 # => (1/2)
688 * r % 2.0 # => 0.5
690 * r = Rational(301,100) # => (301/100)
691 * r2 = Rational(7,5) # => (7/5)
692 * r % r2 # => (21/100)
693 * r % -r2 # => (-119/100)
694 * (-r) % r2 # => (119/100)
695 * (-r) %-r2 # => (-21/100)
699 static VALUE
700 num_modulo(VALUE x, VALUE y)
702 VALUE q = num_funcall1(x, id_div, y);
703 return rb_funcall(x, '-', 1,
704 rb_funcall(y, '*', 1, q));
708 * call-seq:
709 * remainder(other) -> real_number
711 * Returns the remainder after dividing +self+ by +other+.
713 * Of the Core and Standard Library classes,
714 * only Float and Rational use this implementation.
716 * Examples:
718 * 11.0.remainder(4) # => 3.0
719 * 11.0.remainder(-4) # => 3.0
720 * -11.0.remainder(4) # => -3.0
721 * -11.0.remainder(-4) # => -3.0
723 * 12.0.remainder(4) # => 0.0
724 * 12.0.remainder(-4) # => 0.0
725 * -12.0.remainder(4) # => -0.0
726 * -12.0.remainder(-4) # => -0.0
728 * 13.0.remainder(4.0) # => 1.0
729 * 13.0.remainder(Rational(4, 1)) # => 1.0
731 * Rational(13, 1).remainder(4) # => (1/1)
732 * Rational(13, 1).remainder(-4) # => (1/1)
733 * Rational(-13, 1).remainder(4) # => (-1/1)
734 * Rational(-13, 1).remainder(-4) # => (-1/1)
738 static VALUE
739 num_remainder(VALUE x, VALUE y)
741 if (!rb_obj_is_kind_of(y, rb_cNumeric)) {
742 do_coerce(&x, &y, TRUE);
744 VALUE z = num_funcall1(x, '%', y);
746 if ((!rb_equal(z, INT2FIX(0))) &&
747 ((rb_num_negative_int_p(x) &&
748 rb_num_positive_int_p(y)) ||
749 (rb_num_positive_int_p(x) &&
750 rb_num_negative_int_p(y)))) {
751 if (RB_FLOAT_TYPE_P(y)) {
752 if (isinf(RFLOAT_VALUE(y))) {
753 return x;
756 return rb_funcall(z, '-', 1, y);
758 return z;
762 * call-seq:
763 * divmod(other) -> array
765 * Returns a 2-element array <tt>[q, r]</tt>, where
767 * q = (self/other).floor # Quotient
768 * r = self % other # Remainder
770 * Of the Core and Standard Library classes,
771 * only Rational uses this implementation.
773 * Examples:
775 * Rational(11, 1).divmod(4) # => [2, (3/1)]
776 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
777 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
778 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
780 * Rational(12, 1).divmod(4) # => [3, (0/1)]
781 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
782 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
783 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
785 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
786 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
789 static VALUE
790 num_divmod(VALUE x, VALUE y)
792 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
796 * call-seq:
797 * abs -> numeric
799 * Returns the absolute value of +self+.
801 * 12.abs #=> 12
802 * (-34.56).abs #=> 34.56
803 * -34.56.abs #=> 34.56
807 static VALUE
808 num_abs(VALUE num)
810 if (rb_num_negative_int_p(num)) {
811 return num_funcall0(num, idUMinus);
813 return num;
817 * call-seq:
818 * zero? -> true or false
820 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
822 * Of the Core and Standard Library classes,
823 * only Rational and Complex use this implementation.
827 static VALUE
828 num_zero_p(VALUE num)
830 return rb_equal(num, INT2FIX(0));
833 static bool
834 int_zero_p(VALUE num)
836 if (FIXNUM_P(num)) {
837 return FIXNUM_ZERO_P(num);
839 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
840 return rb_bigzero_p(num);
843 VALUE
844 rb_int_zero_p(VALUE num)
846 return RBOOL(int_zero_p(num));
850 * call-seq:
851 * nonzero? -> self or nil
853 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
854 * uses method <tt>zero?</tt> for the evaluation.
856 * The returned +self+ allows the method to be chained:
858 * a = %w[z Bb bB bb BB a aA Aa AA A]
859 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
860 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
862 * Of the Core and Standard Library classes,
863 * Integer, Float, Rational, and Complex use this implementation.
865 * Related: #zero?
869 static VALUE
870 num_nonzero_p(VALUE num)
872 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
873 return Qnil;
875 return num;
879 * call-seq:
880 * to_int -> integer
882 * Returns +self+ as an integer;
883 * converts using method +to_i+ in the derived class.
885 * Of the Core and Standard Library classes,
886 * only Rational and Complex use this implementation.
888 * Examples:
890 * Rational(1, 2).to_int # => 0
891 * Rational(2, 1).to_int # => 2
892 * Complex(2, 0).to_int # => 2
893 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
897 static VALUE
898 num_to_int(VALUE num)
900 return num_funcall0(num, id_to_i);
904 * call-seq:
905 * positive? -> true or false
907 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
911 static VALUE
912 num_positive_p(VALUE num)
914 const ID mid = '>';
916 if (FIXNUM_P(num)) {
917 if (method_basic_p(rb_cInteger))
918 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
920 else if (RB_BIGNUM_TYPE_P(num)) {
921 if (method_basic_p(rb_cInteger))
922 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
924 return rb_num_compare_with_zero(num, mid);
928 * call-seq:
929 * negative? -> true or false
931 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
935 static VALUE
936 num_negative_p(VALUE num)
938 return RBOOL(rb_num_negative_int_p(num));
942 /********************************************************************
944 * Document-class: Float
946 * A \Float object represents a sometimes-inexact real number using the native
947 * architecture's double-precision floating point representation.
949 * Floating point has a different arithmetic and is an inexact number.
950 * So you should know its esoteric system. See following:
952 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
953 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#-why-are-rubys-floats-imprecise
954 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
956 * You can create a \Float object explicitly with:
958 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
960 * You can convert certain objects to Floats with:
962 * - \Method #Float.
964 * == What's Here
966 * First, what's elsewhere. \Class \Float:
968 * - Inherits from
969 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
970 * and {class Object}[rdoc-ref:Object@What-27s+Here].
971 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
973 * Here, class \Float provides methods for:
975 * - {Querying}[rdoc-ref:Float@Querying]
976 * - {Comparing}[rdoc-ref:Float@Comparing]
977 * - {Converting}[rdoc-ref:Float@Converting]
979 * === Querying
981 * - #finite?: Returns whether +self+ is finite.
982 * - #hash: Returns the integer hash code for +self+.
983 * - #infinite?: Returns whether +self+ is infinite.
984 * - #nan?: Returns whether +self+ is a NaN (not-a-number).
986 * === Comparing
988 * - #<: Returns whether +self+ is less than the given value.
989 * - #<=: Returns whether +self+ is less than or equal to the given value.
990 * - #<=>: Returns a number indicating whether +self+ is less than, equal
991 * to, or greater than the given value.
992 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
993 * the given value.
994 * - #>: Returns whether +self+ is greater than the given value.
995 * - #>=: Returns whether +self+ is greater than or equal to the given value.
997 * === Converting
999 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
1000 * - #*: Returns the product of +self+ and the given value.
1001 * - #**: Returns the value of +self+ raised to the power of the given value.
1002 * - #+: Returns the sum of +self+ and the given value.
1003 * - #-: Returns the difference of +self+ and the given value.
1004 * - #/: Returns the quotient of +self+ and the given value.
1005 * - #ceil: Returns the smallest number greater than or equal to +self+.
1006 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
1007 * and +self+
1008 * - #divmod: Returns a 2-element array containing the quotient and remainder
1009 * results of dividing +self+ by the given value.
1010 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
1011 * - #floor: Returns the greatest number smaller than or equal to +self+.
1012 * - #next_float: Returns the next-larger representable \Float.
1013 * - #prev_float: Returns the next-smaller representable \Float.
1014 * - #quo: Returns the quotient from dividing +self+ by the given value.
1015 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
1016 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
1017 * - #to_s (aliased as #inspect): Returns a string containing the place-value
1018 * representation of +self+ in the given radix.
1019 * - #truncate: Returns +self+ truncated to a given precision.
1023 VALUE
1024 rb_float_new_in_heap(double d)
1026 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0), sizeof(struct RFloat), 0);
1028 #if SIZEOF_DOUBLE <= SIZEOF_VALUE
1029 flt->float_value = d;
1030 #else
1031 union {
1032 double d;
1033 rb_float_value_type v;
1034 } u = {d};
1035 flt->float_value = u.v;
1036 #endif
1037 OBJ_FREEZE((VALUE)flt);
1038 return (VALUE)flt;
1042 * call-seq:
1043 * to_s -> string
1045 * Returns a string containing a representation of +self+;
1046 * depending of the value of +self+, the string representation
1047 * may contain:
1049 * - A fixed-point number.
1050 * - A number in "scientific notation" (containing an exponent).
1051 * - 'Infinity'.
1052 * - '-Infinity'.
1053 * - 'NaN' (indicating not-a-number).
1055 * 3.14.to_s # => "3.14"
1056 * (10.1**50).to_s # => "1.644631821843879e+50"
1057 * (10.1**500).to_s # => "Infinity"
1058 * (-10.1**500).to_s # => "-Infinity"
1059 * (0.0/0.0).to_s # => "NaN"
1063 static VALUE
1064 flo_to_s(VALUE flt)
1066 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
1067 enum {float_dig = DBL_DIG+1};
1068 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
1069 double value = RFLOAT_VALUE(flt);
1070 VALUE s;
1071 char *p, *e;
1072 int sign, decpt, digs;
1074 if (isinf(value)) {
1075 static const char minf[] = "-Infinity";
1076 const int pos = (value > 0); /* skip "-" */
1077 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
1079 else if (isnan(value))
1080 return rb_usascii_str_new2("NaN");
1082 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
1083 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1084 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
1085 memcpy(buf, p, digs);
1086 free(p);
1087 if (decpt > 0) {
1088 if (decpt < digs) {
1089 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
1090 buf[decpt] = '.';
1091 rb_str_cat(s, buf, digs + 1);
1093 else if (decpt <= DBL_DIG) {
1094 long len;
1095 char *ptr;
1096 rb_str_cat(s, buf, digs);
1097 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
1098 ptr = RSTRING_PTR(s) + len;
1099 if (decpt > digs) {
1100 memset(ptr, '0', decpt - digs);
1101 ptr += decpt - digs;
1103 memcpy(ptr, ".0", 2);
1105 else {
1106 goto exp;
1109 else if (decpt > -4) {
1110 long len;
1111 char *ptr;
1112 rb_str_cat(s, "0.", 2);
1113 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1114 ptr = RSTRING_PTR(s);
1115 memset(ptr += len, '0', -decpt);
1116 memcpy(ptr -= decpt, buf, digs);
1118 else {
1119 goto exp;
1121 return s;
1123 exp:
1124 if (digs > 1) {
1125 memmove(buf + 2, buf + 1, digs - 1);
1127 else {
1128 buf[2] = '0';
1129 digs++;
1131 buf[1] = '.';
1132 rb_str_cat(s, buf, digs + 1);
1133 rb_str_catf(s, "e%+03d", decpt - 1);
1134 return s;
1138 * call-seq:
1139 * coerce(other) -> array
1141 * Returns a 2-element array containing +other+ converted to a \Float
1142 * and +self+:
1144 * f = 3.14 # => 3.14
1145 * f.coerce(2) # => [2.0, 3.14]
1146 * f.coerce(2.0) # => [2.0, 3.14]
1147 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1148 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1150 * Raises an exception if a type conversion fails.
1154 static VALUE
1155 flo_coerce(VALUE x, VALUE y)
1157 return rb_assoc_new(rb_Float(y), x);
1160 VALUE
1161 rb_float_uminus(VALUE flt)
1163 return DBL2NUM(-RFLOAT_VALUE(flt));
1167 * call-seq:
1168 * self + other -> numeric
1170 * Returns a new \Float which is the sum of +self+ and +other+:
1172 * f = 3.14
1173 * f + 1 # => 4.140000000000001
1174 * f + 1.0 # => 4.140000000000001
1175 * f + Rational(1, 1) # => 4.140000000000001
1176 * f + Complex(1, 0) # => (4.140000000000001+0i)
1180 VALUE
1181 rb_float_plus(VALUE x, VALUE y)
1183 if (FIXNUM_P(y)) {
1184 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1186 else if (RB_BIGNUM_TYPE_P(y)) {
1187 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1189 else if (RB_FLOAT_TYPE_P(y)) {
1190 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1192 else {
1193 return rb_num_coerce_bin(x, y, '+');
1198 * call-seq:
1199 * self - other -> numeric
1201 * Returns a new \Float which is the difference of +self+ and +other+:
1203 * f = 3.14
1204 * f - 1 # => 2.14
1205 * f - 1.0 # => 2.14
1206 * f - Rational(1, 1) # => 2.14
1207 * f - Complex(1, 0) # => (2.14+0i)
1211 VALUE
1212 rb_float_minus(VALUE x, VALUE y)
1214 if (FIXNUM_P(y)) {
1215 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1217 else if (RB_BIGNUM_TYPE_P(y)) {
1218 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1220 else if (RB_FLOAT_TYPE_P(y)) {
1221 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1223 else {
1224 return rb_num_coerce_bin(x, y, '-');
1229 * call-seq:
1230 * self * other -> numeric
1232 * Returns a new \Float which is the product of +self+ and +other+:
1234 * f = 3.14
1235 * f * 2 # => 6.28
1236 * f * 2.0 # => 6.28
1237 * f * Rational(1, 2) # => 1.57
1238 * f * Complex(2, 0) # => (6.28+0.0i)
1241 VALUE
1242 rb_float_mul(VALUE x, VALUE y)
1244 if (FIXNUM_P(y)) {
1245 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1247 else if (RB_BIGNUM_TYPE_P(y)) {
1248 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1250 else if (RB_FLOAT_TYPE_P(y)) {
1251 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1253 else {
1254 return rb_num_coerce_bin(x, y, '*');
1258 static double
1259 double_div_double(double x, double y)
1261 if (LIKELY(y != 0.0)) {
1262 return x / y;
1264 else if (x == 0.0) {
1265 return nan("");
1267 else {
1268 double z = signbit(y) ? -1.0 : 1.0;
1269 return x * z * HUGE_VAL;
1273 VALUE
1274 rb_flo_div_flo(VALUE x, VALUE y)
1276 double num = RFLOAT_VALUE(x);
1277 double den = RFLOAT_VALUE(y);
1278 double ret = double_div_double(num, den);
1279 return DBL2NUM(ret);
1283 * call-seq:
1284 * self / other -> numeric
1286 * Returns a new \Float which is the result of dividing +self+ by +other+:
1288 * f = 3.14
1289 * f / 2 # => 1.57
1290 * f / 2.0 # => 1.57
1291 * f / Rational(2, 1) # => 1.57
1292 * f / Complex(2, 0) # => (1.57+0.0i)
1296 VALUE
1297 rb_float_div(VALUE x, VALUE y)
1299 double num = RFLOAT_VALUE(x);
1300 double den;
1301 double ret;
1303 if (FIXNUM_P(y)) {
1304 den = FIX2LONG(y);
1306 else if (RB_BIGNUM_TYPE_P(y)) {
1307 den = rb_big2dbl(y);
1309 else if (RB_FLOAT_TYPE_P(y)) {
1310 den = RFLOAT_VALUE(y);
1312 else {
1313 return rb_num_coerce_bin(x, y, '/');
1316 ret = double_div_double(num, den);
1317 return DBL2NUM(ret);
1321 * call-seq:
1322 * quo(other) -> numeric
1324 * Returns the quotient from dividing +self+ by +other+:
1326 * f = 3.14
1327 * f.quo(2) # => 1.57
1328 * f.quo(-2) # => -1.57
1329 * f.quo(Rational(2, 1)) # => 1.57
1330 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1334 static VALUE
1335 flo_quo(VALUE x, VALUE y)
1337 return num_funcall1(x, '/', y);
1340 static void
1341 flodivmod(double x, double y, double *divp, double *modp)
1343 double div, mod;
1345 if (isnan(y)) {
1346 /* y is NaN so all results are NaN */
1347 if (modp) *modp = y;
1348 if (divp) *divp = y;
1349 return;
1351 if (y == 0.0) rb_num_zerodiv();
1352 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1353 mod = x;
1354 else {
1355 #ifdef HAVE_FMOD
1356 mod = fmod(x, y);
1357 #else
1358 double z;
1360 modf(x/y, &z);
1361 mod = x - z * y;
1362 #endif
1364 if (isinf(x) && !isinf(y))
1365 div = x;
1366 else {
1367 div = (x - mod) / y;
1368 if (modp && divp) div = round(div);
1370 if (y*mod < 0) {
1371 mod += y;
1372 div -= 1.0;
1374 if (modp) *modp = mod;
1375 if (divp) *divp = div;
1379 * Returns the modulo of division of x by y.
1380 * An error will be raised if y == 0.
1383 double
1384 ruby_float_mod(double x, double y)
1386 double mod;
1387 flodivmod(x, y, 0, &mod);
1388 return mod;
1392 * call-seq:
1393 * self % other -> float
1395 * Returns +self+ modulo +other+ as a float.
1397 * For float +f+ and real number +r+, these expressions are equivalent:
1399 * f % r
1400 * f-r*(f/r).floor
1401 * f.divmod(r)[1]
1403 * See Numeric#divmod.
1405 * Examples:
1407 * 10.0 % 2 # => 0.0
1408 * 10.0 % 3 # => 1.0
1409 * 10.0 % 4 # => 2.0
1411 * 10.0 % -2 # => 0.0
1412 * 10.0 % -3 # => -2.0
1413 * 10.0 % -4 # => -2.0
1415 * 10.0 % 4.0 # => 2.0
1416 * 10.0 % Rational(4, 1) # => 2.0
1420 static VALUE
1421 flo_mod(VALUE x, VALUE y)
1423 double fy;
1425 if (FIXNUM_P(y)) {
1426 fy = (double)FIX2LONG(y);
1428 else if (RB_BIGNUM_TYPE_P(y)) {
1429 fy = rb_big2dbl(y);
1431 else if (RB_FLOAT_TYPE_P(y)) {
1432 fy = RFLOAT_VALUE(y);
1434 else {
1435 return rb_num_coerce_bin(x, y, '%');
1437 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1440 static VALUE
1441 dbl2ival(double d)
1443 if (FIXABLE(d)) {
1444 return LONG2FIX((long)d);
1446 return rb_dbl2big(d);
1450 * call-seq:
1451 * divmod(other) -> array
1453 * Returns a 2-element array <tt>[q, r]</tt>, where
1455 * q = (self/other).floor # Quotient
1456 * r = self % other # Remainder
1458 * Examples:
1460 * 11.0.divmod(4) # => [2, 3.0]
1461 * 11.0.divmod(-4) # => [-3, -1.0]
1462 * -11.0.divmod(4) # => [-3, 1.0]
1463 * -11.0.divmod(-4) # => [2, -3.0]
1465 * 12.0.divmod(4) # => [3, 0.0]
1466 * 12.0.divmod(-4) # => [-3, 0.0]
1467 * -12.0.divmod(4) # => [-3, -0.0]
1468 * -12.0.divmod(-4) # => [3, -0.0]
1470 * 13.0.divmod(4.0) # => [3, 1.0]
1471 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1475 static VALUE
1476 flo_divmod(VALUE x, VALUE y)
1478 double fy, div, mod;
1479 volatile VALUE a, b;
1481 if (FIXNUM_P(y)) {
1482 fy = (double)FIX2LONG(y);
1484 else if (RB_BIGNUM_TYPE_P(y)) {
1485 fy = rb_big2dbl(y);
1487 else if (RB_FLOAT_TYPE_P(y)) {
1488 fy = RFLOAT_VALUE(y);
1490 else {
1491 return rb_num_coerce_bin(x, y, id_divmod);
1493 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1494 a = dbl2ival(div);
1495 b = DBL2NUM(mod);
1496 return rb_assoc_new(a, b);
1500 * call-seq:
1501 * self ** other -> numeric
1503 * Raises +self+ to the power of +other+:
1505 * f = 3.14
1506 * f ** 2 # => 9.8596
1507 * f ** -2 # => 0.1014239928597509
1508 * f ** 2.1 # => 11.054834900588839
1509 * f ** Rational(2, 1) # => 9.8596
1510 * f ** Complex(2, 0) # => (9.8596+0i)
1514 VALUE
1515 rb_float_pow(VALUE x, VALUE y)
1517 double dx, dy;
1518 if (y == INT2FIX(2)) {
1519 dx = RFLOAT_VALUE(x);
1520 return DBL2NUM(dx * dx);
1522 else if (FIXNUM_P(y)) {
1523 dx = RFLOAT_VALUE(x);
1524 dy = (double)FIX2LONG(y);
1526 else if (RB_BIGNUM_TYPE_P(y)) {
1527 dx = RFLOAT_VALUE(x);
1528 dy = rb_big2dbl(y);
1530 else if (RB_FLOAT_TYPE_P(y)) {
1531 dx = RFLOAT_VALUE(x);
1532 dy = RFLOAT_VALUE(y);
1533 if (dx < 0 && dy != round(dy))
1534 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1536 else {
1537 return rb_num_coerce_bin(x, y, idPow);
1539 return DBL2NUM(pow(dx, dy));
1543 * call-seq:
1544 * eql?(other) -> true or false
1546 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1548 * Of the Core and Standard Library classes,
1549 * only Integer, Rational, and Complex use this implementation.
1551 * Examples:
1553 * 1.eql?(1) # => true
1554 * 1.eql?(1.0) # => false
1555 * 1.eql?(Rational(1, 1)) # => false
1556 * 1.eql?(Complex(1, 0)) # => false
1558 * \Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1559 * while <tt>==</tt> does not.
1563 static VALUE
1564 num_eql(VALUE x, VALUE y)
1566 if (TYPE(x) != TYPE(y)) return Qfalse;
1568 if (RB_BIGNUM_TYPE_P(x)) {
1569 return rb_big_eql(x, y);
1572 return rb_equal(x, y);
1576 * call-seq:
1577 * self <=> other -> zero or nil
1579 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1581 * No subclass in the Ruby Core or Standard Library uses this implementation.
1585 static VALUE
1586 num_cmp(VALUE x, VALUE y)
1588 if (x == y) return INT2FIX(0);
1589 return Qnil;
1592 static VALUE
1593 num_equal(VALUE x, VALUE y)
1595 VALUE result;
1596 if (x == y) return Qtrue;
1597 result = num_funcall1(y, id_eq, x);
1598 return RBOOL(RTEST(result));
1602 * call-seq:
1603 * self == other -> true or false
1605 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1607 * 2.0 == 2 # => true
1608 * 2.0 == 2.0 # => true
1609 * 2.0 == Rational(2, 1) # => true
1610 * 2.0 == Complex(2, 0) # => true
1612 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1614 * Related: Float#eql? (requires +other+ to be a \Float).
1618 VALUE
1619 rb_float_equal(VALUE x, VALUE y)
1621 volatile double a, b;
1623 if (RB_INTEGER_TYPE_P(y)) {
1624 return rb_integer_float_eq(y, x);
1626 else if (RB_FLOAT_TYPE_P(y)) {
1627 b = RFLOAT_VALUE(y);
1628 #if MSC_VERSION_BEFORE(1300)
1629 if (isnan(b)) return Qfalse;
1630 #endif
1632 else {
1633 return num_equal(x, y);
1635 a = RFLOAT_VALUE(x);
1636 #if MSC_VERSION_BEFORE(1300)
1637 if (isnan(a)) return Qfalse;
1638 #endif
1639 return RBOOL(a == b);
1642 #define flo_eq rb_float_equal
1643 static VALUE rb_dbl_hash(double d);
1646 * call-seq:
1647 * hash -> integer
1649 * Returns the integer hash value for +self+.
1651 * See also Object#hash.
1654 static VALUE
1655 flo_hash(VALUE num)
1657 return rb_dbl_hash(RFLOAT_VALUE(num));
1660 static VALUE
1661 rb_dbl_hash(double d)
1663 return ST2FIX(rb_dbl_long_hash(d));
1666 VALUE
1667 rb_dbl_cmp(double a, double b)
1669 if (isnan(a) || isnan(b)) return Qnil;
1670 if (a == b) return INT2FIX(0);
1671 if (a > b) return INT2FIX(1);
1672 if (a < b) return INT2FIX(-1);
1673 return Qnil;
1677 * call-seq:
1678 * self <=> other -> -1, 0, +1, or nil
1680 * Returns a value that depends on the numeric relation
1681 * between +self+ and +other+:
1683 * - -1, if +self+ is less than +other+.
1684 * - 0, if +self+ is equal to +other+.
1685 * - 1, if +self+ is greater than +other+.
1686 * - +nil+, if the two values are incommensurate.
1688 * Examples:
1690 * 2.0 <=> 2 # => 0
1691 * 2.0 <=> 2.0 # => 0
1692 * 2.0 <=> Rational(2, 1) # => 0
1693 * 2.0 <=> Complex(2, 0) # => 0
1694 * 2.0 <=> 1.9 # => 1
1695 * 2.0 <=> 2.1 # => -1
1696 * 2.0 <=> 'foo' # => nil
1698 * This is the basis for the tests in the Comparable module.
1700 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1704 static VALUE
1705 flo_cmp(VALUE x, VALUE y)
1707 double a, b;
1708 VALUE i;
1710 a = RFLOAT_VALUE(x);
1711 if (isnan(a)) return Qnil;
1712 if (RB_INTEGER_TYPE_P(y)) {
1713 VALUE rel = rb_integer_float_cmp(y, x);
1714 if (FIXNUM_P(rel))
1715 return LONG2FIX(-FIX2LONG(rel));
1716 return rel;
1718 else if (RB_FLOAT_TYPE_P(y)) {
1719 b = RFLOAT_VALUE(y);
1721 else {
1722 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1723 if (RTEST(i)) {
1724 int j = rb_cmpint(i, x, y);
1725 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1726 return INT2FIX(j);
1728 if (a > 0.0) return INT2FIX(1);
1729 return INT2FIX(-1);
1731 return rb_num_coerce_cmp(x, y, id_cmp);
1733 return rb_dbl_cmp(a, b);
1737 rb_float_cmp(VALUE x, VALUE y)
1739 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1743 * call-seq:
1744 * self > other -> true or false
1746 * Returns +true+ if +self+ is numerically greater than +other+:
1748 * 2.0 > 1 # => true
1749 * 2.0 > 1.0 # => true
1750 * 2.0 > Rational(1, 2) # => true
1751 * 2.0 > 2.0 # => false
1753 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1757 VALUE
1758 rb_float_gt(VALUE x, VALUE y)
1760 double a, b;
1762 a = RFLOAT_VALUE(x);
1763 if (RB_INTEGER_TYPE_P(y)) {
1764 VALUE rel = rb_integer_float_cmp(y, x);
1765 if (FIXNUM_P(rel))
1766 return RBOOL(-FIX2LONG(rel) > 0);
1767 return Qfalse;
1769 else if (RB_FLOAT_TYPE_P(y)) {
1770 b = RFLOAT_VALUE(y);
1771 #if MSC_VERSION_BEFORE(1300)
1772 if (isnan(b)) return Qfalse;
1773 #endif
1775 else {
1776 return rb_num_coerce_relop(x, y, '>');
1778 #if MSC_VERSION_BEFORE(1300)
1779 if (isnan(a)) return Qfalse;
1780 #endif
1781 return RBOOL(a > b);
1785 * call-seq:
1786 * self >= other -> true or false
1788 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1790 * 2.0 >= 1 # => true
1791 * 2.0 >= 1.0 # => true
1792 * 2.0 >= Rational(1, 2) # => true
1793 * 2.0 >= 2.0 # => true
1794 * 2.0 >= 2.1 # => false
1796 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1800 static VALUE
1801 flo_ge(VALUE x, VALUE y)
1803 double a, b;
1805 a = RFLOAT_VALUE(x);
1806 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1807 VALUE rel = rb_integer_float_cmp(y, x);
1808 if (FIXNUM_P(rel))
1809 return RBOOL(-FIX2LONG(rel) >= 0);
1810 return Qfalse;
1812 else if (RB_FLOAT_TYPE_P(y)) {
1813 b = RFLOAT_VALUE(y);
1814 #if MSC_VERSION_BEFORE(1300)
1815 if (isnan(b)) return Qfalse;
1816 #endif
1818 else {
1819 return rb_num_coerce_relop(x, y, idGE);
1821 #if MSC_VERSION_BEFORE(1300)
1822 if (isnan(a)) return Qfalse;
1823 #endif
1824 return RBOOL(a >= b);
1828 * call-seq:
1829 * self < other -> true or false
1831 * Returns +true+ if +self+ is numerically less than +other+:
1833 * 2.0 < 3 # => true
1834 * 2.0 < 3.0 # => true
1835 * 2.0 < Rational(3, 1) # => true
1836 * 2.0 < 2.0 # => false
1838 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1842 static VALUE
1843 flo_lt(VALUE x, VALUE y)
1845 double a, b;
1847 a = RFLOAT_VALUE(x);
1848 if (RB_INTEGER_TYPE_P(y)) {
1849 VALUE rel = rb_integer_float_cmp(y, x);
1850 if (FIXNUM_P(rel))
1851 return RBOOL(-FIX2LONG(rel) < 0);
1852 return Qfalse;
1854 else if (RB_FLOAT_TYPE_P(y)) {
1855 b = RFLOAT_VALUE(y);
1856 #if MSC_VERSION_BEFORE(1300)
1857 if (isnan(b)) return Qfalse;
1858 #endif
1860 else {
1861 return rb_num_coerce_relop(x, y, '<');
1863 #if MSC_VERSION_BEFORE(1300)
1864 if (isnan(a)) return Qfalse;
1865 #endif
1866 return RBOOL(a < b);
1870 * call-seq:
1871 * self <= other -> true or false
1873 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1875 * 2.0 <= 3 # => true
1876 * 2.0 <= 3.0 # => true
1877 * 2.0 <= Rational(3, 1) # => true
1878 * 2.0 <= 2.0 # => true
1879 * 2.0 <= 1.0 # => false
1881 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1885 static VALUE
1886 flo_le(VALUE x, VALUE y)
1888 double a, b;
1890 a = RFLOAT_VALUE(x);
1891 if (RB_INTEGER_TYPE_P(y)) {
1892 VALUE rel = rb_integer_float_cmp(y, x);
1893 if (FIXNUM_P(rel))
1894 return RBOOL(-FIX2LONG(rel) <= 0);
1895 return Qfalse;
1897 else if (RB_FLOAT_TYPE_P(y)) {
1898 b = RFLOAT_VALUE(y);
1899 #if MSC_VERSION_BEFORE(1300)
1900 if (isnan(b)) return Qfalse;
1901 #endif
1903 else {
1904 return rb_num_coerce_relop(x, y, idLE);
1906 #if MSC_VERSION_BEFORE(1300)
1907 if (isnan(a)) return Qfalse;
1908 #endif
1909 return RBOOL(a <= b);
1913 * call-seq:
1914 * eql?(other) -> true or false
1916 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1917 * +false+ otherwise:
1919 * 2.0.eql?(2.0) # => true
1920 * 2.0.eql?(1.0) # => false
1921 * 2.0.eql?(1) # => false
1922 * 2.0.eql?(Rational(2, 1)) # => false
1923 * 2.0.eql?(Complex(2, 0)) # => false
1925 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1927 * Related: Float#== (performs type conversions).
1930 VALUE
1931 rb_float_eql(VALUE x, VALUE y)
1933 if (RB_FLOAT_TYPE_P(y)) {
1934 double a = RFLOAT_VALUE(x);
1935 double b = RFLOAT_VALUE(y);
1936 #if MSC_VERSION_BEFORE(1300)
1937 if (isnan(a) || isnan(b)) return Qfalse;
1938 #endif
1939 return RBOOL(a == b);
1941 return Qfalse;
1944 #define flo_eql rb_float_eql
1946 VALUE
1947 rb_float_abs(VALUE flt)
1949 double val = fabs(RFLOAT_VALUE(flt));
1950 return DBL2NUM(val);
1954 * call-seq:
1955 * nan? -> true or false
1957 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1959 * f = -1.0 #=> -1.0
1960 * f.nan? #=> false
1961 * f = 0.0/0.0 #=> NaN
1962 * f.nan? #=> true
1965 static VALUE
1966 flo_is_nan_p(VALUE num)
1968 double value = RFLOAT_VALUE(num);
1970 return RBOOL(isnan(value));
1974 * call-seq:
1975 * infinite? -> -1, 1, or nil
1977 * Returns:
1979 * - 1, if +self+ is <tt>Infinity</tt>.
1980 * - -1 if +self+ is <tt>-Infinity</tt>.
1981 * - +nil+, otherwise.
1983 * Examples:
1985 * f = 1.0/0.0 # => Infinity
1986 * f.infinite? # => 1
1987 * f = -1.0/0.0 # => -Infinity
1988 * f.infinite? # => -1
1989 * f = 1.0 # => 1.0
1990 * f.infinite? # => nil
1991 * f = 0.0/0.0 # => NaN
1992 * f.infinite? # => nil
1996 VALUE
1997 rb_flo_is_infinite_p(VALUE num)
1999 double value = RFLOAT_VALUE(num);
2001 if (isinf(value)) {
2002 return INT2FIX( value < 0 ? -1 : 1 );
2005 return Qnil;
2009 * call-seq:
2010 * finite? -> true or false
2012 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
2013 * +false+ otherwise:
2015 * f = 2.0 # => 2.0
2016 * f.finite? # => true
2017 * f = 1.0/0.0 # => Infinity
2018 * f.finite? # => false
2019 * f = -1.0/0.0 # => -Infinity
2020 * f.finite? # => false
2021 * f = 0.0/0.0 # => NaN
2022 * f.finite? # => false
2026 VALUE
2027 rb_flo_is_finite_p(VALUE num)
2029 double value = RFLOAT_VALUE(num);
2031 return RBOOL(isfinite(value));
2034 static VALUE
2035 flo_nextafter(VALUE flo, double value)
2037 double x, y;
2038 x = NUM2DBL(flo);
2039 y = nextafter(x, value);
2040 return DBL2NUM(y);
2044 * call-seq:
2045 * next_float -> float
2047 * Returns the next-larger representable \Float.
2049 * These examples show the internally stored values (64-bit hexadecimal)
2050 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2052 * f = 0.0 # 0x0000000000000000
2053 * f.next_float # 0x0000000000000001
2055 * f = 0.01 # 0x3f847ae147ae147b
2056 * f.next_float # 0x3f847ae147ae147c
2058 * In the remaining examples here, the output is shown in the usual way
2059 * (result +to_s+):
2061 * 0.01.next_float # => 0.010000000000000002
2062 * 1.0.next_float # => 1.0000000000000002
2063 * 100.0.next_float # => 100.00000000000001
2065 * f = 0.01
2066 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2068 * Output:
2070 * 0 0x1.47ae147ae147bp-7 0.01
2071 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2072 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2073 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2075 * f = 0.0; 100.times { f += 0.1 }
2076 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2077 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2078 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2079 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2080 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2081 * "%a" % 10 # => "0x1.4p+3"
2082 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2084 * Related: Float#prev_float
2087 static VALUE
2088 flo_next_float(VALUE vx)
2090 return flo_nextafter(vx, HUGE_VAL);
2094 * call-seq:
2095 * float.prev_float -> float
2097 * Returns the next-smaller representable \Float.
2099 * These examples show the internally stored values (64-bit hexadecimal)
2100 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2102 * f = 5e-324 # 0x0000000000000001
2103 * f.prev_float # 0x0000000000000000
2105 * f = 0.01 # 0x3f847ae147ae147b
2106 * f.prev_float # 0x3f847ae147ae147a
2108 * In the remaining examples here, the output is shown in the usual way
2109 * (result +to_s+):
2111 * 0.01.prev_float # => 0.009999999999999998
2112 * 1.0.prev_float # => 0.9999999999999999
2113 * 100.0.prev_float # => 99.99999999999999
2115 * f = 0.01
2116 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2118 * Output:
2120 * 0 0x1.47ae147ae147bp-7 0.01
2121 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2122 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2123 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2125 * Related: Float#next_float.
2128 static VALUE
2129 flo_prev_float(VALUE vx)
2131 return flo_nextafter(vx, -HUGE_VAL);
2134 VALUE
2135 rb_float_floor(VALUE num, int ndigits)
2137 double number;
2138 number = RFLOAT_VALUE(num);
2139 if (number == 0.0) {
2140 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2142 if (ndigits > 0) {
2143 int binexp;
2144 double f, mul, res;
2145 frexp(number, &binexp);
2146 if (float_round_overflow(ndigits, binexp)) return num;
2147 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2148 return DBL2NUM(0.0);
2149 f = pow(10, ndigits);
2150 mul = floor(number * f);
2151 res = (mul + 1) / f;
2152 if (res > number)
2153 res = mul / f;
2154 return DBL2NUM(res);
2156 else {
2157 num = dbl2ival(floor(number));
2158 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2159 return num;
2163 static int
2164 flo_ndigits(int argc, VALUE *argv)
2166 if (rb_check_arity(argc, 0, 1)) {
2167 return NUM2INT(argv[0]);
2169 return 0;
2173 * call-seq:
2174 * floor(ndigits = 0) -> float or integer
2176 * Returns the largest number less than or equal to +self+ with
2177 * a precision of +ndigits+ decimal digits.
2179 * When +ndigits+ is positive, returns a float with +ndigits+
2180 * digits after the decimal point (as available):
2182 * f = 12345.6789
2183 * f.floor(1) # => 12345.6
2184 * f.floor(3) # => 12345.678
2185 * f = -12345.6789
2186 * f.floor(1) # => -12345.7
2187 * f.floor(3) # => -12345.679
2189 * When +ndigits+ is non-positive, returns an integer with at least
2190 * <code>ndigits.abs</code> trailing zeros:
2192 * f = 12345.6789
2193 * f.floor(0) # => 12345
2194 * f.floor(-3) # => 12000
2195 * f = -12345.6789
2196 * f.floor(0) # => -12346
2197 * f.floor(-3) # => -13000
2199 * Note that the limited precision of floating-point arithmetic
2200 * may lead to surprising results:
2202 * (0.3 / 0.1).floor #=> 2 (!)
2204 * Related: Float#ceil.
2208 static VALUE
2209 flo_floor(int argc, VALUE *argv, VALUE num)
2211 int ndigits = flo_ndigits(argc, argv);
2212 return rb_float_floor(num, ndigits);
2216 * call-seq:
2217 * ceil(ndigits = 0) -> float or integer
2219 * Returns the smallest number greater than or equal to +self+ with
2220 * a precision of +ndigits+ decimal digits.
2222 * When +ndigits+ is positive, returns a float with +ndigits+
2223 * digits after the decimal point (as available):
2225 * f = 12345.6789
2226 * f.ceil(1) # => 12345.7
2227 * f.ceil(3) # => 12345.679
2228 * f = -12345.6789
2229 * f.ceil(1) # => -12345.6
2230 * f.ceil(3) # => -12345.678
2232 * When +ndigits+ is non-positive, returns an integer with at least
2233 * <code>ndigits.abs</code> trailing zeros:
2235 * f = 12345.6789
2236 * f.ceil(0) # => 12346
2237 * f.ceil(-3) # => 13000
2238 * f = -12345.6789
2239 * f.ceil(0) # => -12345
2240 * f.ceil(-3) # => -12000
2242 * Note that the limited precision of floating-point arithmetic
2243 * may lead to surprising results:
2245 * (2.1 / 0.7).ceil #=> 4 (!)
2247 * Related: Float#floor.
2251 static VALUE
2252 flo_ceil(int argc, VALUE *argv, VALUE num)
2254 int ndigits = flo_ndigits(argc, argv);
2255 return rb_float_ceil(num, ndigits);
2258 VALUE
2259 rb_float_ceil(VALUE num, int ndigits)
2261 double number, f;
2263 number = RFLOAT_VALUE(num);
2264 if (number == 0.0) {
2265 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2267 if (ndigits > 0) {
2268 int binexp;
2269 frexp(number, &binexp);
2270 if (float_round_overflow(ndigits, binexp)) return num;
2271 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2272 return DBL2NUM(0.0);
2273 f = pow(10, ndigits);
2274 f = ceil(number * f) / f;
2275 return DBL2NUM(f);
2277 else {
2278 num = dbl2ival(ceil(number));
2279 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2280 return num;
2284 static int
2285 int_round_zero_p(VALUE num, int ndigits)
2287 long bytes;
2288 /* If 10**N / 2 > num, then return 0 */
2289 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2290 if (FIXNUM_P(num)) {
2291 bytes = sizeof(long);
2293 else if (RB_BIGNUM_TYPE_P(num)) {
2294 bytes = rb_big_size(num);
2296 else {
2297 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2299 return (-0.415241 * ndigits - 0.125 > bytes);
2302 static SIGNED_VALUE
2303 int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2305 SIGNED_VALUE z = +(x + y / 2) / y;
2306 if ((z * y - x) * 2 == y) {
2307 z &= ~1;
2309 return z * y;
2312 static SIGNED_VALUE
2313 int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2315 return (x + y / 2) / y * y;
2318 static SIGNED_VALUE
2319 int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2321 return (x + y / 2 - 1) / y * y;
2324 static int
2325 int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2327 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2330 static int
2331 int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2333 return int_pos_p(num);
2336 static int
2337 int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2339 return int_neg_p(num);
2343 * Assumes num is an \Integer, ndigits <= 0
2345 static VALUE
2346 rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2348 VALUE n, f, h, r;
2350 if (int_round_zero_p(num, ndigits)) {
2351 return INT2FIX(0);
2354 f = int_pow(10, -ndigits);
2355 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2356 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2357 int neg = x < 0;
2358 if (neg) x = -x;
2359 x = ROUND_CALL(mode, int_round, (x, y));
2360 if (neg) x = -x;
2361 return LONG2NUM(x);
2363 if (RB_FLOAT_TYPE_P(f)) {
2364 /* then int_pow overflow */
2365 return INT2FIX(0);
2367 h = rb_int_idiv(f, INT2FIX(2));
2368 r = rb_int_modulo(num, f);
2369 n = rb_int_minus(num, r);
2370 r = rb_int_cmp(r, h);
2371 if (FIXNUM_POSITIVE_P(r) ||
2372 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2373 n = rb_int_plus(n, f);
2375 return n;
2378 static VALUE
2379 rb_int_floor(VALUE num, int ndigits)
2381 VALUE f;
2383 if (int_round_zero_p(num, ndigits))
2384 return INT2FIX(0);
2385 f = int_pow(10, -ndigits);
2386 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2387 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2388 int neg = x < 0;
2389 if (neg) x = -x + y - 1;
2390 x = x / y * y;
2391 if (neg) x = -x;
2392 return LONG2NUM(x);
2394 if (RB_FLOAT_TYPE_P(f)) {
2395 /* then int_pow overflow */
2396 return INT2FIX(0);
2398 return rb_int_minus(num, rb_int_modulo(num, f));
2401 static VALUE
2402 rb_int_ceil(VALUE num, int ndigits)
2404 VALUE f;
2406 if (int_round_zero_p(num, ndigits))
2407 return INT2FIX(0);
2408 f = int_pow(10, -ndigits);
2409 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2410 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2411 int neg = x < 0;
2412 if (neg) x = -x;
2413 else x += y - 1;
2414 x = (x / y) * y;
2415 if (neg) x = -x;
2416 return LONG2NUM(x);
2418 if (RB_FLOAT_TYPE_P(f)) {
2419 /* then int_pow overflow */
2420 return INT2FIX(0);
2422 return rb_int_plus(num, rb_int_minus(f, rb_int_modulo(num, f)));
2425 VALUE
2426 rb_int_truncate(VALUE num, int ndigits)
2428 VALUE f;
2429 VALUE m;
2431 if (int_round_zero_p(num, ndigits))
2432 return INT2FIX(0);
2433 f = int_pow(10, -ndigits);
2434 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2435 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2436 int neg = x < 0;
2437 if (neg) x = -x;
2438 x = x / y * y;
2439 if (neg) x = -x;
2440 return LONG2NUM(x);
2442 if (RB_FLOAT_TYPE_P(f)) {
2443 /* then int_pow overflow */
2444 return INT2FIX(0);
2446 m = rb_int_modulo(num, f);
2447 if (int_neg_p(num)) {
2448 return rb_int_plus(num, rb_int_minus(f, m));
2450 else {
2451 return rb_int_minus(num, m);
2456 * call-seq:
2457 * round(ndigits = 0, half: :up) -> integer or float
2459 * Returns +self+ rounded to the nearest value with
2460 * a precision of +ndigits+ decimal digits.
2462 * When +ndigits+ is non-negative, returns a float with +ndigits+
2463 * after the decimal point (as available):
2465 * f = 12345.6789
2466 * f.round(1) # => 12345.7
2467 * f.round(3) # => 12345.679
2468 * f = -12345.6789
2469 * f.round(1) # => -12345.7
2470 * f.round(3) # => -12345.679
2472 * When +ndigits+ is negative, returns an integer
2473 * with at least <tt>ndigits.abs</tt> trailing zeros:
2475 * f = 12345.6789
2476 * f.round(0) # => 12346
2477 * f.round(-3) # => 12000
2478 * f = -12345.6789
2479 * f.round(0) # => -12346
2480 * f.round(-3) # => -12000
2482 * If keyword argument +half+ is given,
2483 * and +self+ is equidistant from the two candidate values,
2484 * the rounding is according to the given +half+ value:
2486 * - +:up+ or +nil+: round away from zero:
2488 * 2.5.round(half: :up) # => 3
2489 * 3.5.round(half: :up) # => 4
2490 * (-2.5).round(half: :up) # => -3
2492 * - +:down+: round toward zero:
2494 * 2.5.round(half: :down) # => 2
2495 * 3.5.round(half: :down) # => 3
2496 * (-2.5).round(half: :down) # => -2
2498 * - +:even+: round toward the candidate whose last nonzero digit is even:
2500 * 2.5.round(half: :even) # => 2
2501 * 3.5.round(half: :even) # => 4
2502 * (-2.5).round(half: :even) # => -2
2504 * Raises and exception if the value for +half+ is invalid.
2506 * Related: Float#truncate.
2510 static VALUE
2511 flo_round(int argc, VALUE *argv, VALUE num)
2513 double number, f, x;
2514 VALUE nd, opt;
2515 int ndigits = 0;
2516 enum ruby_num_rounding_mode mode;
2518 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2519 ndigits = NUM2INT(nd);
2521 mode = rb_num_get_rounding_option(opt);
2522 number = RFLOAT_VALUE(num);
2523 if (number == 0.0) {
2524 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2526 if (ndigits < 0) {
2527 return rb_int_round(flo_to_i(num), ndigits, mode);
2529 if (ndigits == 0) {
2530 x = ROUND_CALL(mode, round, (number, 1.0));
2531 return dbl2ival(x);
2533 if (isfinite(number)) {
2534 int binexp;
2535 frexp(number, &binexp);
2536 if (float_round_overflow(ndigits, binexp)) return num;
2537 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2538 if (ndigits > 14) {
2539 /* In this case, pow(10, ndigits) may not be accurate. */
2540 return rb_flo_round_by_rational(argc, argv, num);
2542 f = pow(10, ndigits);
2543 x = ROUND_CALL(mode, round, (number, f));
2544 return DBL2NUM(x / f);
2546 return num;
2549 static int
2550 float_round_overflow(int ndigits, int binexp)
2552 enum {float_dig = DBL_DIG+2};
2554 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2555 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2556 Recall that up to float_dig digits can be needed to represent a double,
2557 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2558 will be an integer and thus the result is the original number.
2559 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2560 if ndigits + exp < 0, the result is 0.
2561 We have:
2562 2 ** (binexp-1) <= |number| < 2 ** binexp
2563 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2564 If binexp >= 0, and since log_2(10) = 3.322259:
2565 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2566 floor(binexp/4) <= exp <= ceil(binexp/3)
2567 If binexp <= 0, swap the /4 and the /3
2568 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2569 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2571 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2572 return TRUE;
2574 return FALSE;
2577 static int
2578 float_round_underflow(int ndigits, int binexp)
2580 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2581 return TRUE;
2583 return FALSE;
2587 * call-seq:
2588 * to_i -> integer
2590 * Returns +self+ truncated to an Integer.
2592 * 1.2.to_i # => 1
2593 * (-1.2).to_i # => -1
2595 * Note that the limited precision of floating-point arithmetic
2596 * may lead to surprising results:
2598 * (0.3 / 0.1).to_i # => 2 (!)
2602 static VALUE
2603 flo_to_i(VALUE num)
2605 double f = RFLOAT_VALUE(num);
2607 if (f > 0.0) f = floor(f);
2608 if (f < 0.0) f = ceil(f);
2610 return dbl2ival(f);
2614 * call-seq:
2615 * truncate(ndigits = 0) -> float or integer
2617 * Returns +self+ truncated (toward zero) to
2618 * a precision of +ndigits+ decimal digits.
2620 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2621 * after the decimal point (as available):
2623 * f = 12345.6789
2624 * f.truncate(1) # => 12345.6
2625 * f.truncate(3) # => 12345.678
2626 * f = -12345.6789
2627 * f.truncate(1) # => -12345.6
2628 * f.truncate(3) # => -12345.678
2630 * When +ndigits+ is negative, returns an integer
2631 * with at least <tt>ndigits.abs</tt> trailing zeros:
2633 * f = 12345.6789
2634 * f.truncate(0) # => 12345
2635 * f.truncate(-3) # => 12000
2636 * f = -12345.6789
2637 * f.truncate(0) # => -12345
2638 * f.truncate(-3) # => -12000
2640 * Note that the limited precision of floating-point arithmetic
2641 * may lead to surprising results:
2643 * (0.3 / 0.1).truncate #=> 2 (!)
2645 * Related: Float#round.
2648 static VALUE
2649 flo_truncate(int argc, VALUE *argv, VALUE num)
2651 if (signbit(RFLOAT_VALUE(num)))
2652 return flo_ceil(argc, argv, num);
2653 else
2654 return flo_floor(argc, argv, num);
2658 * call-seq:
2659 * floor(digits = 0) -> integer or float
2661 * Returns the largest number that is less than or equal to +self+ with
2662 * a precision of +digits+ decimal digits.
2664 * \Numeric implements this by converting +self+ to a Float and
2665 * invoking Float#floor.
2668 static VALUE
2669 num_floor(int argc, VALUE *argv, VALUE num)
2671 return flo_floor(argc, argv, rb_Float(num));
2675 * call-seq:
2676 * ceil(digits = 0) -> integer or float
2678 * Returns the smallest number that is greater than or equal to +self+ with
2679 * a precision of +digits+ decimal digits.
2681 * \Numeric implements this by converting +self+ to a Float and
2682 * invoking Float#ceil.
2685 static VALUE
2686 num_ceil(int argc, VALUE *argv, VALUE num)
2688 return flo_ceil(argc, argv, rb_Float(num));
2692 * call-seq:
2693 * round(digits = 0) -> integer or float
2695 * Returns +self+ rounded to the nearest value with
2696 * a precision of +digits+ decimal digits.
2698 * \Numeric implements this by converting +self+ to a Float and
2699 * invoking Float#round.
2702 static VALUE
2703 num_round(int argc, VALUE* argv, VALUE num)
2705 return flo_round(argc, argv, rb_Float(num));
2709 * call-seq:
2710 * truncate(digits = 0) -> integer or float
2712 * Returns +self+ truncated (toward zero) to
2713 * a precision of +digits+ decimal digits.
2715 * \Numeric implements this by converting +self+ to a Float and
2716 * invoking Float#truncate.
2719 static VALUE
2720 num_truncate(int argc, VALUE *argv, VALUE num)
2722 return flo_truncate(argc, argv, rb_Float(num));
2725 double
2726 ruby_float_step_size(double beg, double end, double unit, int excl)
2728 const double epsilon = DBL_EPSILON;
2729 double d, n, err;
2731 if (unit == 0) {
2732 return HUGE_VAL;
2734 if (isinf(unit)) {
2735 return unit > 0 ? beg <= end : beg >= end;
2737 n= (end - beg)/unit;
2738 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2739 if (err>0.5) err=0.5;
2740 if (excl) {
2741 if (n<=0) return 0;
2742 if (n<1)
2743 n = 0;
2744 else
2745 n = floor(n - err);
2746 d = +((n + 1) * unit) + beg;
2747 if (beg < end) {
2748 if (d < end)
2749 n++;
2751 else if (beg > end) {
2752 if (d > end)
2753 n++;
2756 else {
2757 if (n<0) return 0;
2758 n = floor(n + err);
2759 d = +((n + 1) * unit) + beg;
2760 if (beg < end) {
2761 if (d <= end)
2762 n++;
2764 else if (beg > end) {
2765 if (d >= end)
2766 n++;
2769 return n+1;
2773 ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2775 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2776 double unit = NUM2DBL(step);
2777 double beg = NUM2DBL(from);
2778 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2779 double n = ruby_float_step_size(beg, end, unit, excl);
2780 long i;
2782 if (isinf(unit)) {
2783 /* if unit is infinity, i*unit+beg is NaN */
2784 if (n) rb_yield(DBL2NUM(beg));
2786 else if (unit == 0) {
2787 VALUE val = DBL2NUM(beg);
2788 for (;;)
2789 rb_yield(val);
2791 else {
2792 for (i=0; i<n; i++) {
2793 double d = i*unit+beg;
2794 if (unit >= 0 ? end < d : d < end) d = end;
2795 rb_yield(DBL2NUM(d));
2798 return TRUE;
2800 return FALSE;
2803 VALUE
2804 ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2806 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2807 long delta, diff;
2809 diff = FIX2LONG(step);
2810 if (diff == 0) {
2811 return DBL2NUM(HUGE_VAL);
2813 delta = FIX2LONG(to) - FIX2LONG(from);
2814 if (diff < 0) {
2815 diff = -diff;
2816 delta = -delta;
2818 if (excl) {
2819 delta--;
2821 if (delta < 0) {
2822 return INT2FIX(0);
2824 return ULONG2NUM(delta / diff + 1UL);
2826 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2827 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2829 if (isinf(n)) return DBL2NUM(n);
2830 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2831 return rb_dbl2big(n);
2833 else {
2834 VALUE result;
2835 ID cmp = '>';
2836 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2837 case 0: return DBL2NUM(HUGE_VAL);
2838 case -1: cmp = '<'; break;
2840 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2841 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2842 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2843 result = rb_funcall(result, '+', 1, INT2FIX(1));
2845 return result;
2849 static int
2850 num_step_negative_p(VALUE num)
2852 const ID mid = '<';
2853 VALUE zero = INT2FIX(0);
2854 VALUE r;
2856 if (FIXNUM_P(num)) {
2857 if (method_basic_p(rb_cInteger))
2858 return (SIGNED_VALUE)num < 0;
2860 else if (RB_BIGNUM_TYPE_P(num)) {
2861 if (method_basic_p(rb_cInteger))
2862 return BIGNUM_NEGATIVE_P(num);
2865 r = rb_check_funcall(num, '>', 1, &zero);
2866 if (UNDEF_P(r)) {
2867 coerce_failed(num, INT2FIX(0));
2869 return !RTEST(r);
2872 static int
2873 num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2875 VALUE hash;
2877 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2878 if (!NIL_P(hash)) {
2879 ID keys[2];
2880 VALUE values[2];
2881 keys[0] = id_to;
2882 keys[1] = id_by;
2883 rb_get_kwargs(hash, keys, 0, 2, values);
2884 if (!UNDEF_P(values[0])) {
2885 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2886 *to = values[0];
2888 if (!UNDEF_P(values[1])) {
2889 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2890 *by = values[1];
2894 return argc;
2897 static int
2898 num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2900 int desc;
2901 if (!UNDEF_P(by)) {
2902 *step = by;
2904 else {
2905 /* compatibility */
2906 if (argc > 1 && NIL_P(*step)) {
2907 rb_raise(rb_eTypeError, "step must be numeric");
2910 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2911 rb_raise(rb_eArgError, "step can't be 0");
2913 if (NIL_P(*step)) {
2914 *step = INT2FIX(1);
2916 desc = num_step_negative_p(*step);
2917 if (fix_nil && NIL_P(*to)) {
2918 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2920 return desc;
2923 static int
2924 num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2926 VALUE by = Qundef;
2927 argc = num_step_extract_args(argc, argv, to, step, &by);
2928 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2931 static VALUE
2932 num_step_size(VALUE from, VALUE args, VALUE eobj)
2934 VALUE to, step;
2935 int argc = args ? RARRAY_LENINT(args) : 0;
2936 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2938 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2940 return ruby_num_interval_step_size(from, to, step, FALSE);
2944 * call-seq:
2945 * step(to = nil, by = 1) {|n| ... } -> self
2946 * step(to = nil, by = 1) -> enumerator
2947 * step(to = nil, by: 1) {|n| ... } -> self
2948 * step(to = nil, by: 1) -> enumerator
2949 * step(by: 1, to: ) {|n| ... } -> self
2950 * step(by: 1, to: ) -> enumerator
2951 * step(by: , to: nil) {|n| ... } -> self
2952 * step(by: , to: nil) -> enumerator
2954 * Generates a sequence of numbers; with a block given, traverses the sequence.
2956 * Of the Core and Standard Library classes,
2957 * Integer, Float, and Rational use this implementation.
2959 * A quick example:
2961 * squares = []
2962 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2963 * squares # => [1, 9, 25, 49, 81]
2965 * The generated sequence:
2967 * - Begins with +self+.
2968 * - Continues at intervals of +by+ (which may not be zero).
2969 * - Ends with the last number that is within or equal to +to+;
2970 * that is, less than or equal to +to+ if +by+ is positive,
2971 * greater than or equal to +to+ if +by+ is negative.
2972 * If +to+ is +nil+, the sequence is of infinite length.
2974 * If a block is given, calls the block with each number in the sequence;
2975 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2977 * <b>Keyword Arguments</b>
2979 * With keyword arguments +by+ and +to+,
2980 * their values (or defaults) determine the step and limit:
2982 * # Both keywords given.
2983 * squares = []
2984 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2985 * squares # => [16, 36, 64, 100]
2986 * cubes = []
2987 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2988 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2989 * squares = []
2990 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2991 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2993 * squares = []
2994 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2995 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2997 * # Only keyword to given.
2998 * squares = []
2999 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
3000 * squares # => [16, 25, 36, 49, 64, 81, 100]
3001 * # Only by given.
3003 * # Only keyword by given
3004 * squares = []
3005 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3006 * squares # => [16, 36, 64, 100, 144]
3008 * # No block given.
3009 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3010 * e.class # => Enumerator::ArithmeticSequence
3012 * <b>Positional Arguments</b>
3014 * With optional positional arguments +to+ and +by+,
3015 * their values (or defaults) determine the step and limit:
3017 * squares = []
3018 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3019 * squares # => [16, 36, 64, 100]
3020 * squares = []
3021 * 4.step(10) {|i| squares.push(i*i) }
3022 * squares # => [16, 25, 36, 49, 64, 81, 100]
3023 * squares = []
3024 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3025 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3027 * <b>Implementation Notes</b>
3029 * If all the arguments are integers, the loop operates using an integer
3030 * counter.
3032 * If any of the arguments are floating point numbers, all are converted
3033 * to floats, and the loop is executed
3034 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3035 * where <i>n = (limit - self)/step</i>.
3039 static VALUE
3040 num_step(int argc, VALUE *argv, VALUE from)
3042 VALUE to, step;
3043 int desc, inf;
3045 if (!rb_block_given_p()) {
3046 VALUE by = Qundef;
3048 num_step_extract_args(argc, argv, &to, &step, &by);
3049 if (!UNDEF_P(by)) {
3050 step = by;
3052 if (NIL_P(step)) {
3053 step = INT2FIX(1);
3055 else if (rb_equal(step, INT2FIX(0))) {
3056 rb_raise(rb_eArgError, "step can't be 0");
3058 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3059 rb_obj_is_kind_of(step, rb_cNumeric)) {
3060 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3061 num_step_size, from, to, step, FALSE);
3064 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3067 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3068 if (rb_equal(step, INT2FIX(0))) {
3069 inf = 1;
3071 else if (RB_FLOAT_TYPE_P(to)) {
3072 double f = RFLOAT_VALUE(to);
3073 inf = isinf(f) && (signbit(f) ? desc : !desc);
3075 else inf = 0;
3077 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3078 long i = FIX2LONG(from);
3079 long diff = FIX2LONG(step);
3081 if (inf) {
3082 for (;; i += diff)
3083 rb_yield(LONG2FIX(i));
3085 else {
3086 long end = FIX2LONG(to);
3088 if (desc) {
3089 for (; i >= end; i += diff)
3090 rb_yield(LONG2FIX(i));
3092 else {
3093 for (; i <= end; i += diff)
3094 rb_yield(LONG2FIX(i));
3098 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3099 VALUE i = from;
3101 if (inf) {
3102 for (;; i = rb_funcall(i, '+', 1, step))
3103 rb_yield(i);
3105 else {
3106 ID cmp = desc ? '<' : '>';
3108 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3109 rb_yield(i);
3112 return from;
3115 static char *
3116 out_of_range_float(char (*pbuf)[24], VALUE val)
3118 char *const buf = *pbuf;
3119 char *s;
3121 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3122 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3123 return buf;
3126 #define FLOAT_OUT_OF_RANGE(val, type) do { \
3127 char buf[24]; \
3128 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3129 out_of_range_float(&buf, (val))); \
3130 } while (0)
3132 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3133 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3134 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3135 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3136 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3137 LONG_MIN <= (n): \
3138 LONG_MIN_MINUS_ONE < (n))
3140 long
3141 rb_num2long(VALUE val)
3143 again:
3144 if (NIL_P(val)) {
3145 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3148 if (FIXNUM_P(val)) return FIX2LONG(val);
3150 else if (RB_FLOAT_TYPE_P(val)) {
3151 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3152 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3153 return (long)RFLOAT_VALUE(val);
3155 else {
3156 FLOAT_OUT_OF_RANGE(val, "integer");
3159 else if (RB_BIGNUM_TYPE_P(val)) {
3160 return rb_big2long(val);
3162 else {
3163 val = rb_to_int(val);
3164 goto again;
3168 static unsigned long
3169 rb_num2ulong_internal(VALUE val, int *wrap_p)
3171 again:
3172 if (NIL_P(val)) {
3173 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3176 if (FIXNUM_P(val)) {
3177 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3178 if (wrap_p)
3179 *wrap_p = l < 0;
3180 return (unsigned long)l;
3182 else if (RB_FLOAT_TYPE_P(val)) {
3183 double d = RFLOAT_VALUE(val);
3184 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3185 if (wrap_p)
3186 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3187 if (0 <= d)
3188 return (unsigned long)d;
3189 return (unsigned long)(long)d;
3191 else {
3192 FLOAT_OUT_OF_RANGE(val, "integer");
3195 else if (RB_BIGNUM_TYPE_P(val)) {
3197 unsigned long ul = rb_big2ulong(val);
3198 if (wrap_p)
3199 *wrap_p = BIGNUM_NEGATIVE_P(val);
3200 return ul;
3203 else {
3204 val = rb_to_int(val);
3205 goto again;
3209 unsigned long
3210 rb_num2ulong(VALUE val)
3212 return rb_num2ulong_internal(val, NULL);
3215 void
3216 rb_out_of_int(SIGNED_VALUE num)
3218 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3219 num, num < 0 ? "small" : "big");
3222 #if SIZEOF_INT < SIZEOF_LONG
3223 static void
3224 check_int(long num)
3226 if ((long)(int)num != num) {
3227 rb_out_of_int(num);
3231 static void
3232 check_uint(unsigned long num, int sign)
3234 if (sign) {
3235 /* minus */
3236 if (num < (unsigned long)INT_MIN)
3237 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3239 else {
3240 /* plus */
3241 if (UINT_MAX < num)
3242 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3246 long
3247 rb_num2int(VALUE val)
3249 long num = rb_num2long(val);
3251 check_int(num);
3252 return num;
3255 long
3256 rb_fix2int(VALUE val)
3258 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3260 check_int(num);
3261 return num;
3264 unsigned long
3265 rb_num2uint(VALUE val)
3267 int wrap;
3268 unsigned long num = rb_num2ulong_internal(val, &wrap);
3270 check_uint(num, wrap);
3271 return num;
3274 unsigned long
3275 rb_fix2uint(VALUE val)
3277 unsigned long num;
3279 if (!FIXNUM_P(val)) {
3280 return rb_num2uint(val);
3282 num = FIX2ULONG(val);
3284 check_uint(num, FIXNUM_NEGATIVE_P(val));
3285 return num;
3287 #else
3288 long
3289 rb_num2int(VALUE val)
3291 return rb_num2long(val);
3294 long
3295 rb_fix2int(VALUE val)
3297 return FIX2INT(val);
3300 unsigned long
3301 rb_num2uint(VALUE val)
3303 return rb_num2ulong(val);
3306 unsigned long
3307 rb_fix2uint(VALUE val)
3309 return RB_FIX2ULONG(val);
3311 #endif
3313 NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3314 static void
3315 rb_out_of_short(SIGNED_VALUE num)
3317 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3318 num, num < 0 ? "small" : "big");
3321 static void
3322 check_short(long num)
3324 if ((long)(short)num != num) {
3325 rb_out_of_short(num);
3329 static void
3330 check_ushort(unsigned long num, int sign)
3332 if (sign) {
3333 /* minus */
3334 if (num < (unsigned long)SHRT_MIN)
3335 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3337 else {
3338 /* plus */
3339 if (USHRT_MAX < num)
3340 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3344 short
3345 rb_num2short(VALUE val)
3347 long num = rb_num2long(val);
3349 check_short(num);
3350 return num;
3353 short
3354 rb_fix2short(VALUE val)
3356 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3358 check_short(num);
3359 return num;
3362 unsigned short
3363 rb_num2ushort(VALUE val)
3365 int wrap;
3366 unsigned long num = rb_num2ulong_internal(val, &wrap);
3368 check_ushort(num, wrap);
3369 return num;
3372 unsigned short
3373 rb_fix2ushort(VALUE val)
3375 unsigned long num;
3377 if (!FIXNUM_P(val)) {
3378 return rb_num2ushort(val);
3380 num = FIX2ULONG(val);
3382 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3383 return num;
3386 VALUE
3387 rb_num2fix(VALUE val)
3389 long v;
3391 if (FIXNUM_P(val)) return val;
3393 v = rb_num2long(val);
3394 if (!FIXABLE(v))
3395 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3396 return LONG2FIX(v);
3399 #if HAVE_LONG_LONG
3401 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3402 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3403 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3404 #ifndef ULLONG_MAX
3405 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3406 #endif
3407 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3408 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3409 LLONG_MIN <= (n): \
3410 LLONG_MIN_MINUS_ONE < (n))
3412 LONG_LONG
3413 rb_num2ll(VALUE val)
3415 if (NIL_P(val)) {
3416 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3419 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3421 else if (RB_FLOAT_TYPE_P(val)) {
3422 double d = RFLOAT_VALUE(val);
3423 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3424 return (LONG_LONG)d;
3426 else {
3427 FLOAT_OUT_OF_RANGE(val, "long long");
3430 else if (RB_BIGNUM_TYPE_P(val)) {
3431 return rb_big2ll(val);
3433 else if (RB_TYPE_P(val, T_STRING)) {
3434 rb_raise(rb_eTypeError, "no implicit conversion from string");
3436 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3437 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3440 val = rb_to_int(val);
3441 return NUM2LL(val);
3444 unsigned LONG_LONG
3445 rb_num2ull(VALUE val)
3447 if (NIL_P(val)) {
3448 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3450 else if (FIXNUM_P(val)) {
3451 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3453 else if (RB_FLOAT_TYPE_P(val)) {
3454 double d = RFLOAT_VALUE(val);
3455 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3456 if (0 <= d)
3457 return (unsigned LONG_LONG)d;
3458 return (unsigned LONG_LONG)(LONG_LONG)d;
3460 else {
3461 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3464 else if (RB_BIGNUM_TYPE_P(val)) {
3465 return rb_big2ull(val);
3467 else {
3468 val = rb_to_int(val);
3469 return NUM2ULL(val);
3473 #endif /* HAVE_LONG_LONG */
3475 /********************************************************************
3477 * Document-class: Integer
3479 * An \Integer object represents an integer value.
3481 * You can create an \Integer object explicitly with:
3483 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3485 * You can convert certain objects to Integers with:
3487 * - \Method #Integer.
3489 * An attempt to add a singleton method to an instance of this class
3490 * causes an exception to be raised.
3492 * == What's Here
3494 * First, what's elsewhere. \Class \Integer:
3496 * - Inherits from
3497 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3498 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3499 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3501 * Here, class \Integer provides methods for:
3503 * - {Querying}[rdoc-ref:Integer@Querying]
3504 * - {Comparing}[rdoc-ref:Integer@Comparing]
3505 * - {Converting}[rdoc-ref:Integer@Converting]
3506 * - {Other}[rdoc-ref:Integer@Other]
3508 * === Querying
3510 * - #allbits?: Returns whether all bits in +self+ are set.
3511 * - #anybits?: Returns whether any bits in +self+ are set.
3512 * - #nobits?: Returns whether no bits in +self+ are set.
3514 * === Comparing
3516 * - #<: Returns whether +self+ is less than the given value.
3517 * - #<=: Returns whether +self+ is less than or equal to the given value.
3518 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3519 * to, or greater than the given value.
3520 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3521 * value.
3522 * - #>: Returns whether +self+ is greater than the given value.
3523 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3525 * === Converting
3527 * - ::sqrt: Returns the integer square root of the given value.
3528 * - ::try_convert: Returns the given value converted to an \Integer.
3529 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3530 * - #&: Returns the bitwise AND of +self+ and the given value.
3531 * - #*: Returns the product of +self+ and the given value.
3532 * - #**: Returns the value of +self+ raised to the power of the given value.
3533 * - #+: Returns the sum of +self+ and the given value.
3534 * - #-: Returns the difference of +self+ and the given value.
3535 * - #/: Returns the quotient of +self+ and the given value.
3536 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3537 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3538 * - #[]: Returns a slice of bits from +self+.
3539 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3540 * - #ceil: Returns the smallest number greater than or equal to +self+.
3541 * - #chr: Returns a 1-character string containing the character
3542 * represented by the value of +self+.
3543 * - #digits: Returns an array of integers representing the base-radix digits
3544 * of +self+.
3545 * - #div: Returns the integer result of dividing +self+ by the given value.
3546 * - #divmod: Returns a 2-element array containing the quotient and remainder
3547 * results of dividing +self+ by the given value.
3548 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3549 * - #floor: Returns the greatest number smaller than or equal to +self+.
3550 * - #pow: Returns the modular exponentiation of +self+.
3551 * - #pred: Returns the integer predecessor of +self+.
3552 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3553 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3554 * - #succ (aliased as #next): Returns the integer successor of +self+.
3555 * - #to_f: Returns +self+ converted to a Float.
3556 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3557 * representation of +self+ in the given radix.
3558 * - #truncate: Returns +self+ truncated to the given precision.
3559 * - #|: Returns the bitwise OR of +self+ and the given value.
3561 * === Other
3563 * - #downto: Calls the given block with each integer value from +self+
3564 * down to the given value.
3565 * - #times: Calls the given block +self+ times with each integer
3566 * in <tt>(0..self-1)</tt>.
3567 * - #upto: Calls the given block with each integer value from +self+
3568 * up to the given value.
3572 VALUE
3573 rb_int_odd_p(VALUE num)
3575 if (FIXNUM_P(num)) {
3576 return RBOOL(num & 2);
3578 else {
3579 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3580 return rb_big_odd_p(num);
3584 static VALUE
3585 int_even_p(VALUE num)
3587 if (FIXNUM_P(num)) {
3588 return RBOOL((num & 2) == 0);
3590 else {
3591 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3592 return rb_big_even_p(num);
3596 VALUE
3597 rb_int_even_p(VALUE num)
3599 return int_even_p(num);
3603 * call-seq:
3604 * allbits?(mask) -> true or false
3606 * Returns +true+ if all bits that are set (=1) in +mask+
3607 * are also set in +self+; returns +false+ otherwise.
3609 * Example values:
3611 * 0b1010101 self
3612 * 0b1010100 mask
3613 * 0b1010100 self & mask
3614 * true self.allbits?(mask)
3616 * 0b1010100 self
3617 * 0b1010101 mask
3618 * 0b1010100 self & mask
3619 * false self.allbits?(mask)
3621 * Related: Integer#anybits?, Integer#nobits?.
3625 static VALUE
3626 int_allbits_p(VALUE num, VALUE mask)
3628 mask = rb_to_int(mask);
3629 return rb_int_equal(rb_int_and(num, mask), mask);
3633 * call-seq:
3634 * anybits?(mask) -> true or false
3636 * Returns +true+ if any bit that is set (=1) in +mask+
3637 * is also set in +self+; returns +false+ otherwise.
3639 * Example values:
3641 * 0b10000010 self
3642 * 0b11111111 mask
3643 * 0b10000010 self & mask
3644 * true self.anybits?(mask)
3646 * 0b00000000 self
3647 * 0b11111111 mask
3648 * 0b00000000 self & mask
3649 * false self.anybits?(mask)
3651 * Related: Integer#allbits?, Integer#nobits?.
3655 static VALUE
3656 int_anybits_p(VALUE num, VALUE mask)
3658 mask = rb_to_int(mask);
3659 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3663 * call-seq:
3664 * nobits?(mask) -> true or false
3666 * Returns +true+ if no bit that is set (=1) in +mask+
3667 * is also set in +self+; returns +false+ otherwise.
3669 * Example values:
3671 * 0b11110000 self
3672 * 0b00001111 mask
3673 * 0b00000000 self & mask
3674 * true self.nobits?(mask)
3676 * 0b00000001 self
3677 * 0b11111111 mask
3678 * 0b00000001 self & mask
3679 * false self.nobits?(mask)
3681 * Related: Integer#allbits?, Integer#anybits?.
3685 static VALUE
3686 int_nobits_p(VALUE num, VALUE mask)
3688 mask = rb_to_int(mask);
3689 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3693 * call-seq:
3694 * succ -> next_integer
3696 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3698 * 1.succ #=> 2
3699 * -1.succ #=> 0
3701 * Related: Integer#pred (predecessor value).
3704 VALUE
3705 rb_int_succ(VALUE num)
3707 if (FIXNUM_P(num)) {
3708 long i = FIX2LONG(num) + 1;
3709 return LONG2NUM(i);
3711 if (RB_BIGNUM_TYPE_P(num)) {
3712 return rb_big_plus(num, INT2FIX(1));
3714 return num_funcall1(num, '+', INT2FIX(1));
3717 #define int_succ rb_int_succ
3720 * call-seq:
3721 * pred -> next_integer
3723 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3725 * 1.pred #=> 0
3726 * -1.pred #=> -2
3728 * Related: Integer#succ (successor value).
3732 static VALUE
3733 rb_int_pred(VALUE num)
3735 if (FIXNUM_P(num)) {
3736 long i = FIX2LONG(num) - 1;
3737 return LONG2NUM(i);
3739 if (RB_BIGNUM_TYPE_P(num)) {
3740 return rb_big_minus(num, INT2FIX(1));
3742 return num_funcall1(num, '-', INT2FIX(1));
3745 #define int_pred rb_int_pred
3747 VALUE
3748 rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3750 int n;
3751 VALUE str;
3752 switch (n = rb_enc_codelen(code, enc)) {
3753 case ONIGERR_INVALID_CODE_POINT_VALUE:
3754 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3755 break;
3756 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3757 case 0:
3758 rb_raise(rb_eRangeError, "%u out of char range", code);
3759 break;
3761 str = rb_enc_str_new(0, n, enc);
3762 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3763 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3764 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3766 return str;
3769 /* call-seq:
3770 * chr -> string
3771 * chr(encoding) -> string
3773 * Returns a 1-character string containing the character
3774 * represented by the value of +self+, according to the given +encoding+.
3776 * 65.chr # => "A"
3777 * 0.chr # => "\x00"
3778 * 255.chr # => "\xFF"
3779 * string = 255.chr(Encoding::UTF_8)
3780 * string.encoding # => Encoding::UTF_8
3782 * Raises an exception if +self+ is negative.
3784 * Related: Integer#ord.
3788 static VALUE
3789 int_chr(int argc, VALUE *argv, VALUE num)
3791 char c;
3792 unsigned int i;
3793 rb_encoding *enc;
3795 if (rb_num_to_uint(num, &i) == 0) {
3797 else if (FIXNUM_P(num)) {
3798 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3800 else {
3801 rb_raise(rb_eRangeError, "bignum out of char range");
3804 switch (argc) {
3805 case 0:
3806 if (0xff < i) {
3807 enc = rb_default_internal_encoding();
3808 if (!enc) {
3809 rb_raise(rb_eRangeError, "%u out of char range", i);
3811 goto decode;
3813 c = (char)i;
3814 if (i < 0x80) {
3815 return rb_usascii_str_new(&c, 1);
3817 else {
3818 return rb_str_new(&c, 1);
3820 case 1:
3821 break;
3822 default:
3823 rb_error_arity(argc, 0, 1);
3825 enc = rb_to_encoding(argv[0]);
3826 if (!enc) enc = rb_ascii8bit_encoding();
3827 decode:
3828 return rb_enc_uint_chr(i, enc);
3832 * Fixnum
3835 static VALUE
3836 fix_uminus(VALUE num)
3838 return LONG2NUM(-FIX2LONG(num));
3841 VALUE
3842 rb_int_uminus(VALUE num)
3844 if (FIXNUM_P(num)) {
3845 return fix_uminus(num);
3847 else {
3848 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3849 return rb_big_uminus(num);
3853 VALUE
3854 rb_fix2str(VALUE x, int base)
3856 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3857 long val = FIX2LONG(x);
3858 unsigned long u;
3859 int neg = 0;
3861 if (base < 2 || 36 < base) {
3862 rb_raise(rb_eArgError, "invalid radix %d", base);
3864 #if SIZEOF_LONG < SIZEOF_VOIDP
3865 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3866 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
3867 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
3868 rb_bug("Unnormalized Fixnum value %p", (void *)x);
3870 # else
3871 /* should do something like above code, but currently ruby does not know */
3872 /* such platforms */
3873 # endif
3874 #endif
3875 if (val == 0) {
3876 return rb_usascii_str_new2("0");
3878 if (val < 0) {
3879 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3880 neg = 1;
3882 else {
3883 u = val;
3885 do {
3886 *--b = ruby_digitmap[(int)(u % base)];
3887 } while (u /= base);
3888 if (neg) {
3889 *--b = '-';
3892 return rb_usascii_str_new(b, e - b);
3895 static VALUE rb_fix_to_s_static[10];
3897 VALUE
3898 rb_fix_to_s(VALUE x)
3900 long i = FIX2LONG(x);
3901 if (i >= 0 && i < 10) {
3902 return rb_fix_to_s_static[i];
3904 return rb_fix2str(x, 10);
3908 * call-seq:
3909 * to_s(base = 10) -> string
3911 * Returns a string containing the place-value representation of +self+
3912 * in radix +base+ (in 2..36).
3914 * 12345.to_s # => "12345"
3915 * 12345.to_s(2) # => "11000000111001"
3916 * 12345.to_s(8) # => "30071"
3917 * 12345.to_s(10) # => "12345"
3918 * 12345.to_s(16) # => "3039"
3919 * 12345.to_s(36) # => "9ix"
3920 * 78546939656932.to_s(36) # => "rubyrules"
3922 * Raises an exception if +base+ is out of range.
3925 VALUE
3926 rb_int_to_s(int argc, VALUE *argv, VALUE x)
3928 int base;
3930 if (rb_check_arity(argc, 0, 1))
3931 base = NUM2INT(argv[0]);
3932 else
3933 base = 10;
3934 return rb_int2str(x, base);
3937 VALUE
3938 rb_int2str(VALUE x, int base)
3940 if (FIXNUM_P(x)) {
3941 return rb_fix2str(x, base);
3943 else if (RB_BIGNUM_TYPE_P(x)) {
3944 return rb_big2str(x, base);
3947 return rb_any_to_s(x);
3950 static VALUE
3951 fix_plus(VALUE x, VALUE y)
3953 if (FIXNUM_P(y)) {
3954 return rb_fix_plus_fix(x, y);
3956 else if (RB_BIGNUM_TYPE_P(y)) {
3957 return rb_big_plus(y, x);
3959 else if (RB_FLOAT_TYPE_P(y)) {
3960 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
3962 else if (RB_TYPE_P(y, T_COMPLEX)) {
3963 return rb_complex_plus(y, x);
3965 else {
3966 return rb_num_coerce_bin(x, y, '+');
3970 VALUE
3971 rb_fix_plus(VALUE x, VALUE y)
3973 return fix_plus(x, y);
3977 * call-seq:
3978 * self + numeric -> numeric_result
3980 * Performs addition:
3982 * 2 + 2 # => 4
3983 * -2 + 2 # => 0
3984 * -2 + -2 # => -4
3985 * 2 + 2.0 # => 4.0
3986 * 2 + Rational(2, 1) # => (4/1)
3987 * 2 + Complex(2, 0) # => (4+0i)
3991 VALUE
3992 rb_int_plus(VALUE x, VALUE y)
3994 if (FIXNUM_P(x)) {
3995 return fix_plus(x, y);
3997 else if (RB_BIGNUM_TYPE_P(x)) {
3998 return rb_big_plus(x, y);
4000 return rb_num_coerce_bin(x, y, '+');
4003 static VALUE
4004 fix_minus(VALUE x, VALUE y)
4006 if (FIXNUM_P(y)) {
4007 return rb_fix_minus_fix(x, y);
4009 else if (RB_BIGNUM_TYPE_P(y)) {
4010 x = rb_int2big(FIX2LONG(x));
4011 return rb_big_minus(x, y);
4013 else if (RB_FLOAT_TYPE_P(y)) {
4014 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4016 else {
4017 return rb_num_coerce_bin(x, y, '-');
4022 * call-seq:
4023 * self - numeric -> numeric_result
4025 * Performs subtraction:
4027 * 4 - 2 # => 2
4028 * -4 - 2 # => -6
4029 * -4 - -2 # => -2
4030 * 4 - 2.0 # => 2.0
4031 * 4 - Rational(2, 1) # => (2/1)
4032 * 4 - Complex(2, 0) # => (2+0i)
4036 VALUE
4037 rb_int_minus(VALUE x, VALUE y)
4039 if (FIXNUM_P(x)) {
4040 return fix_minus(x, y);
4042 else if (RB_BIGNUM_TYPE_P(x)) {
4043 return rb_big_minus(x, y);
4045 return rb_num_coerce_bin(x, y, '-');
4049 #define SQRT_LONG_MAX HALF_LONG_MSB
4050 /*tests if N*N would overflow*/
4051 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4053 static VALUE
4054 fix_mul(VALUE x, VALUE y)
4056 if (FIXNUM_P(y)) {
4057 return rb_fix_mul_fix(x, y);
4059 else if (RB_BIGNUM_TYPE_P(y)) {
4060 switch (x) {
4061 case INT2FIX(0): return x;
4062 case INT2FIX(1): return y;
4064 return rb_big_mul(y, x);
4066 else if (RB_FLOAT_TYPE_P(y)) {
4067 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4069 else if (RB_TYPE_P(y, T_COMPLEX)) {
4070 return rb_complex_mul(y, x);
4072 else {
4073 return rb_num_coerce_bin(x, y, '*');
4078 * call-seq:
4079 * self * numeric -> numeric_result
4081 * Performs multiplication:
4083 * 4 * 2 # => 8
4084 * 4 * -2 # => -8
4085 * -4 * 2 # => -8
4086 * 4 * 2.0 # => 8.0
4087 * 4 * Rational(1, 3) # => (4/3)
4088 * 4 * Complex(2, 0) # => (8+0i)
4091 VALUE
4092 rb_int_mul(VALUE x, VALUE y)
4094 if (FIXNUM_P(x)) {
4095 return fix_mul(x, y);
4097 else if (RB_BIGNUM_TYPE_P(x)) {
4098 return rb_big_mul(x, y);
4100 return rb_num_coerce_bin(x, y, '*');
4103 static double
4104 fix_fdiv_double(VALUE x, VALUE y)
4106 if (FIXNUM_P(y)) {
4107 long iy = FIX2LONG(y);
4108 #if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4109 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4110 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4112 #endif
4113 return double_div_double(FIX2LONG(x), iy);
4115 else if (RB_BIGNUM_TYPE_P(y)) {
4116 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4118 else if (RB_FLOAT_TYPE_P(y)) {
4119 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4121 else {
4122 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4126 double
4127 rb_int_fdiv_double(VALUE x, VALUE y)
4129 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y)) {
4130 VALUE gcd = rb_gcd(x, y);
4131 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4132 x = rb_int_idiv(x, gcd);
4133 y = rb_int_idiv(y, gcd);
4136 if (FIXNUM_P(x)) {
4137 return fix_fdiv_double(x, y);
4139 else if (RB_BIGNUM_TYPE_P(x)) {
4140 return rb_big_fdiv_double(x, y);
4142 else {
4143 return nan("");
4148 * call-seq:
4149 * fdiv(numeric) -> float
4151 * Returns the Float result of dividing +self+ by +numeric+:
4153 * 4.fdiv(2) # => 2.0
4154 * 4.fdiv(-2) # => -2.0
4155 * -4.fdiv(2) # => -2.0
4156 * 4.fdiv(2.0) # => 2.0
4157 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4159 * Raises an exception if +numeric+ cannot be converted to a Float.
4163 VALUE
4164 rb_int_fdiv(VALUE x, VALUE y)
4166 if (RB_INTEGER_TYPE_P(x)) {
4167 return DBL2NUM(rb_int_fdiv_double(x, y));
4169 return Qnil;
4172 static VALUE
4173 fix_divide(VALUE x, VALUE y, ID op)
4175 if (FIXNUM_P(y)) {
4176 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4177 return rb_fix_div_fix(x, y);
4179 else if (RB_BIGNUM_TYPE_P(y)) {
4180 x = rb_int2big(FIX2LONG(x));
4181 return rb_big_div(x, y);
4183 else if (RB_FLOAT_TYPE_P(y)) {
4184 if (op == '/') {
4185 double d = FIX2LONG(x);
4186 return rb_flo_div_flo(DBL2NUM(d), y);
4188 else {
4189 VALUE v;
4190 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4191 v = fix_divide(x, y, '/');
4192 return flo_floor(0, 0, v);
4195 else {
4196 if (RB_TYPE_P(y, T_RATIONAL) &&
4197 op == '/' && FIX2LONG(x) == 1)
4198 return rb_rational_reciprocal(y);
4199 return rb_num_coerce_bin(x, y, op);
4203 static VALUE
4204 fix_div(VALUE x, VALUE y)
4206 return fix_divide(x, y, '/');
4210 * call-seq:
4211 * self / numeric -> numeric_result
4213 * Performs division; for integer +numeric+, truncates the result to an integer:
4215 * 4 / 3 # => 1
4216 * 4 / -3 # => -2
4217 * -4 / 3 # => -2
4218 * -4 / -3 # => 1
4220 * For other +numeric+, returns non-integer result:
4222 * 4 / 3.0 # => 1.3333333333333333
4223 * 4 / Rational(3, 1) # => (4/3)
4224 * 4 / Complex(3, 0) # => ((4/3)+0i)
4228 VALUE
4229 rb_int_div(VALUE x, VALUE y)
4231 if (FIXNUM_P(x)) {
4232 return fix_div(x, y);
4234 else if (RB_BIGNUM_TYPE_P(x)) {
4235 return rb_big_div(x, y);
4237 return Qnil;
4240 static VALUE
4241 fix_idiv(VALUE x, VALUE y)
4243 return fix_divide(x, y, id_div);
4247 * call-seq:
4248 * div(numeric) -> integer
4250 * Performs integer division; returns the integer result of dividing +self+
4251 * by +numeric+:
4253 * 4.div(3) # => 1
4254 * 4.div(-3) # => -2
4255 * -4.div(3) # => -2
4256 * -4.div(-3) # => 1
4257 * 4.div(3.0) # => 1
4258 * 4.div(Rational(3, 1)) # => 1
4260 * Raises an exception if +numeric+ does not have method +div+.
4264 VALUE
4265 rb_int_idiv(VALUE x, VALUE y)
4267 if (FIXNUM_P(x)) {
4268 return fix_idiv(x, y);
4270 else if (RB_BIGNUM_TYPE_P(x)) {
4271 return rb_big_idiv(x, y);
4273 return num_div(x, y);
4276 static VALUE
4277 fix_mod(VALUE x, VALUE y)
4279 if (FIXNUM_P(y)) {
4280 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4281 return rb_fix_mod_fix(x, y);
4283 else if (RB_BIGNUM_TYPE_P(y)) {
4284 x = rb_int2big(FIX2LONG(x));
4285 return rb_big_modulo(x, y);
4287 else if (RB_FLOAT_TYPE_P(y)) {
4288 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4290 else {
4291 return rb_num_coerce_bin(x, y, '%');
4296 * call-seq:
4297 * self % other -> real_number
4299 * Returns +self+ modulo +other+ as a real number.
4301 * For integer +n+ and real number +r+, these expressions are equivalent:
4303 * n % r
4304 * n-r*(n/r).floor
4305 * n.divmod(r)[1]
4307 * See Numeric#divmod.
4309 * Examples:
4311 * 10 % 2 # => 0
4312 * 10 % 3 # => 1
4313 * 10 % 4 # => 2
4315 * 10 % -2 # => 0
4316 * 10 % -3 # => -2
4317 * 10 % -4 # => -2
4319 * 10 % 3.0 # => 1.0
4320 * 10 % Rational(3, 1) # => (1/1)
4323 VALUE
4324 rb_int_modulo(VALUE x, VALUE y)
4326 if (FIXNUM_P(x)) {
4327 return fix_mod(x, y);
4329 else if (RB_BIGNUM_TYPE_P(x)) {
4330 return rb_big_modulo(x, y);
4332 return num_modulo(x, y);
4336 * call-seq:
4337 * remainder(other) -> real_number
4339 * Returns the remainder after dividing +self+ by +other+.
4341 * Examples:
4343 * 11.remainder(4) # => 3
4344 * 11.remainder(-4) # => 3
4345 * -11.remainder(4) # => -3
4346 * -11.remainder(-4) # => -3
4348 * 12.remainder(4) # => 0
4349 * 12.remainder(-4) # => 0
4350 * -12.remainder(4) # => 0
4351 * -12.remainder(-4) # => 0
4353 * 13.remainder(4.0) # => 1.0
4354 * 13.remainder(Rational(4, 1)) # => (1/1)
4358 static VALUE
4359 int_remainder(VALUE x, VALUE y)
4361 if (FIXNUM_P(x)) {
4362 if (FIXNUM_P(y)) {
4363 VALUE z = fix_mod(x, y);
4364 RUBY_ASSERT(FIXNUM_P(z));
4365 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4366 z = fix_minus(z, y);
4367 return z;
4369 else if (!RB_BIGNUM_TYPE_P(y)) {
4370 return num_remainder(x, y);
4372 x = rb_int2big(FIX2LONG(x));
4374 else if (!RB_BIGNUM_TYPE_P(x)) {
4375 return Qnil;
4377 return rb_big_remainder(x, y);
4380 static VALUE
4381 fix_divmod(VALUE x, VALUE y)
4383 if (FIXNUM_P(y)) {
4384 VALUE div, mod;
4385 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4386 rb_fix_divmod_fix(x, y, &div, &mod);
4387 return rb_assoc_new(div, mod);
4389 else if (RB_BIGNUM_TYPE_P(y)) {
4390 x = rb_int2big(FIX2LONG(x));
4391 return rb_big_divmod(x, y);
4393 else if (RB_FLOAT_TYPE_P(y)) {
4395 double div, mod;
4396 volatile VALUE a, b;
4398 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4399 a = dbl2ival(div);
4400 b = DBL2NUM(mod);
4401 return rb_assoc_new(a, b);
4404 else {
4405 return rb_num_coerce_bin(x, y, id_divmod);
4410 * call-seq:
4411 * divmod(other) -> array
4413 * Returns a 2-element array <tt>[q, r]</tt>, where
4415 * q = (self/other).floor # Quotient
4416 * r = self % other # Remainder
4418 * Examples:
4420 * 11.divmod(4) # => [2, 3]
4421 * 11.divmod(-4) # => [-3, -1]
4422 * -11.divmod(4) # => [-3, 1]
4423 * -11.divmod(-4) # => [2, -3]
4425 * 12.divmod(4) # => [3, 0]
4426 * 12.divmod(-4) # => [-3, 0]
4427 * -12.divmod(4) # => [-3, 0]
4428 * -12.divmod(-4) # => [3, 0]
4430 * 13.divmod(4.0) # => [3, 1.0]
4431 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4434 VALUE
4435 rb_int_divmod(VALUE x, VALUE y)
4437 if (FIXNUM_P(x)) {
4438 return fix_divmod(x, y);
4440 else if (RB_BIGNUM_TYPE_P(x)) {
4441 return rb_big_divmod(x, y);
4443 return Qnil;
4447 * call-seq:
4448 * self ** numeric -> numeric_result
4450 * Raises +self+ to the power of +numeric+:
4452 * 2 ** 3 # => 8
4453 * 2 ** -3 # => (1/8)
4454 * -2 ** 3 # => -8
4455 * -2 ** -3 # => (-1/8)
4456 * 2 ** 3.3 # => 9.849155306759329
4457 * 2 ** Rational(3, 1) # => (8/1)
4458 * 2 ** Complex(3, 0) # => (8+0i)
4462 static VALUE
4463 int_pow(long x, unsigned long y)
4465 int neg = x < 0;
4466 long z = 1;
4468 if (y == 0) return INT2FIX(1);
4469 if (y == 1) return LONG2NUM(x);
4470 if (neg) x = -x;
4471 if (y & 1)
4472 z = x;
4473 else
4474 neg = 0;
4475 y &= ~1;
4476 do {
4477 while (y % 2 == 0) {
4478 if (!FIT_SQRT_LONG(x)) {
4479 goto bignum;
4481 x = x * x;
4482 y >>= 1;
4485 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4486 goto bignum;
4488 z = x * z;
4490 } while (--y);
4491 if (neg) z = -z;
4492 return LONG2NUM(z);
4494 VALUE v;
4495 bignum:
4496 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4497 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4498 return v;
4499 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4500 return v;
4503 VALUE
4504 rb_int_positive_pow(long x, unsigned long y)
4506 return int_pow(x, y);
4509 static VALUE
4510 fix_pow_inverted(VALUE x, VALUE minusb)
4512 if (x == INT2FIX(0)) {
4513 rb_num_zerodiv();
4514 UNREACHABLE_RETURN(Qundef);
4516 else {
4517 VALUE y = rb_int_pow(x, minusb);
4519 if (RB_FLOAT_TYPE_P(y)) {
4520 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4521 return DBL2NUM(1.0 / d);
4523 else {
4524 return rb_rational_raw(INT2FIX(1), y);
4529 static VALUE
4530 fix_pow(VALUE x, VALUE y)
4532 long a = FIX2LONG(x);
4534 if (FIXNUM_P(y)) {
4535 long b = FIX2LONG(y);
4537 if (a == 1) return INT2FIX(1);
4538 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4539 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4540 if (b == 0) return INT2FIX(1);
4541 if (b == 1) return x;
4542 if (a == 0) return INT2FIX(0);
4543 return int_pow(a, b);
4545 else if (RB_BIGNUM_TYPE_P(y)) {
4546 if (a == 1) return INT2FIX(1);
4547 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4548 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4549 if (a == 0) return INT2FIX(0);
4550 x = rb_int2big(FIX2LONG(x));
4551 return rb_big_pow(x, y);
4553 else if (RB_FLOAT_TYPE_P(y)) {
4554 double dy = RFLOAT_VALUE(y);
4555 if (dy == 0.0) return DBL2NUM(1.0);
4556 if (a == 0) {
4557 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4559 if (a == 1) return DBL2NUM(1.0);
4560 if (a < 0 && dy != round(dy))
4561 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4562 return DBL2NUM(pow((double)a, dy));
4564 else {
4565 return rb_num_coerce_bin(x, y, idPow);
4570 * call-seq:
4571 * self ** numeric -> numeric_result
4573 * Raises +self+ to the power of +numeric+:
4575 * 2 ** 3 # => 8
4576 * 2 ** -3 # => (1/8)
4577 * -2 ** 3 # => -8
4578 * -2 ** -3 # => (-1/8)
4579 * 2 ** 3.3 # => 9.849155306759329
4580 * 2 ** Rational(3, 1) # => (8/1)
4581 * 2 ** Complex(3, 0) # => (8+0i)
4584 VALUE
4585 rb_int_pow(VALUE x, VALUE y)
4587 if (FIXNUM_P(x)) {
4588 return fix_pow(x, y);
4590 else if (RB_BIGNUM_TYPE_P(x)) {
4591 return rb_big_pow(x, y);
4593 return Qnil;
4596 VALUE
4597 rb_num_pow(VALUE x, VALUE y)
4599 VALUE z = rb_int_pow(x, y);
4600 if (!NIL_P(z)) return z;
4601 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4602 if (SPECIAL_CONST_P(x)) return Qnil;
4603 switch (BUILTIN_TYPE(x)) {
4604 case T_COMPLEX:
4605 return rb_complex_pow(x, y);
4606 case T_RATIONAL:
4607 return rb_rational_pow(x, y);
4608 default:
4609 break;
4611 return Qnil;
4614 static VALUE
4615 fix_equal(VALUE x, VALUE y)
4617 if (x == y) return Qtrue;
4618 if (FIXNUM_P(y)) return Qfalse;
4619 else if (RB_BIGNUM_TYPE_P(y)) {
4620 return rb_big_eq(y, x);
4622 else if (RB_FLOAT_TYPE_P(y)) {
4623 return rb_integer_float_eq(x, y);
4625 else {
4626 return num_equal(x, y);
4631 * call-seq:
4632 * self == other -> true or false
4634 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4636 * 1 == 2 #=> false
4637 * 1 == 1.0 #=> true
4639 * Related: Integer#eql? (requires +other+ to be an \Integer).
4642 VALUE
4643 rb_int_equal(VALUE x, VALUE y)
4645 if (FIXNUM_P(x)) {
4646 return fix_equal(x, y);
4648 else if (RB_BIGNUM_TYPE_P(x)) {
4649 return rb_big_eq(x, y);
4651 return Qnil;
4654 static VALUE
4655 fix_cmp(VALUE x, VALUE y)
4657 if (x == y) return INT2FIX(0);
4658 if (FIXNUM_P(y)) {
4659 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4660 return INT2FIX(-1);
4662 else if (RB_BIGNUM_TYPE_P(y)) {
4663 VALUE cmp = rb_big_cmp(y, x);
4664 switch (cmp) {
4665 case INT2FIX(+1): return INT2FIX(-1);
4666 case INT2FIX(-1): return INT2FIX(+1);
4668 return cmp;
4670 else if (RB_FLOAT_TYPE_P(y)) {
4671 return rb_integer_float_cmp(x, y);
4673 else {
4674 return rb_num_coerce_cmp(x, y, id_cmp);
4679 * call-seq:
4680 * self <=> other -> -1, 0, +1, or nil
4682 * Returns:
4684 * - -1, if +self+ is less than +other+.
4685 * - 0, if +self+ is equal to +other+.
4686 * - 1, if +self+ is greater then +other+.
4687 * - +nil+, if +self+ and +other+ are incomparable.
4689 * Examples:
4691 * 1 <=> 2 # => -1
4692 * 1 <=> 1 # => 0
4693 * 1 <=> 0 # => 1
4694 * 1 <=> 'foo' # => nil
4696 * 1 <=> 1.0 # => 0
4697 * 1 <=> Rational(1, 1) # => 0
4698 * 1 <=> Complex(1, 0) # => 0
4700 * This method is the basis for comparisons in module Comparable.
4704 VALUE
4705 rb_int_cmp(VALUE x, VALUE y)
4707 if (FIXNUM_P(x)) {
4708 return fix_cmp(x, y);
4710 else if (RB_BIGNUM_TYPE_P(x)) {
4711 return rb_big_cmp(x, y);
4713 else {
4714 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
4718 static VALUE
4719 fix_gt(VALUE x, VALUE y)
4721 if (FIXNUM_P(y)) {
4722 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4724 else if (RB_BIGNUM_TYPE_P(y)) {
4725 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4727 else if (RB_FLOAT_TYPE_P(y)) {
4728 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
4730 else {
4731 return rb_num_coerce_relop(x, y, '>');
4736 * call-seq:
4737 * self > other -> true or false
4739 * Returns +true+ if the value of +self+ is greater than that of +other+:
4741 * 1 > 0 # => true
4742 * 1 > 1 # => false
4743 * 1 > 2 # => false
4744 * 1 > 0.5 # => true
4745 * 1 > Rational(1, 2) # => true
4747 * Raises an exception if the comparison cannot be made.
4751 VALUE
4752 rb_int_gt(VALUE x, VALUE y)
4754 if (FIXNUM_P(x)) {
4755 return fix_gt(x, y);
4757 else if (RB_BIGNUM_TYPE_P(x)) {
4758 return rb_big_gt(x, y);
4760 return Qnil;
4763 static VALUE
4764 fix_ge(VALUE x, VALUE y)
4766 if (FIXNUM_P(y)) {
4767 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
4769 else if (RB_BIGNUM_TYPE_P(y)) {
4770 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
4772 else if (RB_FLOAT_TYPE_P(y)) {
4773 VALUE rel = rb_integer_float_cmp(x, y);
4774 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
4776 else {
4777 return rb_num_coerce_relop(x, y, idGE);
4782 * call-seq:
4783 * self >= real -> true or false
4785 * Returns +true+ if the value of +self+ is greater than or equal to
4786 * that of +other+:
4788 * 1 >= 0 # => true
4789 * 1 >= 1 # => true
4790 * 1 >= 2 # => false
4791 * 1 >= 0.5 # => true
4792 * 1 >= Rational(1, 2) # => true
4794 * Raises an exception if the comparison cannot be made.
4798 VALUE
4799 rb_int_ge(VALUE x, VALUE y)
4801 if (FIXNUM_P(x)) {
4802 return fix_ge(x, y);
4804 else if (RB_BIGNUM_TYPE_P(x)) {
4805 return rb_big_ge(x, y);
4807 return Qnil;
4810 static VALUE
4811 fix_lt(VALUE x, VALUE y)
4813 if (FIXNUM_P(y)) {
4814 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
4816 else if (RB_BIGNUM_TYPE_P(y)) {
4817 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
4819 else if (RB_FLOAT_TYPE_P(y)) {
4820 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
4822 else {
4823 return rb_num_coerce_relop(x, y, '<');
4828 * call-seq:
4829 * self < other -> true or false
4831 * Returns +true+ if the value of +self+ is less than that of +other+:
4833 * 1 < 0 # => false
4834 * 1 < 1 # => false
4835 * 1 < 2 # => true
4836 * 1 < 0.5 # => false
4837 * 1 < Rational(1, 2) # => false
4839 * Raises an exception if the comparison cannot be made.
4843 static VALUE
4844 int_lt(VALUE x, VALUE y)
4846 if (FIXNUM_P(x)) {
4847 return fix_lt(x, y);
4849 else if (RB_BIGNUM_TYPE_P(x)) {
4850 return rb_big_lt(x, y);
4852 return Qnil;
4855 static VALUE
4856 fix_le(VALUE x, VALUE y)
4858 if (FIXNUM_P(y)) {
4859 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
4861 else if (RB_BIGNUM_TYPE_P(y)) {
4862 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
4864 else if (RB_FLOAT_TYPE_P(y)) {
4865 VALUE rel = rb_integer_float_cmp(x, y);
4866 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
4868 else {
4869 return rb_num_coerce_relop(x, y, idLE);
4874 * call-seq:
4875 * self <= real -> true or false
4877 * Returns +true+ if the value of +self+ is less than or equal to
4878 * that of +other+:
4880 * 1 <= 0 # => false
4881 * 1 <= 1 # => true
4882 * 1 <= 2 # => true
4883 * 1 <= 0.5 # => false
4884 * 1 <= Rational(1, 2) # => false
4886 * Raises an exception if the comparison cannot be made.
4890 static VALUE
4891 int_le(VALUE x, VALUE y)
4893 if (FIXNUM_P(x)) {
4894 return fix_le(x, y);
4896 else if (RB_BIGNUM_TYPE_P(x)) {
4897 return rb_big_le(x, y);
4899 return Qnil;
4902 static VALUE
4903 fix_comp(VALUE num)
4905 return ~num | FIXNUM_FLAG;
4908 VALUE
4909 rb_int_comp(VALUE num)
4911 if (FIXNUM_P(num)) {
4912 return fix_comp(num);
4914 else if (RB_BIGNUM_TYPE_P(num)) {
4915 return rb_big_comp(num);
4917 return Qnil;
4920 static VALUE
4921 num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
4923 ID func = (ID)((VALUE *)arg)[0];
4924 VALUE x = ((VALUE *)arg)[1];
4925 if (recursive) {
4926 num_funcall_op_1_recursion(x, func, y);
4928 return rb_check_funcall(x, func, 1, &y);
4931 VALUE
4932 rb_num_coerce_bit(VALUE x, VALUE y, ID func)
4934 VALUE ret, args[3];
4936 args[0] = (VALUE)func;
4937 args[1] = x;
4938 args[2] = y;
4939 do_coerce(&args[1], &args[2], TRUE);
4940 ret = rb_exec_recursive_paired(num_funcall_bit_1,
4941 args[2], args[1], (VALUE)args);
4942 if (UNDEF_P(ret)) {
4943 /* show the original object, not coerced object */
4944 coerce_failed(x, y);
4946 return ret;
4949 static VALUE
4950 fix_and(VALUE x, VALUE y)
4952 if (FIXNUM_P(y)) {
4953 long val = FIX2LONG(x) & FIX2LONG(y);
4954 return LONG2NUM(val);
4957 if (RB_BIGNUM_TYPE_P(y)) {
4958 return rb_big_and(y, x);
4961 return rb_num_coerce_bit(x, y, '&');
4965 * call-seq:
4966 * self & other -> integer
4968 * Bitwise AND; each bit in the result is 1 if both corresponding bits
4969 * in +self+ and +other+ are 1, 0 otherwise:
4971 * "%04b" % (0b0101 & 0b0110) # => "0100"
4973 * Raises an exception if +other+ is not an \Integer.
4975 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
4979 VALUE
4980 rb_int_and(VALUE x, VALUE y)
4982 if (FIXNUM_P(x)) {
4983 return fix_and(x, y);
4985 else if (RB_BIGNUM_TYPE_P(x)) {
4986 return rb_big_and(x, y);
4988 return Qnil;
4991 static VALUE
4992 fix_or(VALUE x, VALUE y)
4994 if (FIXNUM_P(y)) {
4995 long val = FIX2LONG(x) | FIX2LONG(y);
4996 return LONG2NUM(val);
4999 if (RB_BIGNUM_TYPE_P(y)) {
5000 return rb_big_or(y, x);
5003 return rb_num_coerce_bit(x, y, '|');
5007 * call-seq:
5008 * self | other -> integer
5010 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5011 * in +self+ or +other+ is 1, 0 otherwise:
5013 * "%04b" % (0b0101 | 0b0110) # => "0111"
5015 * Raises an exception if +other+ is not an \Integer.
5017 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5021 static VALUE
5022 int_or(VALUE x, VALUE y)
5024 if (FIXNUM_P(x)) {
5025 return fix_or(x, y);
5027 else if (RB_BIGNUM_TYPE_P(x)) {
5028 return rb_big_or(x, y);
5030 return Qnil;
5033 static VALUE
5034 fix_xor(VALUE x, VALUE y)
5036 if (FIXNUM_P(y)) {
5037 long val = FIX2LONG(x) ^ FIX2LONG(y);
5038 return LONG2NUM(val);
5041 if (RB_BIGNUM_TYPE_P(y)) {
5042 return rb_big_xor(y, x);
5045 return rb_num_coerce_bit(x, y, '^');
5049 * call-seq:
5050 * self ^ other -> integer
5052 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5053 * in +self+ and +other+ are different, 0 otherwise:
5055 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5057 * Raises an exception if +other+ is not an \Integer.
5059 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5063 static VALUE
5064 int_xor(VALUE x, VALUE y)
5066 if (FIXNUM_P(x)) {
5067 return fix_xor(x, y);
5069 else if (RB_BIGNUM_TYPE_P(x)) {
5070 return rb_big_xor(x, y);
5072 return Qnil;
5075 static VALUE
5076 rb_fix_lshift(VALUE x, VALUE y)
5078 long val, width;
5080 val = NUM2LONG(x);
5081 if (!val) return (rb_to_int(y), INT2FIX(0));
5082 if (!FIXNUM_P(y))
5083 return rb_big_lshift(rb_int2big(val), y);
5084 width = FIX2LONG(y);
5085 if (width < 0)
5086 return fix_rshift(val, (unsigned long)-width);
5087 return fix_lshift(val, width);
5090 static VALUE
5091 fix_lshift(long val, unsigned long width)
5093 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5094 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5095 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5097 val = val << width;
5098 return LONG2NUM(val);
5102 * call-seq:
5103 * self << count -> integer
5105 * Returns +self+ with bits shifted +count+ positions to the left,
5106 * or to the right if +count+ is negative:
5108 * n = 0b11110000
5109 * "%08b" % (n << 1) # => "111100000"
5110 * "%08b" % (n << 3) # => "11110000000"
5111 * "%08b" % (n << -1) # => "01111000"
5112 * "%08b" % (n << -3) # => "00011110"
5114 * Related: Integer#>>.
5118 VALUE
5119 rb_int_lshift(VALUE x, VALUE y)
5121 if (FIXNUM_P(x)) {
5122 return rb_fix_lshift(x, y);
5124 else if (RB_BIGNUM_TYPE_P(x)) {
5125 return rb_big_lshift(x, y);
5127 return Qnil;
5130 static VALUE
5131 rb_fix_rshift(VALUE x, VALUE y)
5133 long i, val;
5135 val = FIX2LONG(x);
5136 if (!val) return (rb_to_int(y), INT2FIX(0));
5137 if (!FIXNUM_P(y))
5138 return rb_big_rshift(rb_int2big(val), y);
5139 i = FIX2LONG(y);
5140 if (i == 0) return x;
5141 if (i < 0)
5142 return fix_lshift(val, (unsigned long)-i);
5143 return fix_rshift(val, i);
5146 static VALUE
5147 fix_rshift(long val, unsigned long i)
5149 if (i >= sizeof(long)*CHAR_BIT-1) {
5150 if (val < 0) return INT2FIX(-1);
5151 return INT2FIX(0);
5153 val = RSHIFT(val, i);
5154 return LONG2FIX(val);
5158 * call-seq:
5159 * self >> count -> integer
5161 * Returns +self+ with bits shifted +count+ positions to the right,
5162 * or to the left if +count+ is negative:
5164 * n = 0b11110000
5165 * "%08b" % (n >> 1) # => "01111000"
5166 * "%08b" % (n >> 3) # => "00011110"
5167 * "%08b" % (n >> -1) # => "111100000"
5168 * "%08b" % (n >> -3) # => "11110000000"
5170 * Related: Integer#<<.
5174 VALUE
5175 rb_int_rshift(VALUE x, VALUE y)
5177 if (FIXNUM_P(x)) {
5178 return rb_fix_rshift(x, y);
5180 else if (RB_BIGNUM_TYPE_P(x)) {
5181 return rb_big_rshift(x, y);
5183 return Qnil;
5186 VALUE
5187 rb_fix_aref(VALUE fix, VALUE idx)
5189 long val = FIX2LONG(fix);
5190 long i;
5192 idx = rb_to_int(idx);
5193 if (!FIXNUM_P(idx)) {
5194 idx = rb_big_norm(idx);
5195 if (!FIXNUM_P(idx)) {
5196 if (!BIGNUM_SIGN(idx) || val >= 0)
5197 return INT2FIX(0);
5198 return INT2FIX(1);
5201 i = FIX2LONG(idx);
5203 if (i < 0) return INT2FIX(0);
5204 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5205 if (val < 0) return INT2FIX(1);
5206 return INT2FIX(0);
5208 if (val & (1L<<i))
5209 return INT2FIX(1);
5210 return INT2FIX(0);
5214 /* copied from "r_less" in range.c */
5215 /* compares _a_ and _b_ and returns:
5216 * < 0: a < b
5217 * = 0: a = b
5218 * > 0: a > b or non-comparable
5220 static int
5221 compare_indexes(VALUE a, VALUE b)
5223 VALUE r = rb_funcall(a, id_cmp, 1, b);
5225 if (NIL_P(r))
5226 return INT_MAX;
5227 return rb_cmpint(r, a, b);
5230 static VALUE
5231 generate_mask(VALUE len)
5233 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5236 static VALUE
5237 int_aref1(VALUE num, VALUE arg)
5239 VALUE orig_num = num, beg, end;
5240 int excl;
5242 if (rb_range_values(arg, &beg, &end, &excl)) {
5243 if (NIL_P(beg)) {
5244 /* beginless range */
5245 if (!RTEST(num_negative_p(end))) {
5246 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5247 VALUE mask = generate_mask(end);
5248 if (int_zero_p(rb_int_and(num, mask))) {
5249 return INT2FIX(0);
5251 else {
5252 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5255 else {
5256 return INT2FIX(0);
5259 num = rb_int_rshift(num, beg);
5261 int cmp = compare_indexes(beg, end);
5262 if (!NIL_P(end) && cmp < 0) {
5263 VALUE len = rb_int_minus(end, beg);
5264 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5265 VALUE mask = generate_mask(len);
5266 num = rb_int_and(num, mask);
5268 else if (cmp == 0) {
5269 if (excl) return INT2FIX(0);
5270 num = orig_num;
5271 arg = beg;
5272 goto one_bit;
5274 return num;
5277 one_bit:
5278 if (FIXNUM_P(num)) {
5279 return rb_fix_aref(num, arg);
5281 else if (RB_BIGNUM_TYPE_P(num)) {
5282 return rb_big_aref(num, arg);
5284 return Qnil;
5287 static VALUE
5288 int_aref2(VALUE num, VALUE beg, VALUE len)
5290 num = rb_int_rshift(num, beg);
5291 VALUE mask = generate_mask(len);
5292 num = rb_int_and(num, mask);
5293 return num;
5297 * call-seq:
5298 * self[offset] -> 0 or 1
5299 * self[offset, size] -> integer
5300 * self[range] -> integer
5302 * Returns a slice of bits from +self+.
5304 * With argument +offset+, returns the bit at the given offset,
5305 * where offset 0 refers to the least significant bit:
5307 * n = 0b10 # => 2
5308 * n[0] # => 0
5309 * n[1] # => 1
5310 * n[2] # => 0
5311 * n[3] # => 0
5313 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5314 * Thus, negative index always returns zero:
5316 * 255[-1] # => 0
5318 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5319 * beginning at +offset+ and including bits of greater significance:
5321 * n = 0b111000 # => 56
5322 * "%010b" % n[0, 10] # => "0000111000"
5323 * "%010b" % n[4, 10] # => "0000000011"
5325 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5326 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5328 * n = 0b111000 # => 56
5329 * "%010b" % n[0..9] # => "0000111000"
5330 * "%010b" % n[4..9] # => "0000000011"
5332 * Raises an exception if the slice cannot be constructed.
5335 static VALUE
5336 int_aref(int const argc, VALUE * const argv, VALUE const num)
5338 rb_check_arity(argc, 1, 2);
5339 if (argc == 2) {
5340 return int_aref2(num, argv[0], argv[1]);
5342 return int_aref1(num, argv[0]);
5344 return Qnil;
5348 * call-seq:
5349 * to_f -> float
5351 * Converts +self+ to a Float:
5353 * 1.to_f # => 1.0
5354 * -1.to_f # => -1.0
5356 * If the value of +self+ does not fit in a Float,
5357 * the result is infinity:
5359 * (10**400).to_f # => Infinity
5360 * (-10**400).to_f # => -Infinity
5364 static VALUE
5365 int_to_f(VALUE num)
5367 double val;
5369 if (FIXNUM_P(num)) {
5370 val = (double)FIX2LONG(num);
5372 else if (RB_BIGNUM_TYPE_P(num)) {
5373 val = rb_big2dbl(num);
5375 else {
5376 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5379 return DBL2NUM(val);
5382 static VALUE
5383 fix_abs(VALUE fix)
5385 long i = FIX2LONG(fix);
5387 if (i < 0) i = -i;
5389 return LONG2NUM(i);
5392 VALUE
5393 rb_int_abs(VALUE num)
5395 if (FIXNUM_P(num)) {
5396 return fix_abs(num);
5398 else if (RB_BIGNUM_TYPE_P(num)) {
5399 return rb_big_abs(num);
5401 return Qnil;
5404 static VALUE
5405 fix_size(VALUE fix)
5407 return INT2FIX(sizeof(long));
5410 VALUE
5411 rb_int_size(VALUE num)
5413 if (FIXNUM_P(num)) {
5414 return fix_size(num);
5416 else if (RB_BIGNUM_TYPE_P(num)) {
5417 return rb_big_size_m(num);
5419 return Qnil;
5422 static VALUE
5423 rb_fix_bit_length(VALUE fix)
5425 long v = FIX2LONG(fix);
5426 if (v < 0)
5427 v = ~v;
5428 return LONG2FIX(bit_length(v));
5431 VALUE
5432 rb_int_bit_length(VALUE num)
5434 if (FIXNUM_P(num)) {
5435 return rb_fix_bit_length(num);
5437 else if (RB_BIGNUM_TYPE_P(num)) {
5438 return rb_big_bit_length(num);
5440 return Qnil;
5443 static VALUE
5444 rb_fix_digits(VALUE fix, long base)
5446 VALUE digits;
5447 long x = FIX2LONG(fix);
5449 RUBY_ASSERT(x >= 0);
5451 if (base < 2)
5452 rb_raise(rb_eArgError, "invalid radix %ld", base);
5454 if (x == 0)
5455 return rb_ary_new_from_args(1, INT2FIX(0));
5457 digits = rb_ary_new();
5458 while (x >= base) {
5459 long q = x % base;
5460 rb_ary_push(digits, LONG2NUM(q));
5461 x /= base;
5463 rb_ary_push(digits, LONG2NUM(x));
5465 return digits;
5468 static VALUE
5469 rb_int_digits_bigbase(VALUE num, VALUE base)
5471 VALUE digits, bases;
5473 RUBY_ASSERT(!rb_num_negative_p(num));
5475 if (RB_BIGNUM_TYPE_P(base))
5476 base = rb_big_norm(base);
5478 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5479 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5480 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5481 rb_raise(rb_eArgError, "negative radix");
5483 if (FIXNUM_P(base) && FIXNUM_P(num))
5484 return rb_fix_digits(num, FIX2LONG(base));
5486 if (FIXNUM_P(num))
5487 return rb_ary_new_from_args(1, num);
5489 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5490 digits = rb_ary_new();
5491 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5492 VALUE qr = rb_int_divmod(num, base);
5493 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5494 num = RARRAY_AREF(qr, 0);
5496 return digits;
5499 bases = rb_ary_new();
5500 for (VALUE b = base; int_lt(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5501 rb_ary_push(bases, b);
5503 digits = rb_ary_new_from_args(1, num);
5504 while (RARRAY_LEN(bases)) {
5505 VALUE b = rb_ary_pop(bases);
5506 long i, last_idx = RARRAY_LEN(digits) - 1;
5507 for(i = last_idx; i >= 0; i--) {
5508 VALUE n = RARRAY_AREF(digits, i);
5509 VALUE divmod = rb_int_divmod(n, b);
5510 VALUE div = RARRAY_AREF(divmod, 0);
5511 VALUE mod = RARRAY_AREF(divmod, 1);
5512 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5513 rb_ary_store(digits, 2 * i, mod);
5517 return digits;
5521 * call-seq:
5522 * digits(base = 10) -> array_of_integers
5524 * Returns an array of integers representing the +base+-radix
5525 * digits of +self+;
5526 * the first element of the array represents the least significant digit:
5528 * 12345.digits # => [5, 4, 3, 2, 1]
5529 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5530 * 12345.digits(100) # => [45, 23, 1]
5532 * Raises an exception if +self+ is negative or +base+ is less than 2.
5536 static VALUE
5537 rb_int_digits(int argc, VALUE *argv, VALUE num)
5539 VALUE base_value;
5540 long base;
5542 if (rb_num_negative_p(num))
5543 rb_raise(rb_eMathDomainError, "out of domain");
5545 if (rb_check_arity(argc, 0, 1)) {
5546 base_value = rb_to_int(argv[0]);
5547 if (!RB_INTEGER_TYPE_P(base_value))
5548 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5549 rb_obj_classname(argv[0]));
5550 if (RB_BIGNUM_TYPE_P(base_value))
5551 return rb_int_digits_bigbase(num, base_value);
5553 base = FIX2LONG(base_value);
5554 if (base < 0)
5555 rb_raise(rb_eArgError, "negative radix");
5556 else if (base < 2)
5557 rb_raise(rb_eArgError, "invalid radix %ld", base);
5559 else
5560 base = 10;
5562 if (FIXNUM_P(num))
5563 return rb_fix_digits(num, base);
5564 else if (RB_BIGNUM_TYPE_P(num))
5565 return rb_int_digits_bigbase(num, LONG2FIX(base));
5567 return Qnil;
5570 static VALUE
5571 int_upto_size(VALUE from, VALUE args, VALUE eobj)
5573 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5577 * call-seq:
5578 * upto(limit) {|i| ... } -> self
5579 * upto(limit) -> enumerator
5581 * Calls the given block with each integer value from +self+ up to +limit+;
5582 * returns +self+:
5584 * a = []
5585 * 5.upto(10) {|i| a << i } # => 5
5586 * a # => [5, 6, 7, 8, 9, 10]
5587 * a = []
5588 * -5.upto(0) {|i| a << i } # => -5
5589 * a # => [-5, -4, -3, -2, -1, 0]
5590 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5592 * With no block given, returns an Enumerator.
5596 static VALUE
5597 int_upto(VALUE from, VALUE to)
5599 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5600 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5601 long i, end;
5603 end = FIX2LONG(to);
5604 for (i = FIX2LONG(from); i <= end; i++) {
5605 rb_yield(LONG2FIX(i));
5608 else {
5609 VALUE i = from, c;
5611 while (!(c = rb_funcall(i, '>', 1, to))) {
5612 rb_yield(i);
5613 i = rb_funcall(i, '+', 1, INT2FIX(1));
5615 ensure_cmp(c, i, to);
5617 return from;
5620 static VALUE
5621 int_downto_size(VALUE from, VALUE args, VALUE eobj)
5623 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5627 * call-seq:
5628 * downto(limit) {|i| ... } -> self
5629 * downto(limit) -> enumerator
5631 * Calls the given block with each integer value from +self+ down to +limit+;
5632 * returns +self+:
5634 * a = []
5635 * 10.downto(5) {|i| a << i } # => 10
5636 * a # => [10, 9, 8, 7, 6, 5]
5637 * a = []
5638 * 0.downto(-5) {|i| a << i } # => 0
5639 * a # => [0, -1, -2, -3, -4, -5]
5640 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5642 * With no block given, returns an Enumerator.
5646 static VALUE
5647 int_downto(VALUE from, VALUE to)
5649 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5650 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5651 long i, end;
5653 end = FIX2LONG(to);
5654 for (i=FIX2LONG(from); i >= end; i--) {
5655 rb_yield(LONG2FIX(i));
5658 else {
5659 VALUE i = from, c;
5661 while (!(c = rb_funcall(i, '<', 1, to))) {
5662 rb_yield(i);
5663 i = rb_funcall(i, '-', 1, INT2FIX(1));
5665 if (NIL_P(c)) rb_cmperr(i, to);
5667 return from;
5670 static VALUE
5671 int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5673 return int_neg_p(num) ? INT2FIX(0) : num;
5677 * call-seq:
5678 * round(ndigits= 0, half: :up) -> integer
5680 * Returns +self+ rounded to the nearest value with
5681 * a precision of +ndigits+ decimal digits.
5683 * When +ndigits+ is negative, the returned value
5684 * has at least <tt>ndigits.abs</tt> trailing zeros:
5686 * 555.round(-1) # => 560
5687 * 555.round(-2) # => 600
5688 * 555.round(-3) # => 1000
5689 * -555.round(-2) # => -600
5690 * 555.round(-4) # => 0
5692 * Returns +self+ when +ndigits+ is zero or positive.
5694 * 555.round # => 555
5695 * 555.round(1) # => 555
5696 * 555.round(50) # => 555
5698 * If keyword argument +half+ is given,
5699 * and +self+ is equidistant from the two candidate values,
5700 * the rounding is according to the given +half+ value:
5702 * - +:up+ or +nil+: round away from zero:
5704 * 25.round(-1, half: :up) # => 30
5705 * (-25).round(-1, half: :up) # => -30
5707 * - +:down+: round toward zero:
5709 * 25.round(-1, half: :down) # => 20
5710 * (-25).round(-1, half: :down) # => -20
5713 * - +:even+: round toward the candidate whose last nonzero digit is even:
5715 * 25.round(-1, half: :even) # => 20
5716 * 15.round(-1, half: :even) # => 20
5717 * (-25).round(-1, half: :even) # => -20
5719 * Raises and exception if the value for +half+ is invalid.
5721 * Related: Integer#truncate.
5725 static VALUE
5726 int_round(int argc, VALUE* argv, VALUE num)
5728 int ndigits;
5729 int mode;
5730 VALUE nd, opt;
5732 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5733 ndigits = NUM2INT(nd);
5734 mode = rb_num_get_rounding_option(opt);
5735 if (ndigits >= 0) {
5736 return num;
5738 return rb_int_round(num, ndigits, mode);
5742 * call-seq:
5743 * floor(ndigits = 0) -> integer
5745 * Returns the largest number less than or equal to +self+ with
5746 * a precision of +ndigits+ decimal digits.
5748 * When +ndigits+ is negative, the returned value
5749 * has at least <tt>ndigits.abs</tt> trailing zeros:
5751 * 555.floor(-1) # => 550
5752 * 555.floor(-2) # => 500
5753 * -555.floor(-2) # => -600
5754 * 555.floor(-3) # => 0
5756 * Returns +self+ when +ndigits+ is zero or positive.
5758 * 555.floor # => 555
5759 * 555.floor(50) # => 555
5761 * Related: Integer#ceil.
5765 static VALUE
5766 int_floor(int argc, VALUE* argv, VALUE num)
5768 int ndigits;
5770 if (!rb_check_arity(argc, 0, 1)) return num;
5771 ndigits = NUM2INT(argv[0]);
5772 if (ndigits >= 0) {
5773 return num;
5775 return rb_int_floor(num, ndigits);
5779 * call-seq:
5780 * ceil(ndigits = 0) -> integer
5782 * Returns the smallest number greater than or equal to +self+ with
5783 * a precision of +ndigits+ decimal digits.
5785 * When the precision is negative, the returned value is an integer
5786 * with at least <code>ndigits.abs</code> trailing zeros:
5788 * 555.ceil(-1) # => 560
5789 * 555.ceil(-2) # => 600
5790 * -555.ceil(-2) # => -500
5791 * 555.ceil(-3) # => 1000
5793 * Returns +self+ when +ndigits+ is zero or positive.
5795 * 555.ceil # => 555
5796 * 555.ceil(50) # => 555
5798 * Related: Integer#floor.
5802 static VALUE
5803 int_ceil(int argc, VALUE* argv, VALUE num)
5805 int ndigits;
5807 if (!rb_check_arity(argc, 0, 1)) return num;
5808 ndigits = NUM2INT(argv[0]);
5809 if (ndigits >= 0) {
5810 return num;
5812 return rb_int_ceil(num, ndigits);
5816 * call-seq:
5817 * truncate(ndigits = 0) -> integer
5819 * Returns +self+ truncated (toward zero) to
5820 * a precision of +ndigits+ decimal digits.
5822 * When +ndigits+ is negative, the returned value
5823 * has at least <tt>ndigits.abs</tt> trailing zeros:
5825 * 555.truncate(-1) # => 550
5826 * 555.truncate(-2) # => 500
5827 * -555.truncate(-2) # => -500
5829 * Returns +self+ when +ndigits+ is zero or positive.
5831 * 555.truncate # => 555
5832 * 555.truncate(50) # => 555
5834 * Related: Integer#round.
5838 static VALUE
5839 int_truncate(int argc, VALUE* argv, VALUE num)
5841 int ndigits;
5843 if (!rb_check_arity(argc, 0, 1)) return num;
5844 ndigits = NUM2INT(argv[0]);
5845 if (ndigits >= 0) {
5846 return num;
5848 return rb_int_truncate(num, ndigits);
5851 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5852 rettype \
5853 prefix##_isqrt(argtype n) \
5855 if (!argtype##_IN_DOUBLE_P(n)) { \
5856 unsigned int b = bit_length(n); \
5857 argtype t; \
5858 rettype x = (rettype)(n >> (b/2+1)); \
5859 x |= ((rettype)1LU << (b-1)/2); \
5860 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5861 return x; \
5863 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5866 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5867 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5868 #else
5869 # define RB_ULONG_IN_DOUBLE_P(n) 1
5870 #endif
5871 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5872 #define RB_ULONG unsigned long
5873 DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5875 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5876 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5877 # define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5878 # else
5879 # define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5880 # endif
5881 # ifdef ULL_TO_DOUBLE
5882 # define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
5883 # else
5884 # define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
5885 # endif
5886 DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
5887 #endif
5889 #define domain_error(msg) \
5890 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
5893 * call-seq:
5894 * Integer.sqrt(numeric) -> integer
5896 * Returns the integer square root of the non-negative integer +n+,
5897 * which is the largest non-negative integer less than or equal to the
5898 * square root of +numeric+.
5900 * Integer.sqrt(0) # => 0
5901 * Integer.sqrt(1) # => 1
5902 * Integer.sqrt(24) # => 4
5903 * Integer.sqrt(25) # => 5
5904 * Integer.sqrt(10**400) # => 10**200
5906 * If +numeric+ is not an \Integer, it is converted to an \Integer:
5908 * Integer.sqrt(Complex(4, 0)) # => 2
5909 * Integer.sqrt(Rational(4, 1)) # => 2
5910 * Integer.sqrt(4.0) # => 2
5911 * Integer.sqrt(3.14159) # => 1
5913 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
5914 * except that the result of the latter code may differ from the true value
5915 * due to the limited precision of floating point arithmetic.
5917 * Integer.sqrt(10**46) # => 100000000000000000000000
5918 * Math.sqrt(10**46).floor # => 99999999999999991611392
5920 * Raises an exception if +numeric+ is negative.
5924 static VALUE
5925 rb_int_s_isqrt(VALUE self, VALUE num)
5927 unsigned long n, sq;
5928 num = rb_to_int(num);
5929 if (FIXNUM_P(num)) {
5930 if (FIXNUM_NEGATIVE_P(num)) {
5931 domain_error("isqrt");
5933 n = FIX2ULONG(num);
5934 sq = rb_ulong_isqrt(n);
5935 return LONG2FIX(sq);
5937 else {
5938 size_t biglen;
5939 if (RBIGNUM_NEGATIVE_P(num)) {
5940 domain_error("isqrt");
5942 biglen = BIGNUM_LEN(num);
5943 if (biglen == 0) return INT2FIX(0);
5944 #if SIZEOF_BDIGIT <= SIZEOF_LONG
5945 /* short-circuit */
5946 if (biglen == 1) {
5947 n = BIGNUM_DIGITS(num)[0];
5948 sq = rb_ulong_isqrt(n);
5949 return ULONG2NUM(sq);
5951 #endif
5952 return rb_big_isqrt(num);
5957 * call-seq:
5958 * Integer.try_convert(object) -> object, integer, or nil
5960 * If +object+ is an \Integer object, returns +object+.
5961 * Integer.try_convert(1) # => 1
5963 * Otherwise if +object+ responds to <tt>:to_int</tt>,
5964 * calls <tt>object.to_int</tt> and returns the result.
5965 * Integer.try_convert(1.25) # => 1
5967 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
5968 * Integer.try_convert([]) # => nil
5970 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
5972 static VALUE
5973 int_s_try_convert(VALUE self, VALUE num)
5975 return rb_check_integer_type(num);
5979 * Document-class: ZeroDivisionError
5981 * Raised when attempting to divide an integer by 0.
5983 * 42 / 0 #=> ZeroDivisionError: divided by 0
5985 * Note that only division by an exact 0 will raise the exception:
5987 * 42 / 0.0 #=> Float::INFINITY
5988 * 42 / -0.0 #=> -Float::INFINITY
5989 * 0 / 0.0 #=> NaN
5993 * Document-class: FloatDomainError
5995 * Raised when attempting to convert special float values (in particular
5996 * +Infinity+ or +NaN+) to numerical classes which don't support them.
5998 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6002 * Document-class: Numeric
6004 * \Numeric is the class from which all higher-level numeric classes should inherit.
6006 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6007 * Integer are implemented as immediates, which means that each Integer is a single immutable
6008 * object which is always passed by value.
6010 * a = 1
6011 * 1.object_id == a.object_id #=> true
6013 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6014 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6016 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6017 * 1.dup #=> 1
6018 * 1.object_id == 1.dup.object_id #=> true
6020 * For this reason, \Numeric should be used when defining other numeric classes.
6022 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6023 * Array containing an object that has been coerced into an instance of the new class
6024 * and +self+ (see #coerce).
6026 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6027 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6028 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6029 * instances of other numeric classes.
6031 * class Tally < Numeric
6032 * def initialize(string)
6033 * @string = string
6034 * end
6036 * def to_s
6037 * @string
6038 * end
6040 * def to_i
6041 * @string.size
6042 * end
6044 * def coerce(other)
6045 * [self.class.new('|' * other.to_i), self]
6046 * end
6048 * def <=>(other)
6049 * to_i <=> other.to_i
6050 * end
6052 * def +(other)
6053 * self.class.new('|' * (to_i + other.to_i))
6054 * end
6056 * def -(other)
6057 * self.class.new('|' * (to_i - other.to_i))
6058 * end
6060 * def *(other)
6061 * self.class.new('|' * (to_i * other.to_i))
6062 * end
6064 * def /(other)
6065 * self.class.new('|' * (to_i / other.to_i))
6066 * end
6067 * end
6069 * tally = Tally.new('||')
6070 * puts tally * 2 #=> "||||"
6071 * puts tally > 1 #=> true
6073 * == What's Here
6075 * First, what's elsewhere. \Class \Numeric:
6077 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6078 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6080 * Here, class \Numeric provides methods for:
6082 * - {Querying}[rdoc-ref:Numeric@Querying]
6083 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6084 * - {Converting}[rdoc-ref:Numeric@Converting]
6085 * - {Other}[rdoc-ref:Numeric@Other]
6087 * === Querying
6089 * - #finite?: Returns true unless +self+ is infinite or not a number.
6090 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6091 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6092 * - #integer?: Returns whether +self+ is an integer.
6093 * - #negative?: Returns whether +self+ is negative.
6094 * - #nonzero?: Returns whether +self+ is not zero.
6095 * - #positive?: Returns whether +self+ is positive.
6096 * - #real?: Returns whether +self+ is a real value.
6097 * - #zero?: Returns whether +self+ is zero.
6099 * === Comparing
6101 * - #<=>: Returns:
6103 * - -1 if +self+ is less than the given value.
6104 * - 0 if +self+ is equal to the given value.
6105 * - 1 if +self+ is greater than the given value.
6106 * - +nil+ if +self+ and the given value are not comparable.
6108 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6110 * === Converting
6112 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6113 * - #-@: Returns the value of +self+, negated.
6114 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6115 * - #abs2: Returns the square of +self+.
6116 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6117 * Math::PI otherwise.
6118 * - #ceil: Returns the smallest number greater than or equal to +self+,
6119 * to a given precision.
6120 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6121 * for the given other value.
6122 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6123 * - #denominator: Returns the denominator (always positive)
6124 * of the Rational representation of +self+.
6125 * - #div: Returns the value of +self+ divided by the given value
6126 * and converted to an integer.
6127 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6128 * from dividing +self+ the given divisor.
6129 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6130 * - #floor: Returns the largest number less than or equal to +self+,
6131 * to a given precision.
6132 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6133 * the given value.
6134 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6135 * - #numerator: Returns the numerator of the Rational representation of +self+;
6136 * has the same sign as +self+.
6137 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6138 * - #quo: Returns the value of +self+ divided by the given value.
6139 * - #real: Returns the real part of +self+.
6140 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6141 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6142 * - #round: Returns the value of +self+ rounded to the nearest value
6143 * for the given a precision.
6144 * - #to_c: Returns the Complex representation of +self+.
6145 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6146 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6148 * === Other
6150 * - #clone: Returns +self+; does not allow freezing.
6151 * - #dup (aliased as #+@): Returns +self+.
6152 * - #step: Invokes the given block with the sequence of specified numbers.
6155 void
6156 Init_Numeric(void)
6158 #ifdef _UNICOSMP
6159 /* Turn off floating point exceptions for divide by zero, etc. */
6160 _set_Creg(0, 0);
6161 #endif
6162 id_coerce = rb_intern_const("coerce");
6163 id_to = rb_intern_const("to");
6164 id_by = rb_intern_const("by");
6166 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6167 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6168 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6170 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6171 rb_include_module(rb_cNumeric, rb_mComparable);
6172 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6173 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6174 rb_define_method(rb_cNumeric, "dup", num_dup, 0);
6176 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6177 rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
6178 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6179 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6180 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6181 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6182 rb_define_method(rb_cNumeric, "div", num_div, 1);
6183 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6184 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6185 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6186 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6187 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6188 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6189 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6191 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6192 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6194 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6195 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6196 rb_define_method(rb_cNumeric, "round", num_round, -1);
6197 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6198 rb_define_method(rb_cNumeric, "step", num_step, -1);
6199 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6200 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6202 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6203 rb_undef_alloc_func(rb_cInteger);
6204 rb_undef_method(CLASS_OF(rb_cInteger), "new");
6205 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6206 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6208 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6209 rb_define_alias(rb_cInteger, "inspect", "to_s");
6210 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6211 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6212 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6213 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6214 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6215 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6216 rb_define_method(rb_cInteger, "next", int_succ, 0);
6217 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6218 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6219 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6220 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6221 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6222 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6223 rb_define_method(rb_cInteger, "round", int_round, -1);
6224 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6226 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6227 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6228 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6229 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6230 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6231 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6232 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6233 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6234 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6235 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6236 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6238 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6240 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6241 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6242 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6243 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6244 rb_define_method(rb_cInteger, "<", int_lt, 1);
6245 rb_define_method(rb_cInteger, "<=", int_le, 1);
6247 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6248 rb_define_method(rb_cInteger, "|", int_or, 1);
6249 rb_define_method(rb_cInteger, "^", int_xor, 1);
6250 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6252 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6253 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6255 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6257 #define fix_to_s_static(n) do { \
6258 VALUE lit = rb_fstring_literal(#n); \
6259 rb_fix_to_s_static[n] = lit; \
6260 rb_vm_register_global_object(lit); \
6261 RB_GC_GUARD(lit); \
6262 } while (0)
6264 fix_to_s_static(0);
6265 fix_to_s_static(1);
6266 fix_to_s_static(2);
6267 fix_to_s_static(3);
6268 fix_to_s_static(4);
6269 fix_to_s_static(5);
6270 fix_to_s_static(6);
6271 fix_to_s_static(7);
6272 fix_to_s_static(8);
6273 fix_to_s_static(9);
6275 #undef fix_to_s_static
6277 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6279 rb_undef_alloc_func(rb_cFloat);
6280 rb_undef_method(CLASS_OF(rb_cFloat), "new");
6283 * The base of the floating point, or number of unique digits used to
6284 * represent the number.
6286 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6288 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6290 * The number of base digits for the +double+ data type.
6292 * Usually defaults to 53.
6294 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6296 * The minimum number of significant decimal digits in a double-precision
6297 * floating point.
6299 * Usually defaults to 15.
6301 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6303 * The smallest possible exponent value in a double-precision floating
6304 * point.
6306 * Usually defaults to -1021.
6308 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6310 * The largest possible exponent value in a double-precision floating
6311 * point.
6313 * Usually defaults to 1024.
6315 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6317 * The smallest negative exponent in a double-precision floating point
6318 * where 10 raised to this power minus 1.
6320 * Usually defaults to -307.
6322 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6324 * The largest positive exponent in a double-precision floating point where
6325 * 10 raised to this power minus 1.
6327 * Usually defaults to 308.
6329 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6331 * The smallest positive normalized number in a double-precision floating point.
6333 * Usually defaults to 2.2250738585072014e-308.
6335 * If the platform supports denormalized numbers,
6336 * there are numbers between zero and Float::MIN.
6337 * 0.0.next_float returns the smallest positive floating point number
6338 * including denormalized numbers.
6340 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6342 * The largest possible integer in a double-precision floating point number.
6344 * Usually defaults to 1.7976931348623157e+308.
6346 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6348 * The difference between 1 and the smallest double-precision floating
6349 * point number greater than 1.
6351 * Usually defaults to 2.2204460492503131e-16.
6353 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6355 * An expression representing positive infinity.
6357 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6359 * An expression representing a value which is "not a number".
6361 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6363 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6364 rb_define_alias(rb_cFloat, "inspect", "to_s");
6365 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6366 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6367 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6368 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6369 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6370 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6371 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6372 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6373 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6374 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6375 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6376 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6377 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6378 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6379 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6380 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6381 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6382 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6383 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6384 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6386 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6387 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6388 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6389 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6390 rb_define_method(rb_cFloat, "round", flo_round, -1);
6391 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6393 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6394 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6395 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6396 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6397 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6400 #undef rb_float_value
6401 double
6402 rb_float_value(VALUE v)
6404 return rb_float_value_inline(v);
6407 #undef rb_float_new
6408 VALUE
6409 rb_float_new(double d)
6411 return rb_float_new_inline(d);
6414 #include "numeric.rbinc"