* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / numeric.c
blob3165556a7f7bb39e4f9439fbf927bb767b42c3b9
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 f, d, xs = x * s;
149 if (x > 0.0) {
150 f = floor(xs);
151 d = xs - f;
152 if (d > 0.5)
153 d = 1.0;
154 else if (d == 0.5 || ((double)((f + 0.5) / s) <= x))
155 d = fmod(f, 2.0);
156 else
157 d = 0.0;
158 x = f + d;
160 else if (x < 0.0) {
161 f = ceil(xs);
162 d = f - xs;
163 if (d > 0.5)
164 d = 1.0;
165 else if (d == 0.5 || ((double)((f - 0.5) / s) >= x))
166 d = fmod(-f, 2.0);
167 else
168 d = 0.0;
169 x = f - d;
171 return x;
174 static VALUE fix_lshift(long, unsigned long);
175 static VALUE fix_rshift(long, unsigned long);
176 static VALUE int_pow(long x, unsigned long y);
177 static VALUE rb_int_floor(VALUE num, int ndigits);
178 static VALUE rb_int_ceil(VALUE num, int ndigits);
179 static VALUE flo_to_i(VALUE num);
180 static int float_round_overflow(int ndigits, int binexp);
181 static int float_round_underflow(int ndigits, int binexp);
183 static ID id_coerce;
184 #define id_div idDiv
185 #define id_divmod idDivmod
186 #define id_to_i idTo_i
187 #define id_eq idEq
188 #define id_cmp idCmp
190 VALUE rb_cNumeric;
191 VALUE rb_cFloat;
192 VALUE rb_cInteger;
194 VALUE rb_eZeroDivError;
195 VALUE rb_eFloatDomainError;
197 static ID id_to, id_by;
199 void
200 rb_num_zerodiv(void)
202 rb_raise(rb_eZeroDivError, "divided by 0");
205 enum ruby_num_rounding_mode
206 rb_num_get_rounding_option(VALUE opts)
208 static ID round_kwds[1];
209 VALUE rounding;
210 VALUE str;
211 const char *s;
213 if (!NIL_P(opts)) {
214 if (!round_kwds[0]) {
215 round_kwds[0] = rb_intern_const("half");
217 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
218 if (SYMBOL_P(rounding)) {
219 str = rb_sym2str(rounding);
221 else if (NIL_P(rounding)) {
222 goto noopt;
224 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
225 str = rb_check_string_type(rounding);
226 if (NIL_P(str)) goto invalid;
228 rb_must_asciicompat(str);
229 s = RSTRING_PTR(str);
230 switch (RSTRING_LEN(str)) {
231 case 2:
232 if (rb_memcicmp(s, "up", 2) == 0)
233 return RUBY_NUM_ROUND_HALF_UP;
234 break;
235 case 4:
236 if (rb_memcicmp(s, "even", 4) == 0)
237 return RUBY_NUM_ROUND_HALF_EVEN;
238 if (strncasecmp(s, "down", 4) == 0)
239 return RUBY_NUM_ROUND_HALF_DOWN;
240 break;
242 invalid:
243 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
245 noopt:
246 return RUBY_NUM_ROUND_DEFAULT;
249 /* experimental API */
251 rb_num_to_uint(VALUE val, unsigned int *ret)
253 #define NUMERR_TYPE 1
254 #define NUMERR_NEGATIVE 2
255 #define NUMERR_TOOLARGE 3
256 if (FIXNUM_P(val)) {
257 long v = FIX2LONG(val);
258 #if SIZEOF_INT < SIZEOF_LONG
259 if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
260 #endif
261 if (v < 0) return NUMERR_NEGATIVE;
262 *ret = (unsigned int)v;
263 return 0;
266 if (RB_BIGNUM_TYPE_P(val)) {
267 if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
268 #if SIZEOF_INT < SIZEOF_LONG
269 /* long is 64bit */
270 return NUMERR_TOOLARGE;
271 #else
272 /* long is 32bit */
273 if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
274 *ret = (unsigned int)rb_big2ulong((VALUE)val);
275 return 0;
276 #endif
278 return NUMERR_TYPE;
281 #define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
283 static inline int
284 int_pos_p(VALUE num)
286 if (FIXNUM_P(num)) {
287 return FIXNUM_POSITIVE_P(num);
289 else if (RB_BIGNUM_TYPE_P(num)) {
290 return BIGNUM_POSITIVE_P(num);
292 rb_raise(rb_eTypeError, "not an Integer");
295 static inline int
296 int_neg_p(VALUE num)
298 if (FIXNUM_P(num)) {
299 return FIXNUM_NEGATIVE_P(num);
301 else if (RB_BIGNUM_TYPE_P(num)) {
302 return BIGNUM_NEGATIVE_P(num);
304 rb_raise(rb_eTypeError, "not an Integer");
308 rb_int_positive_p(VALUE num)
310 return int_pos_p(num);
314 rb_int_negative_p(VALUE num)
316 return int_neg_p(num);
320 rb_num_negative_p(VALUE num)
322 return rb_num_negative_int_p(num);
325 static VALUE
326 num_funcall_op_0(VALUE x, VALUE arg, int recursive)
328 ID func = (ID)arg;
329 if (recursive) {
330 const char *name = rb_id2name(func);
331 if (ISALNUM(name[0])) {
332 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
333 x, ID2SYM(func));
335 else if (name[0] && name[1] == '@' && !name[2]) {
336 rb_name_error(func, "%c%"PRIsVALUE,
337 name[0], x);
339 else {
340 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
341 ID2SYM(func), x);
344 return rb_funcallv(x, func, 0, 0);
347 static VALUE
348 num_funcall0(VALUE x, ID func)
350 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
353 NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
355 static void
356 num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
358 const char *name = rb_id2name(func);
359 if (ISALNUM(name[0])) {
360 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
361 x, ID2SYM(func), y);
363 else {
364 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
365 x, ID2SYM(func), y);
369 static VALUE
370 num_funcall_op_1(VALUE y, VALUE arg, int recursive)
372 ID func = (ID)((VALUE *)arg)[0];
373 VALUE x = ((VALUE *)arg)[1];
374 if (recursive) {
375 num_funcall_op_1_recursion(x, func, y);
377 return rb_funcall(x, func, 1, y);
380 static VALUE
381 num_funcall1(VALUE x, ID func, VALUE y)
383 VALUE args[2];
384 args[0] = (VALUE)func;
385 args[1] = x;
386 return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
390 * call-seq:
391 * coerce(other) -> array
393 * Returns a 2-element array containing two numeric elements,
394 * formed from the two operands +self+ and +other+,
395 * of a common compatible type.
397 * Of the Core and Standard Library classes,
398 * Integer, Rational, and Complex use this implementation.
400 * Examples:
402 * i = 2 # => 2
403 * i.coerce(3) # => [3, 2]
404 * i.coerce(3.0) # => [3.0, 2.0]
405 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
406 * i.coerce(Complex(3, 4)) # Raises RangeError.
408 * r = Rational(5, 2) # => (5/2)
409 * r.coerce(2) # => [(2/1), (5/2)]
410 * r.coerce(2.0) # => [2.0, 2.5]
411 * r.coerce(Rational(2, 3)) # => [(2/3), (5/2)]
412 * r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)]
414 * c = Complex(2, 3) # => (2+3i)
415 * c.coerce(2) # => [(2+0i), (2+3i)]
416 * c.coerce(2.0) # => [(2.0+0i), (2+3i)]
417 * c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)]
418 * c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
420 * Raises an exception if any type conversion fails.
424 static VALUE
425 num_coerce(VALUE x, VALUE y)
427 if (CLASS_OF(x) == CLASS_OF(y))
428 return rb_assoc_new(y, x);
429 x = rb_Float(x);
430 y = rb_Float(y);
431 return rb_assoc_new(y, x);
434 NORETURN(static void coerce_failed(VALUE x, VALUE y));
435 static void
436 coerce_failed(VALUE x, VALUE y)
438 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
439 y = rb_inspect(y);
441 else {
442 y = rb_obj_class(y);
444 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
445 y, rb_obj_class(x));
448 static int
449 do_coerce(VALUE *x, VALUE *y, int err)
451 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
452 if (ary == Qundef) {
453 if (err) {
454 coerce_failed(*x, *y);
456 return FALSE;
458 if (!err && NIL_P(ary)) {
459 return FALSE;
461 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
462 rb_raise(rb_eTypeError, "coerce must return [x, y]");
465 *x = RARRAY_AREF(ary, 0);
466 *y = RARRAY_AREF(ary, 1);
467 return TRUE;
470 VALUE
471 rb_num_coerce_bin(VALUE x, VALUE y, ID func)
473 do_coerce(&x, &y, TRUE);
474 return rb_funcall(x, func, 1, y);
477 VALUE
478 rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
480 if (do_coerce(&x, &y, FALSE))
481 return rb_funcall(x, func, 1, y);
482 return Qnil;
485 static VALUE
486 ensure_cmp(VALUE c, VALUE x, VALUE y)
488 if (NIL_P(c)) rb_cmperr(x, y);
489 return c;
492 VALUE
493 rb_num_coerce_relop(VALUE x, VALUE y, ID func)
495 VALUE x0 = x, y0 = y;
497 if (!do_coerce(&x, &y, FALSE)) {
498 rb_cmperr(x0, y0);
499 UNREACHABLE_RETURN(Qnil);
501 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
504 NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
507 * :nodoc:
509 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
511 * Numerics should be values; singleton_methods should not be added to them.
514 static VALUE
515 num_sadded(VALUE x, VALUE name)
517 ID mid = rb_to_id(name);
518 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
519 rb_remove_method_id(rb_singleton_class(x), mid);
520 rb_raise(rb_eTypeError,
521 "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
522 rb_id2str(mid),
523 rb_obj_class(x));
525 UNREACHABLE_RETURN(Qnil);
528 #if 0
530 * call-seq:
531 * clone(freeze: true) -> self
533 * Returns +self+.
535 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
537 * Related: Numeric#dup.
540 static VALUE
541 num_clone(int argc, VALUE *argv, VALUE x)
543 return rb_immutable_obj_clone(argc, argv, x);
545 #else
546 # define num_clone rb_immutable_obj_clone
547 #endif
549 #if 0
551 * call-seq:
552 * dup -> self
554 * Returns +self+.
556 * Related: Numeric#clone.
559 static VALUE
560 num_dup(VALUE x)
562 return x;
564 #else
565 # define num_dup num_uplus
566 #endif
569 * call-seq:
570 * +self -> self
572 * Returns +self+.
576 static VALUE
577 num_uplus(VALUE num)
579 return num;
583 * call-seq:
584 * i -> complex
586 * Returns <tt>Complex(0, self)</tt>:
588 * 2.i # => (0+2i)
589 * -2.i # => (0-2i)
590 * 2.0.i # => (0+2.0i)
591 * Rational(1, 2).i # => (0+(1/2)*i)
592 * Complex(3, 4).i # Raises NoMethodError.
596 static VALUE
597 num_imaginary(VALUE num)
599 return rb_complex_new(INT2FIX(0), num);
603 * call-seq:
604 * -self -> numeric
606 * Unary Minus---Returns the receiver, negated.
609 static VALUE
610 num_uminus(VALUE num)
612 VALUE zero;
614 zero = INT2FIX(0);
615 do_coerce(&zero, &num, TRUE);
617 return num_funcall1(zero, '-', num);
621 * call-seq:
622 * fdiv(other) -> float
624 * Returns the quotient <tt>self/other</tt> as a float,
625 * using method +/+ in the derived class of +self+.
626 * (\Numeric itself does not define method +/+.)
628 * Of the Core and Standard Library classes,
629 * only BigDecimal uses this implementation.
633 static VALUE
634 num_fdiv(VALUE x, VALUE y)
636 return rb_funcall(rb_Float(x), '/', 1, y);
640 * call-seq:
641 * div(other) -> integer
643 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
644 * using method +/+ in the derived class of +self+.
645 * (\Numeric itself does not define method +/+.)
647 * Of the Core and Standard Library classes,
648 * Float, Rational, and Complex use this implementation.
652 static VALUE
653 num_div(VALUE x, VALUE y)
655 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
656 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
660 * call-seq:
661 * self % other -> real_numeric
663 * Returns +self+ modulo +other+ as a real number.
665 * Of the Core and Standard Library classes,
666 * only Rational uses this implementation.
668 * For \Rational +r+ and real number +n+, these expressions are equivalent:
670 * c % n
671 * c-n*(c/n).floor
672 * c.divmod(n)[1]
674 * See Numeric#divmod.
676 * Examples:
678 * r = Rational(1, 2) # => (1/2)
679 * r2 = Rational(2, 3) # => (2/3)
680 * r % r2 # => (1/2)
681 * r % 2 # => (1/2)
682 * r % 2.0 # => 0.5
684 * r = Rational(301,100) # => (301/100)
685 * r2 = Rational(7,5) # => (7/5)
686 * r % r2 # => (21/100)
687 * r % -r2 # => (-119/100)
688 * (-r) % r2 # => (119/100)
689 * (-r) %-r2 # => (-21/100)
691 * Numeric#modulo is an alias for Numeric#%.
695 static VALUE
696 num_modulo(VALUE x, VALUE y)
698 VALUE q = num_funcall1(x, id_div, y);
699 return rb_funcall(x, '-', 1,
700 rb_funcall(y, '*', 1, q));
704 * call-seq:
705 * remainder(other) -> real_number
707 * Returns the remainder after dividing +self+ by +other+.
709 * Of the Core and Standard Library classes,
710 * only Float and Rational use this implementation.
712 * Examples:
714 * 11.0.remainder(4) # => 3.0
715 * 11.0.remainder(-4) # => 3.0
716 * -11.0.remainder(4) # => -3.0
717 * -11.0.remainder(-4) # => -3.0
719 * 12.0.remainder(4) # => 0.0
720 * 12.0.remainder(-4) # => 0.0
721 * -12.0.remainder(4) # => -0.0
722 * -12.0.remainder(-4) # => -0.0
724 * 13.0.remainder(4.0) # => 1.0
725 * 13.0.remainder(Rational(4, 1)) # => 1.0
727 * Rational(13, 1).remainder(4) # => (1/1)
728 * Rational(13, 1).remainder(-4) # => (1/1)
729 * Rational(-13, 1).remainder(4) # => (-1/1)
730 * Rational(-13, 1).remainder(-4) # => (-1/1)
734 static VALUE
735 num_remainder(VALUE x, VALUE y)
737 VALUE z = num_funcall1(x, '%', y);
739 if ((!rb_equal(z, INT2FIX(0))) &&
740 ((rb_num_negative_int_p(x) &&
741 rb_num_positive_int_p(y)) ||
742 (rb_num_positive_int_p(x) &&
743 rb_num_negative_int_p(y)))) {
744 if (RB_FLOAT_TYPE_P(y)) {
745 if (isinf(RFLOAT_VALUE(y))) {
746 return x;
749 return rb_funcall(z, '-', 1, y);
751 return z;
755 * call-seq:
756 * divmod(other) -> array
758 * Returns a 2-element array <tt>[q, r]</tt>, where
760 * q = (self/other).floor # Quotient
761 * r = self % other # Remainder
763 * Of the Core and Standard Library classes,
764 * only Rational uses this implementation.
766 * Examples:
768 * Rational(11, 1).divmod(4) # => [2, (3/1)]
769 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
770 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
771 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
773 * Rational(12, 1).divmod(4) # => [3, (0/1)]
774 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
775 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
776 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
778 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
779 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
782 static VALUE
783 num_divmod(VALUE x, VALUE y)
785 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
789 * call-seq:
790 * abs -> numeric
792 * Returns the absolute value of +self+.
794 * 12.abs #=> 12
795 * (-34.56).abs #=> 34.56
796 * -34.56.abs #=> 34.56
798 * Numeric#magnitude is an alias for Numeric#abs.
802 static VALUE
803 num_abs(VALUE num)
805 if (rb_num_negative_int_p(num)) {
806 return num_funcall0(num, idUMinus);
808 return num;
812 * call-seq:
813 * zero? -> true or false
815 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
817 * Of the Core and Standard Library classes,
818 * only Rational and Complex use this implementation.
822 static VALUE
823 num_zero_p(VALUE num)
825 return rb_equal(num, INT2FIX(0));
828 static bool
829 int_zero_p(VALUE num)
831 if (FIXNUM_P(num)) {
832 return FIXNUM_ZERO_P(num);
834 assert(RB_BIGNUM_TYPE_P(num));
835 return rb_bigzero_p(num);
838 VALUE
839 rb_int_zero_p(VALUE num)
841 return RBOOL(int_zero_p(num));
845 * call-seq:
846 * nonzero? -> self or nil
848 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
849 * uses method <tt>zero?</tt> for the evaluation.
851 * The returned +self+ allows the method to be chained:
853 * a = %w[z Bb bB bb BB a aA Aa AA A]
854 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
855 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
857 * Of the Core and Standard Library classes,
858 * Integer, Float, Rational, and Complex use this implementation.
862 static VALUE
863 num_nonzero_p(VALUE num)
865 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
866 return Qnil;
868 return num;
872 * call-seq:
873 * to_int -> integer
875 * Returns +self+ as an integer;
876 * converts using method +to_i+ in the derived class.
878 * Of the Core and Standard Library classes,
879 * only Rational and Complex use this implementation.
881 * Examples:
883 * Rational(1, 2).to_int # => 0
884 * Rational(2, 1).to_int # => 2
885 * Complex(2, 0).to_int # => 2
886 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
890 static VALUE
891 num_to_int(VALUE num)
893 return num_funcall0(num, id_to_i);
897 * call-seq:
898 * positive? -> true or false
900 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
904 static VALUE
905 num_positive_p(VALUE num)
907 const ID mid = '>';
909 if (FIXNUM_P(num)) {
910 if (method_basic_p(rb_cInteger))
911 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
913 else if (RB_BIGNUM_TYPE_P(num)) {
914 if (method_basic_p(rb_cInteger))
915 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
917 return rb_num_compare_with_zero(num, mid);
921 * call-seq:
922 * negative? -> true or false
924 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
928 static VALUE
929 num_negative_p(VALUE num)
931 return RBOOL(rb_num_negative_int_p(num));
935 /********************************************************************
937 * Document-class: Float
939 * A \Float object represents a sometimes-inexact real number using the native
940 * architecture's double-precision floating point representation.
942 * Floating point has a different arithmetic and is an inexact number.
943 * So you should know its esoteric system. See following:
945 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
946 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#floats_imprecise
947 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
949 * You can create a \Float object explicitly with:
951 * - A {floating-point literal}[doc/syntax/literals_rdoc.html#label-Float+Literals].
953 * You can convert certain objects to Floats with:
955 * - \Method {Float}[Kernel.html#method-i-Float].
957 * == What's Here
959 * First, what's elsewhere. \Class \Float:
961 * - Inherits from {class Numeric}[Numeric.html#class-Numeric-label-What-27s+Here].
963 * Here, class \Float provides methods for:
965 * - {Querying}[#class-Float-label-Querying]
966 * - {Comparing}[#class-Float-label-Comparing]
967 * - {Converting}[#class-Float-label-Converting]
969 * === Querying
971 * - #finite?:: Returns whether +self+ is finite.
972 * - #hash:: Returns the integer hash code for +self+.
973 * - #infinite?:: Returns whether +self+ is infinite.
974 * - #nan?:: Returns whether +self+ is a NaN (not-a-number).
976 * === Comparing
978 * - {<}[#method-i-3C]:: Returns whether +self+ is less than the given value.
979 * - {<=}[#method-i-3C-3D]:: Returns whether +self+ is less than
980 * or equal to the given value.
981 * - {<=>}[#method-i-3C-3D-3E]:: Returns a number indicating whether +self+ is less than,
982 * equal to, or greater than the given value.
983 * - {==}[#method-i-3D-3D] (aliased as #=== and #eql>):: Returns whether +self+ is
984 * equal to the given value.
985 * - {>}[#method-i-3E]:: Returns whether +self+ is greater than the given value.
986 * - {>=}[#method-i-3E-3D]:: Returns whether +self+ is greater than
987 * or equal to the given value.
989 * === Converting
991 * - #% (aliased as #modulo):: Returns +self+ modulo the given value.
992 * - #*:: Returns the product of +self+ and the given value.
993 * - {**}[#method-i-2A-2A]:: Returns the value of +self+ raised to the power of the given value.
994 * - #+:: Returns the sum of +self+ and the given value.
995 * - #-:: Returns the difference of +self+ and the given value.
996 * - {/}[#method-i-2F]:: Returns the quotient of +self+ and the given value.
997 * - #ceil:: Returns the smallest number greater than or equal to +self+.
998 * - #coerce:: Returns a 2-element array containing the given value converted to a \Float
999 and +self+
1000 * - #divmod:: Returns a 2-element array containing the quotient and remainder
1001 * results of dividing +self+ by the given value.
1002 * - #fdiv:: Returns the Float result of dividing +self+ by the given value.
1003 * - #floor:: Returns the greatest number smaller than or equal to +self+.
1004 * - #next_float:: Returns the next-larger representable \Float.
1005 * - #prev_float:: Returns the next-smaller representable \Float.
1006 * - #quo:: Returns the quotient from dividing +self+ by the given value.
1007 * - #round:: Returns +self+ rounded to the nearest value, to a given precision.
1008 * - #to_i (aliased as #to_int):: Returns +self+ truncated to an Integer.
1009 * - #to_s (aliased as #inspect):: Returns a string containing the place-value
1010 * representation of +self+ in the given radix.
1011 * - #truncate:: Returns +self+ truncated to a given precision.
1015 VALUE
1016 rb_float_new_in_heap(double d)
1018 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0));
1020 #if SIZEOF_DOUBLE <= SIZEOF_VALUE
1021 flt->float_value = d;
1022 #else
1023 union {
1024 double d;
1025 rb_float_value_type v;
1026 } u = {d};
1027 flt->float_value = u.v;
1028 #endif
1029 OBJ_FREEZE((VALUE)flt);
1030 return (VALUE)flt;
1034 * call-seq:
1035 * to_s -> string
1037 * Returns a string containing a representation of +self+;
1038 * depending of the value of +self+, the string representation
1039 * may contain:
1041 * - A fixed-point number.
1042 * - A number in "scientific notation" (containing an exponent).
1043 * - 'Infinity'.
1044 * - '-Infinity'.
1045 * - 'NaN' (indicating not-a-number).
1047 * 3.14.to_s # => "3.14"
1048 * (10.1**50).to_s # => "1.644631821843879e+50"
1049 * (10.1**500).to_s # => "Infinity"
1050 * (-10.1**500).to_s # => "-Infinity"
1051 * (0.0/0.0).to_s # => "NaN"
1055 static VALUE
1056 flo_to_s(VALUE flt)
1058 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
1059 enum {float_dig = DBL_DIG+1};
1060 char buf[float_dig + (decimal_mant + CHAR_BIT - 1) / CHAR_BIT + 10];
1061 double value = RFLOAT_VALUE(flt);
1062 VALUE s;
1063 char *p, *e;
1064 int sign, decpt, digs;
1066 if (isinf(value)) {
1067 static const char minf[] = "-Infinity";
1068 const int pos = (value > 0); /* skip "-" */
1069 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
1071 else if (isnan(value))
1072 return rb_usascii_str_new2("NaN");
1074 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
1075 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1076 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
1077 memcpy(buf, p, digs);
1078 xfree(p);
1079 if (decpt > 0) {
1080 if (decpt < digs) {
1081 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
1082 buf[decpt] = '.';
1083 rb_str_cat(s, buf, digs + 1);
1085 else if (decpt <= DBL_DIG) {
1086 long len;
1087 char *ptr;
1088 rb_str_cat(s, buf, digs);
1089 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
1090 ptr = RSTRING_PTR(s) + len;
1091 if (decpt > digs) {
1092 memset(ptr, '0', decpt - digs);
1093 ptr += decpt - digs;
1095 memcpy(ptr, ".0", 2);
1097 else {
1098 goto exp;
1101 else if (decpt > -4) {
1102 long len;
1103 char *ptr;
1104 rb_str_cat(s, "0.", 2);
1105 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1106 ptr = RSTRING_PTR(s);
1107 memset(ptr += len, '0', -decpt);
1108 memcpy(ptr -= decpt, buf, digs);
1110 else {
1111 goto exp;
1113 return s;
1115 exp:
1116 if (digs > 1) {
1117 memmove(buf + 2, buf + 1, digs - 1);
1119 else {
1120 buf[2] = '0';
1121 digs++;
1123 buf[1] = '.';
1124 rb_str_cat(s, buf, digs + 1);
1125 rb_str_catf(s, "e%+03d", decpt - 1);
1126 return s;
1130 * call-seq:
1131 * coerce(other) -> array
1133 * Returns a 2-element array containing +other+ converted to a \Float
1134 * and +self+:
1136 * f = 3.14 # => 3.14
1137 * f.coerce(2) # => [2.0, 3.14]
1138 * f.coerce(2.0) # => [2.0, 3.14]
1139 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1140 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1142 * Raises an exception if a type conversion fails.
1146 static VALUE
1147 flo_coerce(VALUE x, VALUE y)
1149 return rb_assoc_new(rb_Float(y), x);
1152 MJIT_FUNC_EXPORTED VALUE
1153 rb_float_uminus(VALUE flt)
1155 return DBL2NUM(-RFLOAT_VALUE(flt));
1159 * call-seq:
1160 * self + other -> numeric
1162 * Returns a new \Float which is the sum of +self+ and +other+:
1164 * f = 3.14
1165 * f + 1 # => 4.140000000000001
1166 * f + 1.0 # => 4.140000000000001
1167 * f + Rational(1, 1) # => 4.140000000000001
1168 * f + Complex(1, 0) # => (4.140000000000001+0i)
1172 VALUE
1173 rb_float_plus(VALUE x, VALUE y)
1175 if (FIXNUM_P(y)) {
1176 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1178 else if (RB_BIGNUM_TYPE_P(y)) {
1179 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1181 else if (RB_FLOAT_TYPE_P(y)) {
1182 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1184 else {
1185 return rb_num_coerce_bin(x, y, '+');
1190 * call-seq:
1191 * self - other -> numeric
1193 * Returns a new \Float which is the difference of +self+ and +other+:
1195 * f = 3.14
1196 * f - 1 # => 2.14
1197 * f - 1.0 # => 2.14
1198 * f - Rational(1, 1) # => 2.14
1199 * f - Complex(1, 0) # => (2.14+0i)
1203 VALUE
1204 rb_float_minus(VALUE x, VALUE y)
1206 if (FIXNUM_P(y)) {
1207 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1209 else if (RB_BIGNUM_TYPE_P(y)) {
1210 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1212 else if (RB_FLOAT_TYPE_P(y)) {
1213 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1215 else {
1216 return rb_num_coerce_bin(x, y, '-');
1221 * call-seq:
1222 * self * other -> numeric
1224 * Returns a new \Float which is the product of +self+ and +other+:
1226 * f = 3.14
1227 * f * 2 # => 6.28
1228 * f * 2.0 # => 6.28
1229 * f * Rational(1, 2) # => 1.57
1230 * f * Complex(2, 0) # => (6.28+0.0i)
1233 VALUE
1234 rb_float_mul(VALUE x, VALUE y)
1236 if (FIXNUM_P(y)) {
1237 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1239 else if (RB_BIGNUM_TYPE_P(y)) {
1240 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1242 else if (RB_FLOAT_TYPE_P(y)) {
1243 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1245 else {
1246 return rb_num_coerce_bin(x, y, '*');
1250 static double
1251 double_div_double(double x, double y)
1253 if (LIKELY(y != 0.0)) {
1254 return x / y;
1256 else if (x == 0.0) {
1257 return nan("");
1259 else {
1260 double z = signbit(y) ? -1.0 : 1.0;
1261 return x * z * HUGE_VAL;
1265 MJIT_FUNC_EXPORTED VALUE
1266 rb_flo_div_flo(VALUE x, VALUE y)
1268 double num = RFLOAT_VALUE(x);
1269 double den = RFLOAT_VALUE(y);
1270 double ret = double_div_double(num, den);
1271 return DBL2NUM(ret);
1275 * call-seq:
1276 * self / other -> numeric
1278 * Returns a new \Float which is the result of dividing +self+ by +other+:
1280 * f = 3.14
1281 * f / 2 # => 1.57
1282 * f / 2.0 # => 1.57
1283 * f / Rational(2, 1) # => 1.57
1284 * f / Complex(2, 0) # => (1.57+0.0i)
1288 VALUE
1289 rb_float_div(VALUE x, VALUE y)
1291 double num = RFLOAT_VALUE(x);
1292 double den;
1293 double ret;
1295 if (FIXNUM_P(y)) {
1296 den = FIX2LONG(y);
1298 else if (RB_BIGNUM_TYPE_P(y)) {
1299 den = rb_big2dbl(y);
1301 else if (RB_FLOAT_TYPE_P(y)) {
1302 den = RFLOAT_VALUE(y);
1304 else {
1305 return rb_num_coerce_bin(x, y, '/');
1308 ret = double_div_double(num, den);
1309 return DBL2NUM(ret);
1313 * call-seq:
1314 * quo(other) -> numeric
1316 * Returns the quotient from dividing +self+ by +other+:
1318 * f = 3.14
1319 * f.quo(2) # => 1.57
1320 * f.quo(-2) # => -1.57
1321 * f.quo(Rational(2, 1)) # => 1.57
1322 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1324 * Float#fdiv is an alias for Float#quo.
1328 static VALUE
1329 flo_quo(VALUE x, VALUE y)
1331 return num_funcall1(x, '/', y);
1334 static void
1335 flodivmod(double x, double y, double *divp, double *modp)
1337 double div, mod;
1339 if (isnan(y)) {
1340 /* y is NaN so all results are NaN */
1341 if (modp) *modp = y;
1342 if (divp) *divp = y;
1343 return;
1345 if (y == 0.0) rb_num_zerodiv();
1346 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1347 mod = x;
1348 else {
1349 #ifdef HAVE_FMOD
1350 mod = fmod(x, y);
1351 #else
1352 double z;
1354 modf(x/y, &z);
1355 mod = x - z * y;
1356 #endif
1358 if (isinf(x) && !isinf(y))
1359 div = x;
1360 else {
1361 div = (x - mod) / y;
1362 if (modp && divp) div = round(div);
1364 if (y*mod < 0) {
1365 mod += y;
1366 div -= 1.0;
1368 if (modp) *modp = mod;
1369 if (divp) *divp = div;
1373 * Returns the modulo of division of x by y.
1374 * An error will be raised if y == 0.
1377 MJIT_FUNC_EXPORTED double
1378 ruby_float_mod(double x, double y)
1380 double mod;
1381 flodivmod(x, y, 0, &mod);
1382 return mod;
1386 * call-seq:
1387 * self % other -> float
1389 * Returns +self+ modulo +other+ as a float.
1391 * For float +f+ and real number +r+, these expressions are equivalent:
1393 * f % r
1394 * f-r*(f/r).floor
1395 * f.divmod(r)[1]
1397 * See Numeric#divmod.
1399 * Examples:
1401 * 10.0 % 2 # => 0.0
1402 * 10.0 % 3 # => 1.0
1403 * 10.0 % 4 # => 2.0
1405 * 10.0 % -2 # => 0.0
1406 * 10.0 % -3 # => -2.0
1407 * 10.0 % -4 # => -2.0
1409 * 10.0 % 4.0 # => 2.0
1410 * 10.0 % Rational(4, 1) # => 2.0
1412 * Float#modulo is an alias for Float#%.
1416 static VALUE
1417 flo_mod(VALUE x, VALUE y)
1419 double fy;
1421 if (FIXNUM_P(y)) {
1422 fy = (double)FIX2LONG(y);
1424 else if (RB_BIGNUM_TYPE_P(y)) {
1425 fy = rb_big2dbl(y);
1427 else if (RB_FLOAT_TYPE_P(y)) {
1428 fy = RFLOAT_VALUE(y);
1430 else {
1431 return rb_num_coerce_bin(x, y, '%');
1433 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1436 static VALUE
1437 dbl2ival(double d)
1439 if (FIXABLE(d)) {
1440 return LONG2FIX((long)d);
1442 return rb_dbl2big(d);
1446 * call-seq:
1447 * divmod(other) -> array
1449 * Returns a 2-element array <tt>[q, r]</tt>, where
1451 * q = (self/other).floor # Quotient
1452 * r = self % other # Remainder
1454 * Examples:
1456 * 11.0.divmod(4) # => [2, 3.0]
1457 * 11.0.divmod(-4) # => [-3, -1.0]
1458 * -11.0.divmod(4) # => [-3, 1.0]
1459 * -11.0.divmod(-4) # => [2, -3.0]
1461 * 12.0.divmod(4) # => [3, 0.0]
1462 * 12.0.divmod(-4) # => [-3, 0.0]
1463 * -12.0.divmod(4) # => [-3, -0.0]
1464 * -12.0.divmod(-4) # => [3, -0.0]
1466 * 13.0.divmod(4.0) # => [3, 1.0]
1467 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1471 static VALUE
1472 flo_divmod(VALUE x, VALUE y)
1474 double fy, div, mod;
1475 volatile VALUE a, b;
1477 if (FIXNUM_P(y)) {
1478 fy = (double)FIX2LONG(y);
1480 else if (RB_BIGNUM_TYPE_P(y)) {
1481 fy = rb_big2dbl(y);
1483 else if (RB_FLOAT_TYPE_P(y)) {
1484 fy = RFLOAT_VALUE(y);
1486 else {
1487 return rb_num_coerce_bin(x, y, id_divmod);
1489 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1490 a = dbl2ival(div);
1491 b = DBL2NUM(mod);
1492 return rb_assoc_new(a, b);
1496 * call-seq:
1497 * self ** other -> numeric
1499 * Raises +self+ to the power of +other+:
1501 * f = 3.14
1502 * f ** 2 # => 9.8596
1503 * f ** -2 # => 0.1014239928597509
1504 * f ** 2.1 # => 11.054834900588839
1505 * f ** Rational(2, 1) # => 9.8596
1506 * f ** Complex(2, 0) # => (9.8596+0i)
1510 VALUE
1511 rb_float_pow(VALUE x, VALUE y)
1513 double dx, dy;
1514 if (y == INT2FIX(2)) {
1515 dx = RFLOAT_VALUE(x);
1516 return DBL2NUM(dx * dx);
1518 else if (FIXNUM_P(y)) {
1519 dx = RFLOAT_VALUE(x);
1520 dy = (double)FIX2LONG(y);
1522 else if (RB_BIGNUM_TYPE_P(y)) {
1523 dx = RFLOAT_VALUE(x);
1524 dy = rb_big2dbl(y);
1526 else if (RB_FLOAT_TYPE_P(y)) {
1527 dx = RFLOAT_VALUE(x);
1528 dy = RFLOAT_VALUE(y);
1529 if (dx < 0 && dy != round(dy))
1530 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1532 else {
1533 return rb_num_coerce_bin(x, y, idPow);
1535 return DBL2NUM(pow(dx, dy));
1539 * call-seq:
1540 * eql?(other) -> true or false
1542 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1544 * Of the Core and Standard Library classes,
1545 * only Integer, Rational, and Complex use this implementation.
1547 * Examples:
1549 * 1.eql?(1) # => true
1550 * 1.eql?(1.0) # => false
1551 * 1.eql?(Rational(1, 1)) # => false
1552 * 1.eql?(Complex(1, 0)) # => false
1554 * \Method +eql?+ is different from +==+ in that +eql?+ requires matching types,
1555 * while +==+ does not.
1559 static VALUE
1560 num_eql(VALUE x, VALUE y)
1562 if (TYPE(x) != TYPE(y)) return Qfalse;
1564 if (RB_BIGNUM_TYPE_P(x)) {
1565 return rb_big_eql(x, y);
1568 return rb_equal(x, y);
1572 * call-seq:
1573 * self <=> other -> zero or nil
1575 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1577 * No subclass in the Ruby Core or Standard Library uses this implementation.
1581 static VALUE
1582 num_cmp(VALUE x, VALUE y)
1584 if (x == y) return INT2FIX(0);
1585 return Qnil;
1588 static VALUE
1589 num_equal(VALUE x, VALUE y)
1591 VALUE result;
1592 if (x == y) return Qtrue;
1593 result = num_funcall1(y, id_eq, x);
1594 return RBOOL(RTEST(result));
1598 * call-seq:
1599 * self == other -> true or false
1601 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1603 * 2.0 == 2 # => true
1604 * 2.0 == 2.0 # => true
1605 * 2.0 == Rational(2, 1) # => true
1606 * 2.0 == Complex(2, 0) # => true
1608 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1610 * Related: Float#eql? (requires +other+ to be a \Float).
1614 MJIT_FUNC_EXPORTED VALUE
1615 rb_float_equal(VALUE x, VALUE y)
1617 volatile double a, b;
1619 if (RB_INTEGER_TYPE_P(y)) {
1620 return rb_integer_float_eq(y, x);
1622 else if (RB_FLOAT_TYPE_P(y)) {
1623 b = RFLOAT_VALUE(y);
1624 #if MSC_VERSION_BEFORE(1300)
1625 if (isnan(b)) return Qfalse;
1626 #endif
1628 else {
1629 return num_equal(x, y);
1631 a = RFLOAT_VALUE(x);
1632 #if MSC_VERSION_BEFORE(1300)
1633 if (isnan(a)) return Qfalse;
1634 #endif
1635 return RBOOL(a == b);
1638 #define flo_eq rb_float_equal
1639 static VALUE rb_dbl_hash(double d);
1642 * call-seq:
1643 * hash -> integer
1645 * Returns the integer hash value for +self+.
1647 * See also Object#hash.
1650 static VALUE
1651 flo_hash(VALUE num)
1653 return rb_dbl_hash(RFLOAT_VALUE(num));
1656 static VALUE
1657 rb_dbl_hash(double d)
1659 return ST2FIX(rb_dbl_long_hash(d));
1662 VALUE
1663 rb_dbl_cmp(double a, double b)
1665 if (isnan(a) || isnan(b)) return Qnil;
1666 if (a == b) return INT2FIX(0);
1667 if (a > b) return INT2FIX(1);
1668 if (a < b) return INT2FIX(-1);
1669 return Qnil;
1673 * call-seq:
1674 * self <=> other -> -1, 0, +1, or nil
1676 * Returns a value that depends on the numeric relation
1677 * between +self+ and +other+:
1679 * - -1, if +self+ is less than +other+.
1680 * - 0, if +self+ is equal to +other+.
1681 * - 1, if +self+ is greater than +other+.
1682 * - +nil+, if the two values are incommensurate.
1684 * Examples:
1686 * 2.0 <=> 2 # => 0
1687 2.0 <=> 2.0 # => 0
1688 2.0 <=> Rational(2, 1) # => 0
1689 2.0 <=> Complex(2, 0) # => 0
1690 2.0 <=> 1.9 # => 1
1691 2.0 <=> 2.1 # => -1
1692 2.0 <=> 'foo' # => nil
1694 * This is the basis for the tests in the Comparable module.
1696 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1700 static VALUE
1701 flo_cmp(VALUE x, VALUE y)
1703 double a, b;
1704 VALUE i;
1706 a = RFLOAT_VALUE(x);
1707 if (isnan(a)) return Qnil;
1708 if (RB_INTEGER_TYPE_P(y)) {
1709 VALUE rel = rb_integer_float_cmp(y, x);
1710 if (FIXNUM_P(rel))
1711 return LONG2FIX(-FIX2LONG(rel));
1712 return rel;
1714 else if (RB_FLOAT_TYPE_P(y)) {
1715 b = RFLOAT_VALUE(y);
1717 else {
1718 if (isinf(a) && (i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0)) != Qundef) {
1719 if (RTEST(i)) {
1720 int j = rb_cmpint(i, x, y);
1721 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1722 return INT2FIX(j);
1724 if (a > 0.0) return INT2FIX(1);
1725 return INT2FIX(-1);
1727 return rb_num_coerce_cmp(x, y, id_cmp);
1729 return rb_dbl_cmp(a, b);
1732 MJIT_FUNC_EXPORTED int
1733 rb_float_cmp(VALUE x, VALUE y)
1735 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1739 * call-seq:
1740 * self > other -> true or false
1742 * Returns +true+ if +self+ is numerically greater than +other+:
1744 * 2.0 > 1 # => true
1745 * 2.0 > 1.0 # => true
1746 * 2.0 > Rational(1, 2) # => true
1747 * 2.0 > 2.0 # => false
1749 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1753 VALUE
1754 rb_float_gt(VALUE x, VALUE y)
1756 double a, b;
1758 a = RFLOAT_VALUE(x);
1759 if (RB_INTEGER_TYPE_P(y)) {
1760 VALUE rel = rb_integer_float_cmp(y, x);
1761 if (FIXNUM_P(rel))
1762 return RBOOL(-FIX2LONG(rel) > 0);
1763 return Qfalse;
1765 else if (RB_FLOAT_TYPE_P(y)) {
1766 b = RFLOAT_VALUE(y);
1767 #if MSC_VERSION_BEFORE(1300)
1768 if (isnan(b)) return Qfalse;
1769 #endif
1771 else {
1772 return rb_num_coerce_relop(x, y, '>');
1774 #if MSC_VERSION_BEFORE(1300)
1775 if (isnan(a)) return Qfalse;
1776 #endif
1777 return RBOOL(a > b);
1781 * call-seq:
1782 * self >= other -> true or false
1784 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1786 * 2.0 >= 1 # => true
1787 * 2.0 >= 1.0 # => true
1788 * 2.0 >= Rational(1, 2) # => true
1789 * 2.0 >= 2.0 # => true
1790 * 2.0 >= 2.1 # => false
1792 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1796 static VALUE
1797 flo_ge(VALUE x, VALUE y)
1799 double a, b;
1801 a = RFLOAT_VALUE(x);
1802 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1803 VALUE rel = rb_integer_float_cmp(y, x);
1804 if (FIXNUM_P(rel))
1805 return RBOOL(-FIX2LONG(rel) >= 0);
1806 return Qfalse;
1808 else if (RB_FLOAT_TYPE_P(y)) {
1809 b = RFLOAT_VALUE(y);
1810 #if MSC_VERSION_BEFORE(1300)
1811 if (isnan(b)) return Qfalse;
1812 #endif
1814 else {
1815 return rb_num_coerce_relop(x, y, idGE);
1817 #if MSC_VERSION_BEFORE(1300)
1818 if (isnan(a)) return Qfalse;
1819 #endif
1820 return RBOOL(a >= b);
1824 * call-seq:
1825 * self < other -> true or false
1827 * Returns +true+ if +self+ is numerically less than +other+:
1829 * 2.0 < 3 # => true
1830 * 2.0 < 3.0 # => true
1831 * 2.0 < Rational(3, 1) # => true
1832 * 2.0 < 2.0 # => false
1834 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1838 static VALUE
1839 flo_lt(VALUE x, VALUE y)
1841 double a, b;
1843 a = RFLOAT_VALUE(x);
1844 if (RB_INTEGER_TYPE_P(y)) {
1845 VALUE rel = rb_integer_float_cmp(y, x);
1846 if (FIXNUM_P(rel))
1847 return RBOOL(-FIX2LONG(rel) < 0);
1848 return Qfalse;
1850 else if (RB_FLOAT_TYPE_P(y)) {
1851 b = RFLOAT_VALUE(y);
1852 #if MSC_VERSION_BEFORE(1300)
1853 if (isnan(b)) return Qfalse;
1854 #endif
1856 else {
1857 return rb_num_coerce_relop(x, y, '<');
1859 #if MSC_VERSION_BEFORE(1300)
1860 if (isnan(a)) return Qfalse;
1861 #endif
1862 return RBOOL(a < b);
1866 * call-seq:
1867 * self <= other -> true or false
1869 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1871 * 2.0 <= 3 # => true
1872 * 2.0 <= 3.0 # => true
1873 * 2.0 <= Rational(3, 1) # => true
1874 * 2.0 <= 2.0 # => true
1875 * 2.0 <= 1.0 # => false
1877 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1881 static VALUE
1882 flo_le(VALUE x, VALUE y)
1884 double a, b;
1886 a = RFLOAT_VALUE(x);
1887 if (RB_INTEGER_TYPE_P(y)) {
1888 VALUE rel = rb_integer_float_cmp(y, x);
1889 if (FIXNUM_P(rel))
1890 return RBOOL(-FIX2LONG(rel) <= 0);
1891 return Qfalse;
1893 else if (RB_FLOAT_TYPE_P(y)) {
1894 b = RFLOAT_VALUE(y);
1895 #if MSC_VERSION_BEFORE(1300)
1896 if (isnan(b)) return Qfalse;
1897 #endif
1899 else {
1900 return rb_num_coerce_relop(x, y, idLE);
1902 #if MSC_VERSION_BEFORE(1300)
1903 if (isnan(a)) return Qfalse;
1904 #endif
1905 return RBOOL(a <= b);
1909 * call-seq:
1910 * eql?(other) -> true or false
1912 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1913 * +false+ otherwise:
1915 * 2.0.eql?(2.0) # => true
1916 * 2.0.eql?(1.0) # => false
1917 * 2.0.eql?(1) # => false
1918 * 2.0.eql?(Rational(2, 1)) # => false
1919 * 2.0.eql?(Complex(2, 0)) # => false
1921 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1923 * Related: Float#== (performs type conversions).
1926 MJIT_FUNC_EXPORTED VALUE
1927 rb_float_eql(VALUE x, VALUE y)
1929 if (RB_FLOAT_TYPE_P(y)) {
1930 double a = RFLOAT_VALUE(x);
1931 double b = RFLOAT_VALUE(y);
1932 #if MSC_VERSION_BEFORE(1300)
1933 if (isnan(a) || isnan(b)) return Qfalse;
1934 #endif
1935 return RBOOL(a == b);
1937 return Qfalse;
1940 #define flo_eql rb_float_eql
1942 MJIT_FUNC_EXPORTED VALUE
1943 rb_float_abs(VALUE flt)
1945 double val = fabs(RFLOAT_VALUE(flt));
1946 return DBL2NUM(val);
1950 * call-seq:
1951 * nan? -> true or false
1953 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1955 * f = -1.0 #=> -1.0
1956 * f.nan? #=> false
1957 * f = 0.0/0.0 #=> NaN
1958 * f.nan? #=> true
1961 static VALUE
1962 flo_is_nan_p(VALUE num)
1964 double value = RFLOAT_VALUE(num);
1966 return RBOOL(isnan(value));
1970 * call-seq:
1971 * infinite? -> -1, 1, or nil
1973 * Returns:
1975 * - 1, if +self+ is <tt>Infinity</tt>.
1976 * - -1 if +self+ is <tt>-Infinity</tt>.
1977 * - +nil+, otherwise.
1979 * Examples:
1981 * f = 1.0/0.0 # => Infinity
1982 * f.infinite? # => 1
1983 * f = -1.0/0.0 # => -Infinity
1984 * f.infinite? # => -1
1985 * f = 1.0 # => 1.0
1986 * f.infinite? # => nil
1987 * f = 0.0/0.0 # => NaN
1988 * f.infinite? # => nil
1992 VALUE
1993 rb_flo_is_infinite_p(VALUE num)
1995 double value = RFLOAT_VALUE(num);
1997 if (isinf(value)) {
1998 return INT2FIX( value < 0 ? -1 : 1 );
2001 return Qnil;
2005 * call-seq:
2006 * finite? -> true or false
2008 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +Nan+,
2009 * +false+ otherwise:
2011 * f = 2.0 # => 2.0
2012 * f.finite? # => true
2013 * f = 1.0/0.0 # => Infinity
2014 * f.finite? # => false
2015 * f = -1.0/0.0 # => -Infinity
2016 * f.finite? # => false
2017 * f = 0.0/0.0 # => NaN
2018 * f.finite? # => false
2022 VALUE
2023 rb_flo_is_finite_p(VALUE num)
2025 double value = RFLOAT_VALUE(num);
2027 return RBOOL(isfinite(value));
2030 static VALUE
2031 flo_nextafter(VALUE flo, double value)
2033 double x, y;
2034 x = NUM2DBL(flo);
2035 y = nextafter(x, value);
2036 return DBL2NUM(y);
2040 * call-seq:
2041 * next_float -> float
2043 * Returns the next-larger representable \Float.
2045 * These examples show the internally stored values (64-bit hexadecimal)
2046 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2048 * f = 0.0 # 0x0000000000000000
2049 * f.next_float # 0x0000000000000001
2051 * f = 0.01 # 0x3f847ae147ae147b
2052 * f.next_float # 0x3f847ae147ae147c
2054 * In the remaining examples here, the output is shown in the usual way
2055 * (result +to_s+):
2057 * 0.01.next_float # => 0.010000000000000002
2058 * 1.0.next_float # => 1.0000000000000002
2059 * 100.0.next_float # => 100.00000000000001
2061 * f = 0.01
2062 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2064 * Output:
2066 * 0 0x1.47ae147ae147bp-7 0.01
2067 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2068 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2069 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2071 * f = 0.0; 100.times { f += 0.1 }
2072 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2073 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2074 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2075 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2076 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2077 * "%a" % 10 # => "0x1.4p+3"
2078 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2080 * Related: Float#prev_float
2083 static VALUE
2084 flo_next_float(VALUE vx)
2086 return flo_nextafter(vx, HUGE_VAL);
2090 * call-seq:
2091 * float.prev_float -> float
2093 * Returns the next-smaller representable \Float.
2095 * These examples show the internally stored values (64-bit hexadecimal)
2096 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2098 * f = 5e-324 # 0x0000000000000001
2099 * f.prev_float # 0x0000000000000000
2101 * f = 0.01 # 0x3f847ae147ae147b
2102 * f.prev_float # 0x3f847ae147ae147a
2104 * In the remaining examples here, the output is shown in the usual way
2105 * (result +to_s+):
2107 * 0.01.prev_float # => 0.009999999999999998
2108 * 1.0.prev_float # => 0.9999999999999999
2109 * 100.0.prev_float # => 99.99999999999999
2111 * f = 0.01
2112 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2114 * Output:
2116 * 0 0x1.47ae147ae147bp-7 0.01
2117 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2118 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2119 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2121 * Related: Float#next_float.
2124 static VALUE
2125 flo_prev_float(VALUE vx)
2127 return flo_nextafter(vx, -HUGE_VAL);
2130 VALUE
2131 rb_float_floor(VALUE num, int ndigits)
2133 double number;
2134 number = RFLOAT_VALUE(num);
2135 if (number == 0.0) {
2136 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2138 if (ndigits > 0) {
2139 int binexp;
2140 double f, mul, res;
2141 frexp(number, &binexp);
2142 if (float_round_overflow(ndigits, binexp)) return num;
2143 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2144 return DBL2NUM(0.0);
2145 f = pow(10, ndigits);
2146 mul = floor(number * f);
2147 res = (mul + 1) / f;
2148 if (res > number)
2149 res = mul / f;
2150 return DBL2NUM(res);
2152 else {
2153 num = dbl2ival(floor(number));
2154 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2155 return num;
2159 static int
2160 flo_ndigits(int argc, VALUE *argv)
2162 if (rb_check_arity(argc, 0, 1)) {
2163 return NUM2INT(argv[0]);
2165 return 0;
2169 * call-seq:
2170 * floor(ndigits = 0) -> float or integer
2172 * Returns the largest number less than or equal to +self+ with
2173 * a precision of +ndigits+ decimal digits.
2175 * When +ndigits+ is positive, returns a float with +ndigits+
2176 * digits after the decimal point (as available):
2178 * f = 12345.6789
2179 * f.floor(1) # => 12345.6
2180 * f.floor(3) # => 12345.678
2181 * f = -12345.6789
2182 * f.floor(1) # => -12345.7
2183 * f.floor(3) # => -12345.679
2185 * When +ndigits+ is non-positive, returns an integer with at least
2186 * <code>ndigits.abs</code> trailing zeros:
2188 * f = 12345.6789
2189 * f.floor(0) # => 12345
2190 * f.floor(-3) # => 12000
2191 * f = -12345.6789
2192 * f.floor(0) # => -12346
2193 * f.floor(-3) # => -13000
2195 * Note that the limited precision of floating-point arithmetic
2196 * may lead to surprising results:
2198 * (0.3 / 0.1).floor #=> 2 (!)
2200 * Related: Float#ceil.
2204 static VALUE
2205 flo_floor(int argc, VALUE *argv, VALUE num)
2207 int ndigits = flo_ndigits(argc, argv);
2208 return rb_float_floor(num, ndigits);
2212 * call-seq:
2213 * ceil(ndigits = 0) -> float or integer
2215 * Returns the smallest number greater than or equal to +self+ with
2216 * a precision of +ndigits+ decimal digits.
2218 * When +ndigits+ is positive, returns a float with +ndigits+
2219 * digits after the decimal point (as available):
2221 * f = 12345.6789
2222 * f.ceil(1) # => 12345.7
2223 * f.ceil(3) # => 12345.679
2224 * f = -12345.6789
2225 * f.ceil(1) # => -12345.6
2226 * f.ceil(3) # => -12345.678
2228 * When +ndigits+ is non-positive, returns an integer with at least
2229 * <code>ndigits.abs</code> trailing zeros:
2231 * f = 12345.6789
2232 * f.ceil(0) # => 12346
2233 * f.ceil(-3) # => 13000
2234 * f = -12345.6789
2235 * f.ceil(0) # => -12345
2236 * f.ceil(-3) # => -12000
2238 * Note that the limited precision of floating-point arithmetic
2239 * may lead to surprising results:
2241 * (2.1 / 0.7).ceil #=> 4 (!)
2243 * Related: Float#floor.
2247 static VALUE
2248 flo_ceil(int argc, VALUE *argv, VALUE num)
2250 int ndigits = flo_ndigits(argc, argv);
2251 return rb_float_ceil(num, ndigits);
2254 VALUE
2255 rb_float_ceil(VALUE num, int ndigits)
2257 double number, f;
2259 number = RFLOAT_VALUE(num);
2260 if (number == 0.0) {
2261 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2263 if (ndigits > 0) {
2264 int binexp;
2265 frexp(number, &binexp);
2266 if (float_round_overflow(ndigits, binexp)) return num;
2267 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2268 return DBL2NUM(0.0);
2269 f = pow(10, ndigits);
2270 f = ceil(number * f) / f;
2271 return DBL2NUM(f);
2273 else {
2274 num = dbl2ival(ceil(number));
2275 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2276 return num;
2280 static int
2281 int_round_zero_p(VALUE num, int ndigits)
2283 long bytes;
2284 /* If 10**N / 2 > num, then return 0 */
2285 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2286 if (FIXNUM_P(num)) {
2287 bytes = sizeof(long);
2289 else if (RB_BIGNUM_TYPE_P(num)) {
2290 bytes = rb_big_size(num);
2292 else {
2293 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2295 return (-0.415241 * ndigits - 0.125 > bytes);
2298 static SIGNED_VALUE
2299 int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2301 SIGNED_VALUE z = +(x + y / 2) / y;
2302 if ((z * y - x) * 2 == y) {
2303 z &= ~1;
2305 return z * y;
2308 static SIGNED_VALUE
2309 int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2311 return (x + y / 2) / y * y;
2314 static SIGNED_VALUE
2315 int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2317 return (x + y / 2 - 1) / y * y;
2320 static int
2321 int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2323 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2326 static int
2327 int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2329 return int_pos_p(num);
2332 static int
2333 int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2335 return int_neg_p(num);
2339 * Assumes num is an Integer, ndigits <= 0
2341 static VALUE
2342 rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2344 VALUE n, f, h, r;
2346 if (int_round_zero_p(num, ndigits)) {
2347 return INT2FIX(0);
2350 f = int_pow(10, -ndigits);
2351 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2352 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2353 int neg = x < 0;
2354 if (neg) x = -x;
2355 x = ROUND_CALL(mode, int_round, (x, y));
2356 if (neg) x = -x;
2357 return LONG2NUM(x);
2359 if (RB_FLOAT_TYPE_P(f)) {
2360 /* then int_pow overflow */
2361 return INT2FIX(0);
2363 h = rb_int_idiv(f, INT2FIX(2));
2364 r = rb_int_modulo(num, f);
2365 n = rb_int_minus(num, r);
2366 r = rb_int_cmp(r, h);
2367 if (FIXNUM_POSITIVE_P(r) ||
2368 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2369 n = rb_int_plus(n, f);
2371 return n;
2374 static VALUE
2375 rb_int_floor(VALUE num, int ndigits)
2377 VALUE f;
2379 if (int_round_zero_p(num, ndigits))
2380 return INT2FIX(0);
2381 f = int_pow(10, -ndigits);
2382 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2383 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2384 int neg = x < 0;
2385 if (neg) x = -x + y - 1;
2386 x = x / y * y;
2387 if (neg) x = -x;
2388 return LONG2NUM(x);
2390 if (RB_FLOAT_TYPE_P(f)) {
2391 /* then int_pow overflow */
2392 return INT2FIX(0);
2394 return rb_int_minus(num, rb_int_modulo(num, f));
2397 static VALUE
2398 rb_int_ceil(VALUE num, int ndigits)
2400 VALUE f;
2402 if (int_round_zero_p(num, ndigits))
2403 return INT2FIX(0);
2404 f = int_pow(10, -ndigits);
2405 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2406 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2407 int neg = x < 0;
2408 if (neg) x = -x;
2409 else x += y - 1;
2410 x = (x / y) * y;
2411 if (neg) x = -x;
2412 return LONG2NUM(x);
2414 if (RB_FLOAT_TYPE_P(f)) {
2415 /* then int_pow overflow */
2416 return INT2FIX(0);
2418 return rb_int_plus(num, rb_int_minus(f, rb_int_modulo(num, f)));
2421 VALUE
2422 rb_int_truncate(VALUE num, int ndigits)
2424 VALUE f;
2425 VALUE m;
2427 if (int_round_zero_p(num, ndigits))
2428 return INT2FIX(0);
2429 f = int_pow(10, -ndigits);
2430 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2431 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2432 int neg = x < 0;
2433 if (neg) x = -x;
2434 x = x / y * y;
2435 if (neg) x = -x;
2436 return LONG2NUM(x);
2438 if (RB_FLOAT_TYPE_P(f)) {
2439 /* then int_pow overflow */
2440 return INT2FIX(0);
2442 m = rb_int_modulo(num, f);
2443 if (int_neg_p(num)) {
2444 return rb_int_plus(num, rb_int_minus(f, m));
2446 else {
2447 return rb_int_minus(num, m);
2452 * call-seq:
2453 * round(ndigits = 0, half: :up]) -> integer or float
2455 * Returns +self+ rounded to the nearest value with
2456 * a precision of +ndigits+ decimal digits.
2458 * When +ndigits+ is non-negative, returns a float with +ndigits+
2459 * after the decimal point (as available):
2461 * f = 12345.6789
2462 * f.round(1) # => 12345.7
2463 * f.round(3) # => 12345.679
2464 * f = -12345.6789
2465 * f.round(1) # => -12345.7
2466 * f.round(3) # => -12345.679
2468 * When +ndigits+ is negative, returns an integer
2469 * with at least <tt>ndigits.abs</tt> trailing zeros:
2471 * f = 12345.6789
2472 * f.round(0) # => 12346
2473 * f.round(-3) # => 12000
2474 * f = -12345.6789
2475 * f.round(0) # => -12346
2476 * f.round(-3) # => -12000
2478 * If keyword argument +half+ is given,
2479 * and +self+ is equidistant from the two candidate values,
2480 * the rounding is according to the given +half+ value:
2482 * - +:up+ or +nil+: round away from zero:
2484 * 2.5.round(half: :up) # => 3
2485 * 3.5.round(half: :up) # => 4
2486 * (-2.5).round(half: :up) # => -3
2488 * - +:down+: round toward zero:
2490 * 2.5.round(half: :down) # => 2
2491 * 3.5.round(half: :down) # => 3
2492 * (-2.5).round(half: :down) # => -2
2494 * - +:even+: round toward the candidate whose last nonzero digit is even:
2496 * 2.5.round(half: :even) # => 2
2497 * 3.5.round(half: :even) # => 4
2498 * (-2.5).round(half: :even) # => -2
2500 * Raises and exception if the value for +half+ is invalid.
2502 * Related: Float#truncate.
2506 static VALUE
2507 flo_round(int argc, VALUE *argv, VALUE num)
2509 double number, f, x;
2510 VALUE nd, opt;
2511 int ndigits = 0;
2512 enum ruby_num_rounding_mode mode;
2514 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2515 ndigits = NUM2INT(nd);
2517 mode = rb_num_get_rounding_option(opt);
2518 number = RFLOAT_VALUE(num);
2519 if (number == 0.0) {
2520 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2522 if (ndigits < 0) {
2523 return rb_int_round(flo_to_i(num), ndigits, mode);
2525 if (ndigits == 0) {
2526 x = ROUND_CALL(mode, round, (number, 1.0));
2527 return dbl2ival(x);
2529 if (isfinite(number)) {
2530 int binexp;
2531 frexp(number, &binexp);
2532 if (float_round_overflow(ndigits, binexp)) return num;
2533 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2534 if (ndigits > 14) {
2535 /* In this case, pow(10, ndigits) may not be accurate. */
2536 return rb_flo_round_by_rational(argc, argv, num);
2538 f = pow(10, ndigits);
2539 x = ROUND_CALL(mode, round, (number, f));
2540 return DBL2NUM(x / f);
2542 return num;
2545 static int
2546 float_round_overflow(int ndigits, int binexp)
2548 enum {float_dig = DBL_DIG+2};
2550 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2551 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2552 Recall that up to float_dig digits can be needed to represent a double,
2553 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2554 will be an integer and thus the result is the original number.
2555 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2556 if ndigits + exp < 0, the result is 0.
2557 We have:
2558 2 ** (binexp-1) <= |number| < 2 ** binexp
2559 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2560 If binexp >= 0, and since log_2(10) = 3.322259:
2561 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2562 floor(binexp/4) <= exp <= ceil(binexp/3)
2563 If binexp <= 0, swap the /4 and the /3
2564 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2565 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2567 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2568 return TRUE;
2570 return FALSE;
2573 static int
2574 float_round_underflow(int ndigits, int binexp)
2576 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2577 return TRUE;
2579 return FALSE;
2583 * call-seq:
2584 * to_i -> integer
2586 * Returns +self+ truncated to an Integer.
2588 * 1.2.to_i # => 1
2589 * (-1.2).to_i # => -1
2591 * Note that the limited precision of floating-point arithmetic
2592 * may lead to surprising results:
2594 * (0.3 / 0.1).to_i # => 2 (!)
2596 * Float#to_int is an alias for Float#to_i.
2599 static VALUE
2600 flo_to_i(VALUE num)
2602 double f = RFLOAT_VALUE(num);
2604 if (f > 0.0) f = floor(f);
2605 if (f < 0.0) f = ceil(f);
2607 return dbl2ival(f);
2611 * call-seq:
2612 * truncate(ndigits = 0) -> float or integer
2614 * Returns +self+ truncated (toward zero) to
2615 * a precision of +ndigits+ decimal digits.
2617 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2618 * after the decimal point (as available):
2620 * f = 12345.6789
2621 * f.truncate(1) # => 12345.6
2622 * f.truncate(3) # => 12345.678
2623 * f = -12345.6789
2624 * f.truncate(1) # => -12345.6
2625 * f.truncate(3) # => -12345.678
2627 * When +ndigits+ is negative, returns an integer
2628 * with at least <tt>ndigits.abs</tt> trailing zeros:
2630 * f = 12345.6789
2631 * f.truncate(0) # => 12345
2632 * f.truncate(-3) # => 12000
2633 * f = -12345.6789
2634 * f.truncate(0) # => -12345
2635 * f.truncate(-3) # => -12000
2637 * Note that the limited precision of floating-point arithmetic
2638 * may lead to surprising results:
2640 * (0.3 / 0.1).truncate #=> 2 (!)
2642 * Related: Float#round.
2645 static VALUE
2646 flo_truncate(int argc, VALUE *argv, VALUE num)
2648 if (signbit(RFLOAT_VALUE(num)))
2649 return flo_ceil(argc, argv, num);
2650 else
2651 return flo_floor(argc, argv, num);
2655 * call-seq:
2656 * floor(digits = 0) -> integer or float
2658 * Returns the largest number that is less than or equal to +self+ with
2659 * a precision of +digits+ decimal digits.
2661 * \Numeric implements this by converting +self+ to a Float and
2662 * invoking Float#floor.
2665 static VALUE
2666 num_floor(int argc, VALUE *argv, VALUE num)
2668 return flo_floor(argc, argv, rb_Float(num));
2672 * call-seq:
2673 * ceil(digits = 0) -> integer or float
2675 * Returns the smallest number that is greater than or equal to +self+ with
2676 * a precision of +digits+ decimal digits.
2678 * \Numeric implements this by converting +self+ to a Float and
2679 * invoking Float#ceil.
2682 static VALUE
2683 num_ceil(int argc, VALUE *argv, VALUE num)
2685 return flo_ceil(argc, argv, rb_Float(num));
2689 * call-seq:
2690 * round(digits = 0) -> integer or float
2692 * Returns +self+ rounded to the nearest value with
2693 * a precision of +digits+ decimal digits.
2695 * \Numeric implements this by converting +self+ to a Float and
2696 * invoking Float#round.
2699 static VALUE
2700 num_round(int argc, VALUE* argv, VALUE num)
2702 return flo_round(argc, argv, rb_Float(num));
2706 * call-seq:
2707 * truncate(digits = 0) -> integer or float
2709 * Returns +self+ truncated (toward zero) to
2710 * a precision of +digits+ decimal digits.
2712 * \Numeric implements this by converting +self+ to a Float and
2713 * invoking Float#truncate.
2716 static VALUE
2717 num_truncate(int argc, VALUE *argv, VALUE num)
2719 return flo_truncate(argc, argv, rb_Float(num));
2722 double
2723 ruby_float_step_size(double beg, double end, double unit, int excl)
2725 const double epsilon = DBL_EPSILON;
2726 double d, n, err;
2728 if (unit == 0) {
2729 return HUGE_VAL;
2731 if (isinf(unit)) {
2732 return unit > 0 ? beg <= end : beg >= end;
2734 n= (end - beg)/unit;
2735 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2736 if (err>0.5) err=0.5;
2737 if (excl) {
2738 if (n<=0) return 0;
2739 if (n<1)
2740 n = 0;
2741 else
2742 n = floor(n - err);
2743 d = +((n + 1) * unit) + beg;
2744 if (beg < end) {
2745 if (d < end)
2746 n++;
2748 else if (beg > end) {
2749 if (d > end)
2750 n++;
2753 else {
2754 if (n<0) return 0;
2755 n = floor(n + err);
2756 d = +((n + 1) * unit) + beg;
2757 if (beg < end) {
2758 if (d <= end)
2759 n++;
2761 else if (beg > end) {
2762 if (d >= end)
2763 n++;
2766 return n+1;
2770 ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2772 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2773 double unit = NUM2DBL(step);
2774 double beg = NUM2DBL(from);
2775 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2776 double n = ruby_float_step_size(beg, end, unit, excl);
2777 long i;
2779 if (isinf(unit)) {
2780 /* if unit is infinity, i*unit+beg is NaN */
2781 if (n) rb_yield(DBL2NUM(beg));
2783 else if (unit == 0) {
2784 VALUE val = DBL2NUM(beg);
2785 for (;;)
2786 rb_yield(val);
2788 else {
2789 for (i=0; i<n; i++) {
2790 double d = i*unit+beg;
2791 if (unit >= 0 ? end < d : d < end) d = end;
2792 rb_yield(DBL2NUM(d));
2795 return TRUE;
2797 return FALSE;
2800 VALUE
2801 ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2803 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2804 long delta, diff;
2806 diff = FIX2LONG(step);
2807 if (diff == 0) {
2808 return DBL2NUM(HUGE_VAL);
2810 delta = FIX2LONG(to) - FIX2LONG(from);
2811 if (diff < 0) {
2812 diff = -diff;
2813 delta = -delta;
2815 if (excl) {
2816 delta--;
2818 if (delta < 0) {
2819 return INT2FIX(0);
2821 return ULONG2NUM(delta / diff + 1UL);
2823 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2824 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2826 if (isinf(n)) return DBL2NUM(n);
2827 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2828 return rb_dbl2big(n);
2830 else {
2831 VALUE result;
2832 ID cmp = '>';
2833 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2834 case 0: return DBL2NUM(HUGE_VAL);
2835 case -1: cmp = '<'; break;
2837 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2838 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2839 if (!excl || RTEST(rb_funcall(rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step)), cmp, 1, to))) {
2840 result = rb_funcall(result, '+', 1, INT2FIX(1));
2842 return result;
2846 static int
2847 num_step_negative_p(VALUE num)
2849 const ID mid = '<';
2850 VALUE zero = INT2FIX(0);
2851 VALUE r;
2853 if (FIXNUM_P(num)) {
2854 if (method_basic_p(rb_cInteger))
2855 return (SIGNED_VALUE)num < 0;
2857 else if (RB_BIGNUM_TYPE_P(num)) {
2858 if (method_basic_p(rb_cInteger))
2859 return BIGNUM_NEGATIVE_P(num);
2862 r = rb_check_funcall(num, '>', 1, &zero);
2863 if (r == Qundef) {
2864 coerce_failed(num, INT2FIX(0));
2866 return !RTEST(r);
2869 static int
2870 num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2872 VALUE hash;
2874 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2875 if (!NIL_P(hash)) {
2876 ID keys[2];
2877 VALUE values[2];
2878 keys[0] = id_to;
2879 keys[1] = id_by;
2880 rb_get_kwargs(hash, keys, 0, 2, values);
2881 if (values[0] != Qundef) {
2882 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2883 *to = values[0];
2885 if (values[1] != Qundef) {
2886 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2887 *by = values[1];
2891 return argc;
2894 static int
2895 num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2897 int desc;
2898 if (by != Qundef) {
2899 *step = by;
2901 else {
2902 /* compatibility */
2903 if (argc > 1 && NIL_P(*step)) {
2904 rb_raise(rb_eTypeError, "step must be numeric");
2907 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2908 rb_raise(rb_eArgError, "step can't be 0");
2910 if (NIL_P(*step)) {
2911 *step = INT2FIX(1);
2913 desc = num_step_negative_p(*step);
2914 if (fix_nil && NIL_P(*to)) {
2915 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2917 return desc;
2920 static int
2921 num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2923 VALUE by = Qundef;
2924 argc = num_step_extract_args(argc, argv, to, step, &by);
2925 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2928 static VALUE
2929 num_step_size(VALUE from, VALUE args, VALUE eobj)
2931 VALUE to, step;
2932 int argc = args ? RARRAY_LENINT(args) : 0;
2933 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2935 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2937 return ruby_num_interval_step_size(from, to, step, FALSE);
2941 * call-seq:
2942 * step(to = nil, by = 1) {|n| ... } -> self
2943 * step(to = nil, by = 1) -> enumerator
2944 * step(to = nil, by: 1) {|n| ... } -> self
2945 * step(to = nil, by: 1) -> enumerator
2946 * step(by: 1, to: ) {|n| ... } -> self
2947 * step(by: 1, to: ) -> enumerator
2948 * step(by: , to: nil) {|n| ... } -> self
2949 * step(by: , to: nil) -> enumerator
2951 * Generates a sequence of numbers; with a block given, traverses the sequence.
2953 * Of the Core and Standard Library classes,
2954 * Integer, Float, and Rational use this implementation.
2956 * A quick example:
2958 * squares = []
2959 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2960 * squares # => [1, 9, 25, 49, 81]
2962 * The generated sequence:
2964 * - Begins with +self+.
2965 * - Continues at intervals of +step+ (which may not be zero).
2966 * - Ends with the last number that is within or equal to +limit+;
2967 * that is, less than or equal to +limit+ if +step+ is positive,
2968 * greater than or equal to +limit+ if +step+ is negative.
2969 * If +limit+ is not given, the sequence is of infinite length.
2971 * If a block is given, calls the block with each number in the sequence;
2972 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2974 * <b>Keyword Arguments</b>
2976 * With keyword arguments +by+ and +to+,
2977 * their values (or defaults) determine the step and limit:
2979 * # Both keywords given.
2980 * squares = []
2981 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2982 * squares # => [16, 36, 64, 100]
2983 * cubes = []
2984 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2985 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2986 * squares = []
2987 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2988 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2990 * squares = []
2991 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2992 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2994 * # Only keyword to given.
2995 * squares = []
2996 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
2997 * squares # => [16, 25, 36, 49, 64, 81, 100]
2998 * # Only by given.
3000 * # Only keyword by given
3001 * squares = []
3002 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3003 * squares # => [16, 36, 64, 100, 144]
3005 * # No block given.
3006 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3007 * e.class # => Enumerator::ArithmeticSequence
3009 * <b>Positional Arguments</b>
3011 * With optional positional arguments +limit+ and +step+,
3012 * their values (or defaults) determine the step and limit:
3014 * squares = []
3015 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3016 * squares # => [16, 36, 64, 100]
3017 * squares = []
3018 * 4.step(10) {|i| squares.push(i*i) }
3019 * squares # => [16, 25, 36, 49, 64, 81, 100]
3020 * squares = []
3021 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3022 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3024 * <b>Implementation Notes</b>
3026 * If all the arguments are integers, the loop operates using an integer
3027 * counter.
3029 * If any of the arguments are floating point numbers, all are converted
3030 * to floats, and the loop is executed
3031 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3032 * where <i>n = (limit - self)/step</i>.
3036 static VALUE
3037 num_step(int argc, VALUE *argv, VALUE from)
3039 VALUE to, step;
3040 int desc, inf;
3042 if (!rb_block_given_p()) {
3043 VALUE by = Qundef;
3045 num_step_extract_args(argc, argv, &to, &step, &by);
3046 if (by != Qundef) {
3047 step = by;
3049 if (NIL_P(step)) {
3050 step = INT2FIX(1);
3052 else if (rb_equal(step, INT2FIX(0))) {
3053 rb_raise(rb_eArgError, "step can't be 0");
3055 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3056 rb_obj_is_kind_of(step, rb_cNumeric)) {
3057 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3058 num_step_size, from, to, step, FALSE);
3061 return SIZED_ENUMERATOR(from, 2, ((VALUE [2]){to, step}), num_step_size);
3064 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3065 if (rb_equal(step, INT2FIX(0))) {
3066 inf = 1;
3068 else if (RB_FLOAT_TYPE_P(to)) {
3069 double f = RFLOAT_VALUE(to);
3070 inf = isinf(f) && (signbit(f) ? desc : !desc);
3072 else inf = 0;
3074 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3075 long i = FIX2LONG(from);
3076 long diff = FIX2LONG(step);
3078 if (inf) {
3079 for (;; i += diff)
3080 rb_yield(LONG2FIX(i));
3082 else {
3083 long end = FIX2LONG(to);
3085 if (desc) {
3086 for (; i >= end; i += diff)
3087 rb_yield(LONG2FIX(i));
3089 else {
3090 for (; i <= end; i += diff)
3091 rb_yield(LONG2FIX(i));
3095 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3096 VALUE i = from;
3098 if (inf) {
3099 for (;; i = rb_funcall(i, '+', 1, step))
3100 rb_yield(i);
3102 else {
3103 ID cmp = desc ? '<' : '>';
3105 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3106 rb_yield(i);
3109 return from;
3112 static char *
3113 out_of_range_float(char (*pbuf)[24], VALUE val)
3115 char *const buf = *pbuf;
3116 char *s;
3118 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3119 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3120 return buf;
3123 #define FLOAT_OUT_OF_RANGE(val, type) do { \
3124 char buf[24]; \
3125 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3126 out_of_range_float(&buf, (val))); \
3127 } while (0)
3129 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3130 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3131 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3132 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3133 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3134 LONG_MIN <= (n): \
3135 LONG_MIN_MINUS_ONE < (n))
3137 long
3138 rb_num2long(VALUE val)
3140 again:
3141 if (NIL_P(val)) {
3142 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3145 if (FIXNUM_P(val)) return FIX2LONG(val);
3147 else if (RB_FLOAT_TYPE_P(val)) {
3148 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3149 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3150 return (long)RFLOAT_VALUE(val);
3152 else {
3153 FLOAT_OUT_OF_RANGE(val, "integer");
3156 else if (RB_BIGNUM_TYPE_P(val)) {
3157 return rb_big2long(val);
3159 else {
3160 val = rb_to_int(val);
3161 goto again;
3165 static unsigned long
3166 rb_num2ulong_internal(VALUE val, int *wrap_p)
3168 again:
3169 if (NIL_P(val)) {
3170 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3173 if (FIXNUM_P(val)) {
3174 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3175 if (wrap_p)
3176 *wrap_p = l < 0;
3177 return (unsigned long)l;
3179 else if (RB_FLOAT_TYPE_P(val)) {
3180 double d = RFLOAT_VALUE(val);
3181 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3182 if (wrap_p)
3183 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3184 if (0 <= d)
3185 return (unsigned long)d;
3186 return (unsigned long)(long)d;
3188 else {
3189 FLOAT_OUT_OF_RANGE(val, "integer");
3192 else if (RB_BIGNUM_TYPE_P(val)) {
3194 unsigned long ul = rb_big2ulong(val);
3195 if (wrap_p)
3196 *wrap_p = BIGNUM_NEGATIVE_P(val);
3197 return ul;
3200 else {
3201 val = rb_to_int(val);
3202 goto again;
3206 unsigned long
3207 rb_num2ulong(VALUE val)
3209 return rb_num2ulong_internal(val, NULL);
3212 void
3213 rb_out_of_int(SIGNED_VALUE num)
3215 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'",
3216 num, num < 0 ? "small" : "big");
3219 #if SIZEOF_INT < SIZEOF_LONG
3220 static void
3221 check_int(long num)
3223 if ((long)(int)num != num) {
3224 rb_out_of_int(num);
3228 static void
3229 check_uint(unsigned long num, int sign)
3231 if (sign) {
3232 /* minus */
3233 if (num < (unsigned long)INT_MIN)
3234 rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned int'", (long)num);
3236 else {
3237 /* plus */
3238 if (UINT_MAX < num)
3239 rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num);
3243 long
3244 rb_num2int(VALUE val)
3246 long num = rb_num2long(val);
3248 check_int(num);
3249 return num;
3252 long
3253 rb_fix2int(VALUE val)
3255 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3257 check_int(num);
3258 return num;
3261 unsigned long
3262 rb_num2uint(VALUE val)
3264 int wrap;
3265 unsigned long num = rb_num2ulong_internal(val, &wrap);
3267 check_uint(num, wrap);
3268 return num;
3271 unsigned long
3272 rb_fix2uint(VALUE val)
3274 unsigned long num;
3276 if (!FIXNUM_P(val)) {
3277 return rb_num2uint(val);
3279 num = FIX2ULONG(val);
3281 check_uint(num, FIXNUM_NEGATIVE_P(val));
3282 return num;
3284 #else
3285 long
3286 rb_num2int(VALUE val)
3288 return rb_num2long(val);
3291 long
3292 rb_fix2int(VALUE val)
3294 return FIX2INT(val);
3297 unsigned long
3298 rb_num2uint(VALUE val)
3300 return rb_num2ulong(val);
3303 unsigned long
3304 rb_fix2uint(VALUE val)
3306 return RB_FIX2ULONG(val);
3308 #endif
3310 NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3311 static void
3312 rb_out_of_short(SIGNED_VALUE num)
3314 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `short'",
3315 num, num < 0 ? "small" : "big");
3318 static void
3319 check_short(long num)
3321 if ((long)(short)num != num) {
3322 rb_out_of_short(num);
3326 static void
3327 check_ushort(unsigned long num, int sign)
3329 if (sign) {
3330 /* minus */
3331 if (num < (unsigned long)SHRT_MIN)
3332 rb_raise(rb_eRangeError, "integer %ld too small to convert to `unsigned short'", (long)num);
3334 else {
3335 /* plus */
3336 if (USHRT_MAX < num)
3337 rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned short'", num);
3341 short
3342 rb_num2short(VALUE val)
3344 long num = rb_num2long(val);
3346 check_short(num);
3347 return num;
3350 short
3351 rb_fix2short(VALUE val)
3353 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3355 check_short(num);
3356 return num;
3359 unsigned short
3360 rb_num2ushort(VALUE val)
3362 int wrap;
3363 unsigned long num = rb_num2ulong_internal(val, &wrap);
3365 check_ushort(num, wrap);
3366 return num;
3369 unsigned short
3370 rb_fix2ushort(VALUE val)
3372 unsigned long num;
3374 if (!FIXNUM_P(val)) {
3375 return rb_num2ushort(val);
3377 num = FIX2ULONG(val);
3379 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3380 return num;
3383 VALUE
3384 rb_num2fix(VALUE val)
3386 long v;
3388 if (FIXNUM_P(val)) return val;
3390 v = rb_num2long(val);
3391 if (!FIXABLE(v))
3392 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3393 return LONG2FIX(v);
3396 #if HAVE_LONG_LONG
3398 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3399 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3400 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3401 #ifndef ULLONG_MAX
3402 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3403 #endif
3404 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3405 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3406 LLONG_MIN <= (n): \
3407 LLONG_MIN_MINUS_ONE < (n))
3409 LONG_LONG
3410 rb_num2ll(VALUE val)
3412 if (NIL_P(val)) {
3413 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3416 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3418 else if (RB_FLOAT_TYPE_P(val)) {
3419 double d = RFLOAT_VALUE(val);
3420 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3421 return (LONG_LONG)d;
3423 else {
3424 FLOAT_OUT_OF_RANGE(val, "long long");
3427 else if (RB_BIGNUM_TYPE_P(val)) {
3428 return rb_big2ll(val);
3430 else if (RB_TYPE_P(val, T_STRING)) {
3431 rb_raise(rb_eTypeError, "no implicit conversion from string");
3433 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3434 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3437 val = rb_to_int(val);
3438 return NUM2LL(val);
3441 unsigned LONG_LONG
3442 rb_num2ull(VALUE val)
3444 if (NIL_P(val)) {
3445 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3447 else if (FIXNUM_P(val)) {
3448 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3450 else if (RB_FLOAT_TYPE_P(val)) {
3451 double d = RFLOAT_VALUE(val);
3452 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3453 if (0 <= d)
3454 return (unsigned LONG_LONG)d;
3455 return (unsigned LONG_LONG)(LONG_LONG)d;
3457 else {
3458 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3461 else if (RB_BIGNUM_TYPE_P(val)) {
3462 return rb_big2ull(val);
3464 else if (RB_TYPE_P(val, T_STRING)) {
3465 rb_raise(rb_eTypeError, "no implicit conversion from string");
3467 else if (RB_TYPE_P(val, T_TRUE) || RB_TYPE_P(val, T_FALSE)) {
3468 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
3471 val = rb_to_int(val);
3472 return NUM2ULL(val);
3475 #endif /* HAVE_LONG_LONG */
3477 /********************************************************************
3479 * Document-class: Integer
3481 * An \Integer object represents an integer value.
3483 * You can create an \Integer object explicitly with:
3485 * - An {integer literal}[doc/syntax/literals_rdoc.html#label-Integer+Literals].
3487 * You can convert certain objects to Integers with:
3489 * - \Method {Integer}[Kernel.html#method-i-Integer].
3491 * An attempt to add a singleton method to an instance of this class
3492 * causes an exception to be raised.
3494 * == What's Here
3496 * First, what's elsewhere. \Class \Integer:
3498 * - Inherits from {class Numeric}[Numeric.html#class-Numeric-label-What-27s+Here].
3500 * Here, class \Integer provides methods for:
3502 * - {Querying}[#class-Integer-label-Querying]
3503 * - {Comparing}[#class-Integer-label-Comparing]
3504 * - {Converting}[#class-Integer-label-Converting]
3505 * - {Other}[#class-Integer-label-Other]
3507 * === Querying
3509 * - #allbits?:: Returns whether all bits in +self+ are set.
3510 * - #anybits?:: Returns whether any bits in +self+ are set.
3511 * - #nobits?:: Returns whether no bits in +self+ are set.
3513 * === Comparing
3515 * - {<}[#method-i-3C]:: Returns whether +self+ is less than the given value.
3516 * - {<=}[#method-i-3C-3D]:: Returns whether +self+ is less than
3517 * or equal to the given value.
3518 * - {<=>}[#method-i-3C-3D-3E]:: Returns a number indicating whether +self+ is less than,
3519 * equal to, or greater than the given value.
3520 * - {==}[#method-i-3D-3D] (aliased as #===):: Returns whether +self+ is
3521 * equal to the given value.
3522 * - {>}[#method-i-3E]:: Returns whether +self+ is greater than the given value.
3523 * - {>=}[#method-i-3E-3D]:: Returns whether +self+ is greater than
3524 * or equal to the given value.
3526 * === Converting
3528 * - ::sqrt:: Returns the integer square root of the given value.
3529 * - ::try_convert:: Returns the given value converted to an \Integer.
3530 * - #% (aliased as #modulo):: Returns +self+ modulo the given value.
3531 * - {&}[#method-i-26]:: Returns the bitwise AND of +self+ and the given value.
3532 * - #*:: Returns the product of +self+ and the given value.
3533 * - {**}[#method-i-2A-2A]:: Returns the value of +self+ raised to the power of the given value.
3534 * - #+:: Returns the sum of +self+ and the given value.
3535 * - #-:: Returns the difference of +self+ and the given value.
3536 * - {/}[#method-i-2F]:: Returns the quotient of +self+ and the given value.
3537 * - #<<:: Returns the value of +self+ after a leftward bit-shift.
3538 * - #>>:: Returns the value of +self+ after a rightward bit-shift.
3539 * - #[]:: Returns a slice of bits from +self+.
3540 * - {^}[#method-i-5E]:: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3541 * - #ceil:: Returns the smallest number greater than or equal to +self+.
3542 * - #chr:: Returns a 1-character string containing the character
3543 * represented by the value of +self+.
3544 * - #digits:: Returns an array of integers representing the base-radix digits
3545 * of +self+.
3546 * - #div:: Returns the integer result of dividing +self+ by the given value.
3547 * - #divmod:: Returns a 2-element array containing the quotient and remainder
3548 * results of dividing +self+ by the given value.
3549 * - #fdiv:: Returns the Float result of dividing +self+ by the given value.
3550 * - #floor:: Returns the greatest number smaller than or equal to +self+.
3551 * - #pow:: Returns the modular exponentiation of +self+.
3552 * - #pred:: Returns the integer predecessor of +self+.
3553 * - #remainder:: Returns the remainder after dividing +self+ by the given value.
3554 * - #round:: Returns +self+ rounded to the nearest value with the given precision.
3555 * - #succ (aliased as #next):: Returns the integer successor of +self+.
3556 * - #to_f:: Returns +self+ converted to a Float.
3557 * - #to_s (aliased as #inspect):: Returns a string containing the place-value
3558 * representation of +self+ in the given radix.
3559 * - #truncate:: Returns +self+ truncated to the given precision.
3560 * - {/}[#method-i-7C]:: Returns the bitwise OR of +self+ and the given value.
3562 * === Other
3564 * - #downto:: Calls the given block with each integer value from +self+
3565 * down to the given value.
3566 * - #times:: Calls the given block +self+ times with each integer
3567 * in <tt>(0..self-1)</tt>.
3568 * - #upto:: Calls the given block with each integer value from +self+
3569 * up to the given value.
3573 VALUE
3574 rb_int_odd_p(VALUE num)
3576 if (FIXNUM_P(num)) {
3577 return RBOOL(num & 2);
3579 else {
3580 assert(RB_BIGNUM_TYPE_P(num));
3581 return rb_big_odd_p(num);
3585 static VALUE
3586 int_even_p(VALUE num)
3588 if (FIXNUM_P(num)) {
3589 return RBOOL((num & 2) == 0);
3591 else {
3592 assert(RB_BIGNUM_TYPE_P(num));
3593 return rb_big_even_p(num);
3597 VALUE
3598 rb_int_even_p(VALUE num)
3600 return int_even_p(num);
3604 * call-seq:
3605 * allbits?(mask) -> true or false
3607 * Returns +true+ if all bits that are set (=1) in +mask+
3608 * are also set in +self+; returns +false+ otherwise.
3610 * Example values:
3612 * 0b1010101 self
3613 * 0b1010100 mask
3614 * 0b1010100 self & mask
3615 * true self.allbits?(mask)
3617 * 0b1010100 self
3618 * 0b1010101 mask
3619 * 0b1010100 self & mask
3620 * false self.allbits?(mask)
3622 * Related: Integer#anybits?, Integer#nobits?.
3626 static VALUE
3627 int_allbits_p(VALUE num, VALUE mask)
3629 mask = rb_to_int(mask);
3630 return rb_int_equal(rb_int_and(num, mask), mask);
3634 * call-seq:
3635 * anybits?(mask) -> true or false
3637 * Returns +true+ if any bit that is set (=1) in +mask+
3638 * is also set in +self+; returns +false+ otherwise.
3640 * Example values:
3642 * 0b10000010 self
3643 * 0b11111111 mask
3644 * 0b10000010 self & mask
3645 * true self.anybits?(mask)
3647 * 0b00000000 self
3648 * 0b11111111 mask
3649 * 0b00000000 self & mask
3650 * false self.anybits?(mask)
3652 * Related: Integer#allbits?, Integer#nobits?.
3656 static VALUE
3657 int_anybits_p(VALUE num, VALUE mask)
3659 mask = rb_to_int(mask);
3660 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3664 * call-seq:
3665 * nobits?(mask) -> true or false
3667 * Returns +true+ if no bit that is set (=1) in +mask+
3668 * is also set in +self+; returns +false+ otherwise.
3670 * Example values:
3672 * 0b11110000 self
3673 * 0b00001111 mask
3674 * 0b00000000 self & mask
3675 * true self.nobits?(mask)
3677 * 0b00000001 self
3678 * 0b11111111 mask
3679 * 0b00000001 self & mask
3680 * false self.nobits?(mask)
3682 * Related: Integer#allbits?, Integer#anybits?.
3686 static VALUE
3687 int_nobits_p(VALUE num, VALUE mask)
3689 mask = rb_to_int(mask);
3690 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3694 * call-seq:
3695 * succ -> next_integer
3697 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3699 * 1.succ #=> 2
3700 * -1.succ #=> 0
3702 * Integer#next is an alias for Integer#succ.
3704 * Related: Integer#pred (predecessor value).
3707 VALUE
3708 rb_int_succ(VALUE num)
3710 if (FIXNUM_P(num)) {
3711 long i = FIX2LONG(num) + 1;
3712 return LONG2NUM(i);
3714 if (RB_BIGNUM_TYPE_P(num)) {
3715 return rb_big_plus(num, INT2FIX(1));
3717 return num_funcall1(num, '+', INT2FIX(1));
3720 #define int_succ rb_int_succ
3723 * call-seq:
3724 * pred -> next_integer
3726 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3728 * 1.pred #=> 0
3729 * -1.pred #=> -2
3731 * Related: Integer#succ (successor value).
3735 static VALUE
3736 rb_int_pred(VALUE num)
3738 if (FIXNUM_P(num)) {
3739 long i = FIX2LONG(num) - 1;
3740 return LONG2NUM(i);
3742 if (RB_BIGNUM_TYPE_P(num)) {
3743 return rb_big_minus(num, INT2FIX(1));
3745 return num_funcall1(num, '-', INT2FIX(1));
3748 #define int_pred rb_int_pred
3750 VALUE
3751 rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3753 int n;
3754 VALUE str;
3755 switch (n = rb_enc_codelen(code, enc)) {
3756 case ONIGERR_INVALID_CODE_POINT_VALUE:
3757 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3758 break;
3759 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3760 case 0:
3761 rb_raise(rb_eRangeError, "%u out of char range", code);
3762 break;
3764 str = rb_enc_str_new(0, n, enc);
3765 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3766 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3767 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3769 return str;
3772 /* call-seq:
3773 * chr -> string
3774 * chr(encoding) -> string
3776 * Returns a 1-character string containing the character
3777 * represented by the value of +self+, according to the given +encoding+.
3779 * 65.chr # => "A"
3780 * 0..chr # => "\x00"
3781 * 255.chr # => "\xFF"
3782 * string = 255.chr(Encoding::UTF_8)
3783 * string.encoding # => Encoding::UTF_8
3785 * Raises an exception if +self+ is negative.
3787 * Related: Integer#ord.
3791 static VALUE
3792 int_chr(int argc, VALUE *argv, VALUE num)
3794 char c;
3795 unsigned int i;
3796 rb_encoding *enc;
3798 if (rb_num_to_uint(num, &i) == 0) {
3800 else if (FIXNUM_P(num)) {
3801 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3803 else {
3804 rb_raise(rb_eRangeError, "bignum out of char range");
3807 switch (argc) {
3808 case 0:
3809 if (0xff < i) {
3810 enc = rb_default_internal_encoding();
3811 if (!enc) {
3812 rb_raise(rb_eRangeError, "%u out of char range", i);
3814 goto decode;
3816 c = (char)i;
3817 if (i < 0x80) {
3818 return rb_usascii_str_new(&c, 1);
3820 else {
3821 return rb_str_new(&c, 1);
3823 case 1:
3824 break;
3825 default:
3826 rb_error_arity(argc, 0, 1);
3828 enc = rb_to_encoding(argv[0]);
3829 if (!enc) enc = rb_ascii8bit_encoding();
3830 decode:
3831 return rb_enc_uint_chr(i, enc);
3835 * Fixnum
3838 static VALUE
3839 fix_uminus(VALUE num)
3841 return LONG2NUM(-FIX2LONG(num));
3844 VALUE
3845 rb_int_uminus(VALUE num)
3847 if (FIXNUM_P(num)) {
3848 return fix_uminus(num);
3850 else {
3851 assert(RB_BIGNUM_TYPE_P(num));
3852 return rb_big_uminus(num);
3856 VALUE
3857 rb_fix2str(VALUE x, int base)
3859 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3860 long val = FIX2LONG(x);
3861 unsigned long u;
3862 int neg = 0;
3864 if (base < 2 || 36 < base) {
3865 rb_raise(rb_eArgError, "invalid radix %d", base);
3867 #if SIZEOF_LONG < SIZEOF_VOIDP
3868 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3869 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
3870 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
3871 rb_bug("Unnormalized Fixnum value %p", (void *)x);
3873 # else
3874 /* should do something like above code, but currently ruby does not know */
3875 /* such platforms */
3876 # endif
3877 #endif
3878 if (val == 0) {
3879 return rb_usascii_str_new2("0");
3881 if (val < 0) {
3882 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3883 neg = 1;
3885 else {
3886 u = val;
3888 do {
3889 *--b = ruby_digitmap[(int)(u % base)];
3890 } while (u /= base);
3891 if (neg) {
3892 *--b = '-';
3895 return rb_usascii_str_new(b, e - b);
3898 static VALUE rb_fix_to_s_static[10];
3900 MJIT_FUNC_EXPORTED VALUE
3901 rb_fix_to_s(VALUE x)
3903 long i = FIX2LONG(x);
3904 if (i >= 0 && i < 10) {
3905 return rb_fix_to_s_static[i];
3907 return rb_fix2str(x, 10);
3911 * call-seq:
3912 * to_s(base = 10) -> string
3914 * Returns a string containing the place-value representation of +self+
3915 * in radix +base+ (in 2..36).
3917 * 12345.to_s # => "12345"
3918 * 12345.to_s(2) # => "11000000111001"
3919 * 12345.to_s(8) # => "30071"
3920 * 12345.to_s(10) # => "12345"
3921 * 12345.to_s(16) # => "3039"
3922 * 12345.to_s(36) # => "9ix"
3923 * 78546939656932.to_s(36) # => "rubyrules"
3925 * Raises an exception if +base+ is out of range.
3927 * Integer#inspect is an alias for Integer#to_s.
3931 MJIT_FUNC_EXPORTED VALUE
3932 rb_int_to_s(int argc, VALUE *argv, VALUE x)
3934 int base;
3936 if (rb_check_arity(argc, 0, 1))
3937 base = NUM2INT(argv[0]);
3938 else
3939 base = 10;
3940 return rb_int2str(x, base);
3943 VALUE
3944 rb_int2str(VALUE x, int base)
3946 if (FIXNUM_P(x)) {
3947 return rb_fix2str(x, base);
3949 else if (RB_BIGNUM_TYPE_P(x)) {
3950 return rb_big2str(x, base);
3953 return rb_any_to_s(x);
3956 static VALUE
3957 fix_plus(VALUE x, VALUE y)
3959 if (FIXNUM_P(y)) {
3960 return rb_fix_plus_fix(x, y);
3962 else if (RB_BIGNUM_TYPE_P(y)) {
3963 return rb_big_plus(y, x);
3965 else if (RB_FLOAT_TYPE_P(y)) {
3966 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
3968 else if (RB_TYPE_P(y, T_COMPLEX)) {
3969 return rb_complex_plus(y, x);
3971 else {
3972 return rb_num_coerce_bin(x, y, '+');
3976 VALUE
3977 rb_fix_plus(VALUE x, VALUE y)
3979 return fix_plus(x, y);
3983 * call-seq:
3984 * self + numeric -> numeric_result
3986 * Performs addition:
3988 * 2 + 2 # => 4
3989 * -2 + 2 # => 0
3990 * -2 + -2 # => -4
3991 * 2 + 2.0 # => 4.0
3992 * 2 + Rational(2, 1) # => (4/1)
3993 * 2 + Complex(2, 0) # => (4+0i)
3997 VALUE
3998 rb_int_plus(VALUE x, VALUE y)
4000 if (FIXNUM_P(x)) {
4001 return fix_plus(x, y);
4003 else if (RB_BIGNUM_TYPE_P(x)) {
4004 return rb_big_plus(x, y);
4006 return rb_num_coerce_bin(x, y, '+');
4009 static VALUE
4010 fix_minus(VALUE x, VALUE y)
4012 if (FIXNUM_P(y)) {
4013 return rb_fix_minus_fix(x, y);
4015 else if (RB_BIGNUM_TYPE_P(y)) {
4016 x = rb_int2big(FIX2LONG(x));
4017 return rb_big_minus(x, y);
4019 else if (RB_FLOAT_TYPE_P(y)) {
4020 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4022 else {
4023 return rb_num_coerce_bin(x, y, '-');
4028 * call-seq:
4029 * self - numeric -> numeric_result
4031 * Performs subtraction:
4033 * 4 - 2 # => 2
4034 * -4 - 2 # => -6
4035 * -4 - -2 # => -2
4036 * 4 - 2.0 # => 2.0
4037 * 4 - Rational(2, 1) # => (2/1)
4038 * 4 - Complex(2, 0) # => (2+0i)
4042 VALUE
4043 rb_int_minus(VALUE x, VALUE y)
4045 if (FIXNUM_P(x)) {
4046 return fix_minus(x, y);
4048 else if (RB_BIGNUM_TYPE_P(x)) {
4049 return rb_big_minus(x, y);
4051 return rb_num_coerce_bin(x, y, '-');
4055 #define SQRT_LONG_MAX HALF_LONG_MSB
4056 /*tests if N*N would overflow*/
4057 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4059 static VALUE
4060 fix_mul(VALUE x, VALUE y)
4062 if (FIXNUM_P(y)) {
4063 return rb_fix_mul_fix(x, y);
4065 else if (RB_BIGNUM_TYPE_P(y)) {
4066 switch (x) {
4067 case INT2FIX(0): return x;
4068 case INT2FIX(1): return y;
4070 return rb_big_mul(y, x);
4072 else if (RB_FLOAT_TYPE_P(y)) {
4073 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4075 else if (RB_TYPE_P(y, T_COMPLEX)) {
4076 return rb_complex_mul(y, x);
4078 else {
4079 return rb_num_coerce_bin(x, y, '*');
4084 * call-seq:
4085 * self * numeric -> numeric_result
4087 * Performs multiplication:
4089 * 4 * 2 # => 8
4090 * 4 * -2 # => -8
4091 * -4 * 2 # => -8
4092 * 4 * 2.0 # => 8.0
4093 * 4 * Rational(1, 3) # => (4/3)
4094 * 4 * Complex(2, 0) # => (8+0i)
4097 VALUE
4098 rb_int_mul(VALUE x, VALUE y)
4100 if (FIXNUM_P(x)) {
4101 return fix_mul(x, y);
4103 else if (RB_BIGNUM_TYPE_P(x)) {
4104 return rb_big_mul(x, y);
4106 return rb_num_coerce_bin(x, y, '*');
4109 static double
4110 fix_fdiv_double(VALUE x, VALUE y)
4112 if (FIXNUM_P(y)) {
4113 return double_div_double(FIX2LONG(x), FIX2LONG(y));
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)) {
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)
4322 * Integer#modulo is an alias for Integer#%.
4325 VALUE
4326 rb_int_modulo(VALUE x, VALUE y)
4328 if (FIXNUM_P(x)) {
4329 return fix_mod(x, y);
4331 else if (RB_BIGNUM_TYPE_P(x)) {
4332 return rb_big_modulo(x, y);
4334 return num_modulo(x, y);
4338 * call-seq:
4339 * remainder(other) -> real_number
4341 * Returns the remainder after dividing +self+ by +other+.
4343 * Examples:
4345 * 11.remainder(4) # => 3
4346 * 11.remainder(-4) # => 3
4347 * -11.remainder(4) # => -3
4348 * -11.remainder(-4) # => -3
4350 * 12.remainder(4) # => 0
4351 * 12.remainder(-4) # => 0
4352 * -12.remainder(4) # => 0
4353 * -12.remainder(-4) # => 0
4355 * 13.remainder(4.0) # => 1.0
4356 * 13.remainder(Rational(4, 1)) # => (1/1)
4360 static VALUE
4361 int_remainder(VALUE x, VALUE y)
4363 if (FIXNUM_P(x)) {
4364 return num_remainder(x, y);
4366 else if (RB_BIGNUM_TYPE_P(x)) {
4367 return rb_big_remainder(x, y);
4369 return Qnil;
4372 static VALUE
4373 fix_divmod(VALUE x, VALUE y)
4375 if (FIXNUM_P(y)) {
4376 VALUE div, mod;
4377 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4378 rb_fix_divmod_fix(x, y, &div, &mod);
4379 return rb_assoc_new(div, mod);
4381 else if (RB_BIGNUM_TYPE_P(y)) {
4382 x = rb_int2big(FIX2LONG(x));
4383 return rb_big_divmod(x, y);
4385 else if (RB_FLOAT_TYPE_P(y)) {
4387 double div, mod;
4388 volatile VALUE a, b;
4390 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4391 a = dbl2ival(div);
4392 b = DBL2NUM(mod);
4393 return rb_assoc_new(a, b);
4396 else {
4397 return rb_num_coerce_bin(x, y, id_divmod);
4402 * call-seq:
4403 * divmod(other) -> array
4405 * Returns a 2-element array <tt>[q, r]</tt>, where
4407 * q = (self/other).floor # Quotient
4408 * r = self % other # Remainder
4410 * Examples:
4412 * 11.divmod(4) # => [2, 3]
4413 * 11.divmod(-4) # => [-3, -1]
4414 * -11.divmod(4) # => [-3, 1]
4415 * -11.divmod(-4) # => [2, -3]
4417 * 12.divmod(4) # => [3, 0]
4418 * 12.divmod(-4) # => [-3, 0]
4419 * -12.divmod(4) # => [-3, 0]
4420 * -12.divmod(-4) # => [3, 0]
4422 * 13.divmod(4.0) # => [3, 1.0]
4423 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4426 VALUE
4427 rb_int_divmod(VALUE x, VALUE y)
4429 if (FIXNUM_P(x)) {
4430 return fix_divmod(x, y);
4432 else if (RB_BIGNUM_TYPE_P(x)) {
4433 return rb_big_divmod(x, y);
4435 return Qnil;
4439 * call-seq:
4440 * self ** numeric -> numeric_result
4442 * Raises +self+ to the power of +numeric+:
4444 * 2 ** 3 # => 8
4445 * 2 ** -3 # => (1/8)
4446 * -2 ** 3 # => -8
4447 * -2 ** -3 # => (-1/8)
4448 * 2 ** 3.3 # => 9.849155306759329
4449 * 2 ** Rational(3, 1) # => (8/1)
4450 * 2 ** Complex(3, 0) # => (8+0i)
4454 static VALUE
4455 int_pow(long x, unsigned long y)
4457 int neg = x < 0;
4458 long z = 1;
4460 if (y == 0) return INT2FIX(1);
4461 if (y == 1) return LONG2NUM(x);
4462 if (neg) x = -x;
4463 if (y & 1)
4464 z = x;
4465 else
4466 neg = 0;
4467 y &= ~1;
4468 do {
4469 while (y % 2 == 0) {
4470 if (!FIT_SQRT_LONG(x)) {
4471 goto bignum;
4473 x = x * x;
4474 y >>= 1;
4477 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4478 goto bignum;
4480 z = x * z;
4482 } while (--y);
4483 if (neg) z = -z;
4484 return LONG2NUM(z);
4486 VALUE v;
4487 bignum:
4488 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4489 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4490 return v;
4491 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4492 return v;
4495 VALUE
4496 rb_int_positive_pow(long x, unsigned long y)
4498 return int_pow(x, y);
4501 static VALUE
4502 fix_pow_inverted(VALUE x, VALUE minusb)
4504 if (x == INT2FIX(0)) {
4505 rb_num_zerodiv();
4506 UNREACHABLE_RETURN(Qundef);
4508 else {
4509 VALUE y = rb_int_pow(x, minusb);
4511 if (RB_FLOAT_TYPE_P(y)) {
4512 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4513 return DBL2NUM(1.0 / d);
4515 else {
4516 return rb_rational_raw(INT2FIX(1), y);
4521 static VALUE
4522 fix_pow(VALUE x, VALUE y)
4524 long a = FIX2LONG(x);
4526 if (FIXNUM_P(y)) {
4527 long b = FIX2LONG(y);
4529 if (a == 1) return INT2FIX(1);
4530 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4531 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4532 if (b == 0) return INT2FIX(1);
4533 if (b == 1) return x;
4534 if (a == 0) return INT2FIX(0);
4535 return int_pow(a, b);
4537 else if (RB_BIGNUM_TYPE_P(y)) {
4538 if (a == 1) return INT2FIX(1);
4539 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4540 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4541 if (a == 0) return INT2FIX(0);
4542 x = rb_int2big(FIX2LONG(x));
4543 return rb_big_pow(x, y);
4545 else if (RB_FLOAT_TYPE_P(y)) {
4546 double dy = RFLOAT_VALUE(y);
4547 if (dy == 0.0) return DBL2NUM(1.0);
4548 if (a == 0) {
4549 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4551 if (a == 1) return DBL2NUM(1.0);
4552 if (a < 0 && dy != round(dy))
4553 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4554 return DBL2NUM(pow((double)a, dy));
4556 else {
4557 return rb_num_coerce_bin(x, y, idPow);
4562 * call-seq:
4563 * self ** numeric -> numeric_result
4565 * Raises +self+ to the power of +numeric+:
4567 * 2 ** 3 # => 8
4568 * 2 ** -3 # => (1/8)
4569 * -2 ** 3 # => -8
4570 * -2 ** -3 # => (-1/8)
4571 * 2 ** 3.3 # => 9.849155306759329
4572 * 2 ** Rational(3, 1) # => (8/1)
4573 * 2 ** Complex(3, 0) # => (8+0i)
4576 VALUE
4577 rb_int_pow(VALUE x, VALUE y)
4579 if (FIXNUM_P(x)) {
4580 return fix_pow(x, y);
4582 else if (RB_BIGNUM_TYPE_P(x)) {
4583 return rb_big_pow(x, y);
4585 return Qnil;
4588 VALUE
4589 rb_num_pow(VALUE x, VALUE y)
4591 VALUE z = rb_int_pow(x, y);
4592 if (!NIL_P(z)) return z;
4593 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4594 if (SPECIAL_CONST_P(x)) return Qnil;
4595 switch (BUILTIN_TYPE(x)) {
4596 case T_COMPLEX:
4597 return rb_complex_pow(x, y);
4598 case T_RATIONAL:
4599 return rb_rational_pow(x, y);
4600 default:
4601 break;
4603 return Qnil;
4606 static VALUE
4607 fix_equal(VALUE x, VALUE y)
4609 if (x == y) return Qtrue;
4610 if (FIXNUM_P(y)) return Qfalse;
4611 else if (RB_BIGNUM_TYPE_P(y)) {
4612 return rb_big_eq(y, x);
4614 else if (RB_FLOAT_TYPE_P(y)) {
4615 return rb_integer_float_eq(x, y);
4617 else {
4618 return num_equal(x, y);
4623 * call-seq:
4624 * self == other -> true or false
4626 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4628 * 1 == 2 #=> false
4629 * 1 == 1.0 #=> true
4631 * Related: Integer#eql? (requires +other+ to be an \Integer).
4633 * Integer#=== is an alias for Integer#==.
4637 VALUE
4638 rb_int_equal(VALUE x, VALUE y)
4640 if (FIXNUM_P(x)) {
4641 return fix_equal(x, y);
4643 else if (RB_BIGNUM_TYPE_P(x)) {
4644 return rb_big_eq(x, y);
4646 return Qnil;
4649 static VALUE
4650 fix_cmp(VALUE x, VALUE y)
4652 if (x == y) return INT2FIX(0);
4653 if (FIXNUM_P(y)) {
4654 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4655 return INT2FIX(-1);
4657 else if (RB_BIGNUM_TYPE_P(y)) {
4658 VALUE cmp = rb_big_cmp(y, x);
4659 switch (cmp) {
4660 case INT2FIX(+1): return INT2FIX(-1);
4661 case INT2FIX(-1): return INT2FIX(+1);
4663 return cmp;
4665 else if (RB_FLOAT_TYPE_P(y)) {
4666 return rb_integer_float_cmp(x, y);
4668 else {
4669 return rb_num_coerce_cmp(x, y, id_cmp);
4674 * call-seq:
4675 * self <=> other -> -1, 0, +1, or nil
4677 * Returns:
4679 * - -1, if +self+ is less than +other+.
4680 * - 0, if +self+ is equal to +other+.
4681 * - 1, if +self+ is greater then +other+.
4682 * - +nil+, if +self+ and +other+ are incomparable.
4684 * Examples:
4686 * 1 <=> 2 # => -1
4687 * 1 <=> 1 # => 0
4688 * 1 <=> 0 # => 1
4689 * 1 <=> 'foo' # => nil
4691 * 1 <=> 1.0 # => 0
4692 * 1 <=> Rational(1, 1) # => 0
4693 * 1 <=> Complex(1, 0) # => 0
4695 * This method is the basis for comparisons in module Comparable.
4699 VALUE
4700 rb_int_cmp(VALUE x, VALUE y)
4702 if (FIXNUM_P(x)) {
4703 return fix_cmp(x, y);
4705 else if (RB_BIGNUM_TYPE_P(x)) {
4706 return rb_big_cmp(x, y);
4708 else {
4709 rb_raise(rb_eNotImpError, "need to define `<=>' in %s", rb_obj_classname(x));
4713 static VALUE
4714 fix_gt(VALUE x, VALUE y)
4716 if (FIXNUM_P(y)) {
4717 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4719 else if (RB_BIGNUM_TYPE_P(y)) {
4720 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4722 else if (RB_FLOAT_TYPE_P(y)) {
4723 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
4725 else {
4726 return rb_num_coerce_relop(x, y, '>');
4731 * call-seq:
4732 * self > other -> true or false
4734 * Returns +true+ if the value of +self+ is greater than that of +other+:
4736 * 1 > 0 # => true
4737 * 1 > 1 # => false
4738 * 1 > 2 # => false
4739 * 1 > 0.5 # => true
4740 * 1 > Rational(1, 2) # => true
4742 * Raises an exception if the comparison cannot be made.
4746 VALUE
4747 rb_int_gt(VALUE x, VALUE y)
4749 if (FIXNUM_P(x)) {
4750 return fix_gt(x, y);
4752 else if (RB_BIGNUM_TYPE_P(x)) {
4753 return rb_big_gt(x, y);
4755 return Qnil;
4758 static VALUE
4759 fix_ge(VALUE x, VALUE y)
4761 if (FIXNUM_P(y)) {
4762 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
4764 else if (RB_BIGNUM_TYPE_P(y)) {
4765 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
4767 else if (RB_FLOAT_TYPE_P(y)) {
4768 VALUE rel = rb_integer_float_cmp(x, y);
4769 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
4771 else {
4772 return rb_num_coerce_relop(x, y, idGE);
4777 * call-seq:
4778 * self >= real -> true or false
4780 * Returns +true+ if the value of +self+ is greater than or equal to
4781 * that of +other+:
4783 * 1 >= 0 # => true
4784 * 1 >= 1 # => true
4785 * 1 >= 2 # => false
4786 * 1 >= 0.5 # => true
4787 * 1 >= Rational(1, 2) # => true
4789 * Raises an exception if the comparison cannot be made.
4793 VALUE
4794 rb_int_ge(VALUE x, VALUE y)
4796 if (FIXNUM_P(x)) {
4797 return fix_ge(x, y);
4799 else if (RB_BIGNUM_TYPE_P(x)) {
4800 return rb_big_ge(x, y);
4802 return Qnil;
4805 static VALUE
4806 fix_lt(VALUE x, VALUE y)
4808 if (FIXNUM_P(y)) {
4809 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
4811 else if (RB_BIGNUM_TYPE_P(y)) {
4812 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
4814 else if (RB_FLOAT_TYPE_P(y)) {
4815 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
4817 else {
4818 return rb_num_coerce_relop(x, y, '<');
4823 * call-seq:
4824 * self < other -> true or false
4826 * Returns +true+ if the value of +self+ is less than that of +other+:
4828 * 1 < 0 # => false
4829 * 1 < 1 # => false
4830 * 1 < 2 # => true
4831 * 1 < 0.5 # => false
4832 * 1 < Rational(1, 2) # => false
4834 * Raises an exception if the comparison cannot be made.
4838 static VALUE
4839 int_lt(VALUE x, VALUE y)
4841 if (FIXNUM_P(x)) {
4842 return fix_lt(x, y);
4844 else if (RB_BIGNUM_TYPE_P(x)) {
4845 return rb_big_lt(x, y);
4847 return Qnil;
4850 static VALUE
4851 fix_le(VALUE x, VALUE y)
4853 if (FIXNUM_P(y)) {
4854 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
4856 else if (RB_BIGNUM_TYPE_P(y)) {
4857 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
4859 else if (RB_FLOAT_TYPE_P(y)) {
4860 VALUE rel = rb_integer_float_cmp(x, y);
4861 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
4863 else {
4864 return rb_num_coerce_relop(x, y, idLE);
4869 * call-seq:
4870 * self <= real -> true or false
4872 * Returns +true+ if the value of +self+ is less than or equal to
4873 * that of +other+:
4875 * 1 <= 0 # => false
4876 * 1 <= 1 # => true
4877 * 1 <= 2 # => true
4878 * 1 <= 0.5 # => false
4879 * 1 <= Rational(1, 2) # => false
4881 * Raises an exception if the comparison cannot be made.
4885 static VALUE
4886 int_le(VALUE x, VALUE y)
4888 if (FIXNUM_P(x)) {
4889 return fix_le(x, y);
4891 else if (RB_BIGNUM_TYPE_P(x)) {
4892 return rb_big_le(x, y);
4894 return Qnil;
4897 static VALUE
4898 fix_comp(VALUE num)
4900 return ~num | FIXNUM_FLAG;
4903 VALUE
4904 rb_int_comp(VALUE num)
4906 if (FIXNUM_P(num)) {
4907 return fix_comp(num);
4909 else if (RB_BIGNUM_TYPE_P(num)) {
4910 return rb_big_comp(num);
4912 return Qnil;
4915 static VALUE
4916 num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
4918 ID func = (ID)((VALUE *)arg)[0];
4919 VALUE x = ((VALUE *)arg)[1];
4920 if (recursive) {
4921 num_funcall_op_1_recursion(x, func, y);
4923 return rb_check_funcall(x, func, 1, &y);
4926 VALUE
4927 rb_num_coerce_bit(VALUE x, VALUE y, ID func)
4929 VALUE ret, args[3];
4931 args[0] = (VALUE)func;
4932 args[1] = x;
4933 args[2] = y;
4934 do_coerce(&args[1], &args[2], TRUE);
4935 ret = rb_exec_recursive_paired(num_funcall_bit_1,
4936 args[2], args[1], (VALUE)args);
4937 if (ret == Qundef) {
4938 /* show the original object, not coerced object */
4939 coerce_failed(x, y);
4941 return ret;
4944 static VALUE
4945 fix_and(VALUE x, VALUE y)
4947 if (FIXNUM_P(y)) {
4948 long val = FIX2LONG(x) & FIX2LONG(y);
4949 return LONG2NUM(val);
4952 if (RB_BIGNUM_TYPE_P(y)) {
4953 return rb_big_and(y, x);
4956 return rb_num_coerce_bit(x, y, '&');
4960 * call-seq:
4961 * self & other -> integer
4963 * Bitwise AND; each bit in the result is 1 if both corresponding bits
4964 * in +self+ and +other+ are 1, 0 otherwise:
4966 * "%04b" % (0b0101 & 0b0110) # => "0100"
4968 * Raises an exception if +other+ is not an \Integer.
4970 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
4974 VALUE
4975 rb_int_and(VALUE x, VALUE y)
4977 if (FIXNUM_P(x)) {
4978 return fix_and(x, y);
4980 else if (RB_BIGNUM_TYPE_P(x)) {
4981 return rb_big_and(x, y);
4983 return Qnil;
4986 static VALUE
4987 fix_or(VALUE x, VALUE y)
4989 if (FIXNUM_P(y)) {
4990 long val = FIX2LONG(x) | FIX2LONG(y);
4991 return LONG2NUM(val);
4994 if (RB_BIGNUM_TYPE_P(y)) {
4995 return rb_big_or(y, x);
4998 return rb_num_coerce_bit(x, y, '|');
5002 * call-seq:
5003 * self | other -> integer
5005 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5006 * in +self+ or +other+ is 1, 0 otherwise:
5008 * "%04b" % (0b0101 | 0b0110) # => "0111"
5010 * Raises an exception if +other+ is not an \Integer.
5012 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5016 static VALUE
5017 int_or(VALUE x, VALUE y)
5019 if (FIXNUM_P(x)) {
5020 return fix_or(x, y);
5022 else if (RB_BIGNUM_TYPE_P(x)) {
5023 return rb_big_or(x, y);
5025 return Qnil;
5028 static VALUE
5029 fix_xor(VALUE x, VALUE y)
5031 if (FIXNUM_P(y)) {
5032 long val = FIX2LONG(x) ^ FIX2LONG(y);
5033 return LONG2NUM(val);
5036 if (RB_BIGNUM_TYPE_P(y)) {
5037 return rb_big_xor(y, x);
5040 return rb_num_coerce_bit(x, y, '^');
5044 * call-seq:
5045 * self ^ other -> integer
5047 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5048 * in +self+ and +other+ are different, 0 otherwise:
5050 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5052 * Raises an exception if +other+ is not an \Integer.
5054 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5058 static VALUE
5059 int_xor(VALUE x, VALUE y)
5061 if (FIXNUM_P(x)) {
5062 return fix_xor(x, y);
5064 else if (RB_BIGNUM_TYPE_P(x)) {
5065 return rb_big_xor(x, y);
5067 return Qnil;
5070 static VALUE
5071 rb_fix_lshift(VALUE x, VALUE y)
5073 long val, width;
5075 val = NUM2LONG(x);
5076 if (!FIXNUM_P(y))
5077 return rb_big_lshift(rb_int2big(val), y);
5078 width = FIX2LONG(y);
5079 if (width < 0)
5080 return fix_rshift(val, (unsigned long)-width);
5081 return fix_lshift(val, width);
5084 static VALUE
5085 fix_lshift(long val, unsigned long width)
5087 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5088 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5089 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5091 val = val << width;
5092 return LONG2NUM(val);
5096 * call-seq:
5097 * self << count -> integer
5099 * Returns +self+ with bits shifted +count+ positions to the left,
5100 * or to the right if +count+ is negative:
5102 * n = 0b11110000
5103 * "%08b" % (n << 1) # => "111100000"
5104 * "%08b" % (n << 3) # => "11110000000"
5105 * "%08b" % (n << -1) # => "01111000"
5106 * "%08b" % (n << -3) # => "00011110"
5108 * Related: Integer#>>.
5112 VALUE
5113 rb_int_lshift(VALUE x, VALUE y)
5115 if (FIXNUM_P(x)) {
5116 return rb_fix_lshift(x, y);
5118 else if (RB_BIGNUM_TYPE_P(x)) {
5119 return rb_big_lshift(x, y);
5121 return Qnil;
5124 static VALUE
5125 rb_fix_rshift(VALUE x, VALUE y)
5127 long i, val;
5129 val = FIX2LONG(x);
5130 if (!FIXNUM_P(y))
5131 return rb_big_rshift(rb_int2big(val), y);
5132 i = FIX2LONG(y);
5133 if (i == 0) return x;
5134 if (i < 0)
5135 return fix_lshift(val, (unsigned long)-i);
5136 return fix_rshift(val, i);
5139 static VALUE
5140 fix_rshift(long val, unsigned long i)
5142 if (i >= sizeof(long)*CHAR_BIT-1) {
5143 if (val < 0) return INT2FIX(-1);
5144 return INT2FIX(0);
5146 val = RSHIFT(val, i);
5147 return LONG2FIX(val);
5151 * call-seq:
5152 * self >> count -> integer
5154 * Returns +self+ with bits shifted +count+ positions to the right,
5155 * or to the left if +count+ is negative:
5157 * n = 0b11110000
5158 * "%08b" % (n >> 1) # => "01111000"
5159 * "%08b" % (n >> 3) # => "00011110"
5160 * "%08b" % (n >> -1) # => "111100000"
5161 * "%08b" % (n >> -3) # => "11110000000"
5163 * Related: Integer#<<.
5167 static VALUE
5168 rb_int_rshift(VALUE x, VALUE y)
5170 if (FIXNUM_P(x)) {
5171 return rb_fix_rshift(x, y);
5173 else if (RB_BIGNUM_TYPE_P(x)) {
5174 return rb_big_rshift(x, y);
5176 return Qnil;
5179 MJIT_FUNC_EXPORTED VALUE
5180 rb_fix_aref(VALUE fix, VALUE idx)
5182 long val = FIX2LONG(fix);
5183 long i;
5185 idx = rb_to_int(idx);
5186 if (!FIXNUM_P(idx)) {
5187 idx = rb_big_norm(idx);
5188 if (!FIXNUM_P(idx)) {
5189 if (!BIGNUM_SIGN(idx) || val >= 0)
5190 return INT2FIX(0);
5191 return INT2FIX(1);
5194 i = FIX2LONG(idx);
5196 if (i < 0) return INT2FIX(0);
5197 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5198 if (val < 0) return INT2FIX(1);
5199 return INT2FIX(0);
5201 if (val & (1L<<i))
5202 return INT2FIX(1);
5203 return INT2FIX(0);
5207 /* copied from "r_less" in range.c */
5208 /* compares _a_ and _b_ and returns:
5209 * < 0: a < b
5210 * = 0: a = b
5211 * > 0: a > b or non-comparable
5213 static int
5214 compare_indexes(VALUE a, VALUE b)
5216 VALUE r = rb_funcall(a, id_cmp, 1, b);
5218 if (NIL_P(r))
5219 return INT_MAX;
5220 return rb_cmpint(r, a, b);
5223 static VALUE
5224 generate_mask(VALUE len)
5226 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5229 static VALUE
5230 int_aref1(VALUE num, VALUE arg)
5232 VALUE orig_num = num, beg, end;
5233 int excl;
5235 if (rb_range_values(arg, &beg, &end, &excl)) {
5236 if (NIL_P(beg)) {
5237 /* beginless range */
5238 if (!RTEST(num_negative_p(end))) {
5239 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5240 VALUE mask = generate_mask(end);
5241 if (int_zero_p(rb_int_and(num, mask))) {
5242 return INT2FIX(0);
5244 else {
5245 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5248 else {
5249 return INT2FIX(0);
5252 num = rb_int_rshift(num, beg);
5254 int cmp = compare_indexes(beg, end);
5255 if (!NIL_P(end) && cmp < 0) {
5256 VALUE len = rb_int_minus(end, beg);
5257 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5258 VALUE mask = generate_mask(len);
5259 num = rb_int_and(num, mask);
5261 else if (cmp == 0) {
5262 if (excl) return INT2FIX(0);
5263 num = orig_num;
5264 arg = beg;
5265 goto one_bit;
5267 return num;
5270 one_bit:
5271 if (FIXNUM_P(num)) {
5272 return rb_fix_aref(num, arg);
5274 else if (RB_BIGNUM_TYPE_P(num)) {
5275 return rb_big_aref(num, arg);
5277 return Qnil;
5280 static VALUE
5281 int_aref2(VALUE num, VALUE beg, VALUE len)
5283 num = rb_int_rshift(num, beg);
5284 VALUE mask = generate_mask(len);
5285 num = rb_int_and(num, mask);
5286 return num;
5290 * call-seq:
5291 * self[offset] -> 0 or 1
5292 * self[offset, size] -> integer
5293 * self[range] -> integer
5295 * Returns a slice of bits from +self+.
5297 * With argument +offset+, returns the bit at the given offset,
5298 * where offset 0 refers to the least significant bit:
5300 * n = 0b10 # => 2
5301 * n[0] # => 0
5302 * n[1] # => 1
5303 * n[2] # => 0
5304 * n[3] # => 0
5306 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5307 * Thus, negative index always returns zero:
5309 * 255[-1] # => 0
5311 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5312 * beginning at +offset+ and including bits of greater significance:
5314 * n = 0b111000 # => 56
5315 * "%010b" % n[0, 10] # => "0000111000"
5316 * "%010b" % n[4, 10] # => "0000000011"
5318 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5319 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5321 * n = 0b111000 # => 56
5322 * "%010b" % n[0..9] # => "0000111000"
5323 * "%010b" % n[4..9] # => "0000000011"
5325 * Raises an exception if the slice cannot be constructed.
5328 static VALUE
5329 int_aref(int const argc, VALUE * const argv, VALUE const num)
5331 rb_check_arity(argc, 1, 2);
5332 if (argc == 2) {
5333 return int_aref2(num, argv[0], argv[1]);
5335 return int_aref1(num, argv[0]);
5337 return Qnil;
5341 * call-seq:
5342 * to_f -> float
5344 * Converts +self+ to a Float:
5346 * 1.to_f # => 1.0
5347 * -1.to_f # => -1.0
5349 * If the value of +self+ does not fit in a \Float,
5350 * the result is infinity:
5352 * (10**400).to_f # => Infinity
5353 * (-10**400).to_f # => -Infinity
5357 static VALUE
5358 int_to_f(VALUE num)
5360 double val;
5362 if (FIXNUM_P(num)) {
5363 val = (double)FIX2LONG(num);
5365 else if (RB_BIGNUM_TYPE_P(num)) {
5366 val = rb_big2dbl(num);
5368 else {
5369 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5372 return DBL2NUM(val);
5375 static VALUE
5376 fix_abs(VALUE fix)
5378 long i = FIX2LONG(fix);
5380 if (i < 0) i = -i;
5382 return LONG2NUM(i);
5385 VALUE
5386 rb_int_abs(VALUE num)
5388 if (FIXNUM_P(num)) {
5389 return fix_abs(num);
5391 else if (RB_BIGNUM_TYPE_P(num)) {
5392 return rb_big_abs(num);
5394 return Qnil;
5397 static VALUE
5398 fix_size(VALUE fix)
5400 return INT2FIX(sizeof(long));
5403 MJIT_FUNC_EXPORTED VALUE
5404 rb_int_size(VALUE num)
5406 if (FIXNUM_P(num)) {
5407 return fix_size(num);
5409 else if (RB_BIGNUM_TYPE_P(num)) {
5410 return rb_big_size_m(num);
5412 return Qnil;
5415 static VALUE
5416 rb_fix_bit_length(VALUE fix)
5418 long v = FIX2LONG(fix);
5419 if (v < 0)
5420 v = ~v;
5421 return LONG2FIX(bit_length(v));
5424 VALUE
5425 rb_int_bit_length(VALUE num)
5427 if (FIXNUM_P(num)) {
5428 return rb_fix_bit_length(num);
5430 else if (RB_BIGNUM_TYPE_P(num)) {
5431 return rb_big_bit_length(num);
5433 return Qnil;
5436 static VALUE
5437 rb_fix_digits(VALUE fix, long base)
5439 VALUE digits;
5440 long x = FIX2LONG(fix);
5442 assert(x >= 0);
5444 if (base < 2)
5445 rb_raise(rb_eArgError, "invalid radix %ld", base);
5447 if (x == 0)
5448 return rb_ary_new_from_args(1, INT2FIX(0));
5450 digits = rb_ary_new();
5451 while (x > 0) {
5452 long q = x % base;
5453 rb_ary_push(digits, LONG2NUM(q));
5454 x /= base;
5457 return digits;
5460 static VALUE
5461 rb_int_digits_bigbase(VALUE num, VALUE base)
5463 VALUE digits, bases;
5465 assert(!rb_num_negative_p(num));
5467 if (RB_BIGNUM_TYPE_P(base))
5468 base = rb_big_norm(base);
5470 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5471 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5472 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5473 rb_raise(rb_eArgError, "negative radix");
5475 if (FIXNUM_P(base) && FIXNUM_P(num))
5476 return rb_fix_digits(num, FIX2LONG(base));
5478 if (FIXNUM_P(num))
5479 return rb_ary_new_from_args(1, num);
5481 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5482 digits = rb_ary_new();
5483 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5484 VALUE qr = rb_int_divmod(num, base);
5485 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5486 num = RARRAY_AREF(qr, 0);
5488 return digits;
5491 bases = rb_ary_new();
5492 for (VALUE b = base; int_lt(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5493 rb_ary_push(bases, b);
5495 digits = rb_ary_new_from_args(1, num);
5496 while (RARRAY_LEN(bases)) {
5497 VALUE b = rb_ary_pop(bases);
5498 long i, last_idx = RARRAY_LEN(digits) - 1;
5499 for(i = last_idx; i >= 0; i--) {
5500 VALUE n = RARRAY_AREF(digits, i);
5501 VALUE divmod = rb_int_divmod(n, b);
5502 VALUE div = RARRAY_AREF(divmod, 0);
5503 VALUE mod = RARRAY_AREF(divmod, 1);
5504 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5505 rb_ary_store(digits, 2 * i, mod);
5509 return digits;
5513 * call-seq:
5514 * digits(base = 10) -> array_of_integers
5516 * Returns an array of integers representing the +base+-radix
5517 * digits of +self+;
5518 * the first element of the array represents the least significant digit:
5520 * 12345.digits # => [5, 4, 3, 2, 1]
5521 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5522 * 12345.digits(100) # => [45, 23, 1]
5524 * Raises an exception if +self+ is negative or +base+ is less than 2.
5528 static VALUE
5529 rb_int_digits(int argc, VALUE *argv, VALUE num)
5531 VALUE base_value;
5532 long base;
5534 if (rb_num_negative_p(num))
5535 rb_raise(rb_eMathDomainError, "out of domain");
5537 if (rb_check_arity(argc, 0, 1)) {
5538 base_value = rb_to_int(argv[0]);
5539 if (!RB_INTEGER_TYPE_P(base_value))
5540 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5541 rb_obj_classname(argv[0]));
5542 if (RB_BIGNUM_TYPE_P(base_value))
5543 return rb_int_digits_bigbase(num, base_value);
5545 base = FIX2LONG(base_value);
5546 if (base < 0)
5547 rb_raise(rb_eArgError, "negative radix");
5548 else if (base < 2)
5549 rb_raise(rb_eArgError, "invalid radix %ld", base);
5551 else
5552 base = 10;
5554 if (FIXNUM_P(num))
5555 return rb_fix_digits(num, base);
5556 else if (RB_BIGNUM_TYPE_P(num))
5557 return rb_int_digits_bigbase(num, LONG2FIX(base));
5559 return Qnil;
5562 static VALUE
5563 int_upto_size(VALUE from, VALUE args, VALUE eobj)
5565 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5569 * call-seq:
5570 * upto(limit) {|i| ... } -> self
5571 * upto(limit) -> enumerator
5573 * Calls the given block with each integer value from +self+ up to +limit+;
5574 * returns +self+:
5576 * a = []
5577 * 5.upto(10) {|i| a << i } # => 5
5578 * a # => [5, 6, 7, 8, 9, 10]
5579 * a = []
5580 * -5.upto(0) {|i| a << i } # => -5
5581 * a # => [-5, -4, -3, -2, -1, 0]
5582 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5584 * With no block given, returns an Enumerator.
5588 static VALUE
5589 int_upto(VALUE from, VALUE to)
5591 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5592 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5593 long i, end;
5595 end = FIX2LONG(to);
5596 for (i = FIX2LONG(from); i <= end; i++) {
5597 rb_yield(LONG2FIX(i));
5600 else {
5601 VALUE i = from, c;
5603 while (!(c = rb_funcall(i, '>', 1, to))) {
5604 rb_yield(i);
5605 i = rb_funcall(i, '+', 1, INT2FIX(1));
5607 ensure_cmp(c, i, to);
5609 return from;
5612 static VALUE
5613 int_downto_size(VALUE from, VALUE args, VALUE eobj)
5615 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5619 * call-seq:
5620 * downto(limit) {|i| ... } -> self
5621 * downto(limit) -> enumerator
5623 * Calls the given block with each integer value from +self+ down to +limit+;
5624 * returns +self+:
5626 * a = []
5627 * 10.downto(5) {|i| a << i } # => 10
5628 * a # => [10, 9, 8, 7, 6, 5]
5629 * a = []
5630 * 0.downto(-5) {|i| a << i } # => 0
5631 * a # => [0, -1, -2, -3, -4, -5]
5632 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5634 * With no block given, returns an Enumerator.
5638 static VALUE
5639 int_downto(VALUE from, VALUE to)
5641 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5642 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5643 long i, end;
5645 end = FIX2LONG(to);
5646 for (i=FIX2LONG(from); i >= end; i--) {
5647 rb_yield(LONG2FIX(i));
5650 else {
5651 VALUE i = from, c;
5653 while (!(c = rb_funcall(i, '<', 1, to))) {
5654 rb_yield(i);
5655 i = rb_funcall(i, '-', 1, INT2FIX(1));
5657 if (NIL_P(c)) rb_cmperr(i, to);
5659 return from;
5662 static VALUE
5663 int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5665 if (FIXNUM_P(num)) {
5666 if (NUM2LONG(num) <= 0) return INT2FIX(0);
5668 else {
5669 if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) return INT2FIX(0);
5671 return num;
5675 * call-seq:
5676 * times {|i| ... } -> self
5677 * times -> enumerator
5679 * Calls the given block +self+ times with each integer in <tt>(0..self-1)</tt>:
5681 * a = []
5682 * 5.times {|i| a.push(i) } # => 5
5683 * a # => [0, 1, 2, 3, 4]
5685 * With no block given, returns an Enumerator.
5689 static VALUE
5690 int_dotimes(VALUE num)
5692 RETURN_SIZED_ENUMERATOR(num, 0, 0, int_dotimes_size);
5694 if (FIXNUM_P(num)) {
5695 long i, end;
5697 end = FIX2LONG(num);
5698 for (i=0; i<end; i++) {
5699 rb_yield_1(LONG2FIX(i));
5702 else {
5703 VALUE i = INT2FIX(0);
5705 for (;;) {
5706 if (!RTEST(int_le(i, num))) break;
5707 rb_yield(i);
5708 i = rb_int_plus(i, INT2FIX(1));
5711 return num;
5715 * call-seq:
5716 * round(ndigits= 0, half: :up) -> integer
5718 * Returns +self+ rounded to the nearest value with
5719 * a precision of +ndigits+ decimal digits.
5721 * When +ndigits+ is negative, the returned value
5722 * has at least <tt>ndigits.abs</tt> trailing zeros:
5724 * 555.round(-1) # => 560
5725 * 555.round(-2) # => 600
5726 * 555.round(-3) # => 1000
5727 * -555.round(-2) # => -600
5728 * 555.round(-4) # => 0
5730 * Returns +self+ when +ndigits+ is zero or positive.
5732 * 555.round # => 555
5733 * 555.round(1) # => 555
5734 * 555.round(50) # => 555
5736 * If keyword argument +half+ is given,
5737 * and +self+ is equidistant from the two candidate values,
5738 * the rounding is according to the given +half+ value:
5740 * - +:up+ or +nil+: round away from zero:
5742 * 25.round(-1, half: :up) # => 30
5743 * (-25).round(-1, half: :up) # => -30
5745 * - +:down+: round toward zero:
5747 * 25.round(-1, half: :down) # => 20
5748 * (-25).round(-1, half: :down) # => -20
5751 * - +:even+: round toward the candidate whose last nonzero digit is even:
5753 * 25.round(-1, half: :even) # => 20
5754 * 15.round(-1, half: :even) # => 20
5755 * (-25).round(-1, half: :even) # => -20
5757 * Raises and exception if the value for +half+ is invalid.
5759 * Related: Integer#truncate.
5763 static VALUE
5764 int_round(int argc, VALUE* argv, VALUE num)
5766 int ndigits;
5767 int mode;
5768 VALUE nd, opt;
5770 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5771 ndigits = NUM2INT(nd);
5772 mode = rb_num_get_rounding_option(opt);
5773 if (ndigits >= 0) {
5774 return num;
5776 return rb_int_round(num, ndigits, mode);
5780 * call-seq:
5781 * floor(ndigits = 0) -> integer
5783 * Returns the largest number less than or equal to +self+ with
5784 * a precision of +ndigits+ decimal digits.
5786 * When +ndigits+ is negative, the returned value
5787 * has at least <tt>ndigits.abs</tt> trailing zeros:
5789 * 555.floor(-1) # => 550
5790 * 555.floor(-2) # => 500
5791 * -555.floor(-2) # => -600
5792 * 555.floor(-3) # => 0
5794 * Returns +self+ when +ndigits+ is zero or positive.
5796 * 555.floor # => 555
5797 * 555.floor(50) # => 555
5799 * Related: Integer#ceil.
5803 static VALUE
5804 int_floor(int argc, VALUE* argv, VALUE num)
5806 int ndigits;
5808 if (!rb_check_arity(argc, 0, 1)) return num;
5809 ndigits = NUM2INT(argv[0]);
5810 if (ndigits >= 0) {
5811 return num;
5813 return rb_int_floor(num, ndigits);
5817 * call-seq:
5818 * ceil(ndigits = 0) -> integer
5820 * Returns the smallest number greater than or equal to +self+ with
5821 * a precision of +ndigits+ decimal digits.
5823 * When the precision is negative, the returned value is an integer
5824 * with at least <code>ndigits.abs</code> trailing zeros:
5826 * 555.ceil(-1) # => 560
5827 * 555.ceil(-2) # => 600
5828 * -555.ceil(-2) # => -500
5829 * 555.ceil(-3) # => 1000
5831 * Returns +self+ when +ndigits+ is zero or positive.
5833 * 555.ceil # => 555
5834 * 555.ceil(50) # => 555
5836 * Related: Integer#floor.
5840 static VALUE
5841 int_ceil(int argc, VALUE* argv, VALUE num)
5843 int ndigits;
5845 if (!rb_check_arity(argc, 0, 1)) return num;
5846 ndigits = NUM2INT(argv[0]);
5847 if (ndigits >= 0) {
5848 return num;
5850 return rb_int_ceil(num, ndigits);
5854 * call-seq:
5855 * truncate(ndigits = 0) -> integer
5857 * Returns +self+ truncated (toward zero) to
5858 * a precision of +ndigits+ decimal digits.
5860 * When +ndigits+ is negative, the returned value
5861 * has at least <tt>ndigits.abs</tt> trailing zeros:
5863 * 555.truncate(-1) # => 550
5864 * 555.truncate(-2) # => 500
5865 * -555.truncate(-2) # => -500
5867 * Returns +self+ when +ndigits+ is zero or positive.
5869 * 555.truncate # => 555
5870 * 555.truncate(50) # => 555
5872 * Related: Integer#round.
5876 static VALUE
5877 int_truncate(int argc, VALUE* argv, VALUE num)
5879 int ndigits;
5881 if (!rb_check_arity(argc, 0, 1)) return num;
5882 ndigits = NUM2INT(argv[0]);
5883 if (ndigits >= 0) {
5884 return num;
5886 return rb_int_truncate(num, ndigits);
5889 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5890 rettype \
5891 prefix##_isqrt(argtype n) \
5893 if (!argtype##_IN_DOUBLE_P(n)) { \
5894 unsigned int b = bit_length(n); \
5895 argtype t; \
5896 rettype x = (rettype)(n >> (b/2+1)); \
5897 x |= ((rettype)1LU << (b-1)/2); \
5898 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5899 return x; \
5901 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5904 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5905 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5906 #else
5907 # define RB_ULONG_IN_DOUBLE_P(n) 1
5908 #endif
5909 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5910 #define RB_ULONG unsigned long
5911 DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5913 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5914 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5915 # define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5916 # else
5917 # define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5918 # endif
5919 # ifdef ULL_TO_DOUBLE
5920 # define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
5921 # else
5922 # define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
5923 # endif
5924 DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
5925 #endif
5927 #define domain_error(msg) \
5928 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
5931 * call-seq:
5932 * Integer.sqrt(numeric) -> integer
5934 * Returns the integer square root of the non-negative integer +n+,
5935 * which is the largest non-negative integer less than or equal to the
5936 * square root of +numeric+.
5938 * Integer.sqrt(0) # => 0
5939 * Integer.sqrt(1) # => 1
5940 * Integer.sqrt(24) # => 4
5941 * Integer.sqrt(25) # => 5
5942 * Integer.sqrt(10**400) # => 10**200
5944 * If +numeric+ is not an \Integer, it is converted to an \Integer:
5946 * Integer.sqrt(Complex(4, 0)) # => 2
5947 * Integer.sqrt(Rational(4, 1)) # => 2
5948 * Integer.sqrt(4.0) # => 2
5949 * Integer.sqrt(3.14159) # => 1
5951 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
5952 * except that the result of the latter code may differ from the true value
5953 * due to the limited precision of floating point arithmetic.
5955 * Integer.sqrt(10**46) # => 100000000000000000000000
5956 * Math.sqrt(10**46).floor # => 99999999999999991611392
5958 * Raises an exception if +numeric+ is negative.
5962 static VALUE
5963 rb_int_s_isqrt(VALUE self, VALUE num)
5965 unsigned long n, sq;
5966 num = rb_to_int(num);
5967 if (FIXNUM_P(num)) {
5968 if (FIXNUM_NEGATIVE_P(num)) {
5969 domain_error("isqrt");
5971 n = FIX2ULONG(num);
5972 sq = rb_ulong_isqrt(n);
5973 return LONG2FIX(sq);
5975 else {
5976 size_t biglen;
5977 if (RBIGNUM_NEGATIVE_P(num)) {
5978 domain_error("isqrt");
5980 biglen = BIGNUM_LEN(num);
5981 if (biglen == 0) return INT2FIX(0);
5982 #if SIZEOF_BDIGIT <= SIZEOF_LONG
5983 /* short-circuit */
5984 if (biglen == 1) {
5985 n = BIGNUM_DIGITS(num)[0];
5986 sq = rb_ulong_isqrt(n);
5987 return ULONG2NUM(sq);
5989 #endif
5990 return rb_big_isqrt(num);
5994 /* :nodoc: */
5995 static VALUE
5996 int_s_try_convert(VALUE self, VALUE num)
5998 return rb_check_integer_type(num);
6002 * Document-class: ZeroDivisionError
6004 * Raised when attempting to divide an integer by 0.
6006 * 42 / 0 #=> ZeroDivisionError: divided by 0
6008 * Note that only division by an exact 0 will raise the exception:
6010 * 42 / 0.0 #=> Float::INFINITY
6011 * 42 / -0.0 #=> -Float::INFINITY
6012 * 0 / 0.0 #=> NaN
6016 * Document-class: FloatDomainError
6018 * Raised when attempting to convert special float values (in particular
6019 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6021 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6025 * Document-class: Numeric
6027 * Numeric is the class from which all higher-level numeric classes should inherit.
6029 * Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6030 * Integer are implemented as immediates, which means that each Integer is a single immutable
6031 * object which is always passed by value.
6033 * a = 1
6034 * 1.object_id == a.object_id #=> true
6036 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6037 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6039 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6040 * 1.dup #=> 1
6041 * 1.object_id == 1.dup.object_id #=> true
6043 * For this reason, Numeric should be used when defining other numeric classes.
6045 * Classes which inherit from Numeric must implement +coerce+, which returns a two-member
6046 * Array containing an object that has been coerced into an instance of the new class
6047 * and +self+ (see #coerce).
6049 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6050 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6051 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6052 * instances of other numeric classes.
6054 * class Tally < Numeric
6055 * def initialize(string)
6056 * @string = string
6057 * end
6059 * def to_s
6060 * @string
6061 * end
6063 * def to_i
6064 * @string.size
6065 * end
6067 * def coerce(other)
6068 * [self.class.new('|' * other.to_i), self]
6069 * end
6071 * def <=>(other)
6072 * to_i <=> other.to_i
6073 * end
6075 * def +(other)
6076 * self.class.new('|' * (to_i + other.to_i))
6077 * end
6079 * def -(other)
6080 * self.class.new('|' * (to_i - other.to_i))
6081 * end
6083 * def *(other)
6084 * self.class.new('|' * (to_i * other.to_i))
6085 * end
6087 * def /(other)
6088 * self.class.new('|' * (to_i / other.to_i))
6089 * end
6090 * end
6092 * tally = Tally.new('||')
6093 * puts tally * 2 #=> "||||"
6094 * puts tally > 1 #=> true
6096 * == What's Here
6098 * First, what's elsewhere. \Class \Numeric:
6100 * - Inherits from {class Object}[Object.html#class-Object-label-What-27s+Here].
6101 * - Includes {module Comparable}[Comparable.html#module-Comparable-label-What-27s+Here].
6103 * Here, class \Numeric provides methods for:
6105 * - {Querying}[#class-Numeric-label-Querying]
6106 * - {Comparing}[#class-Numeric-label-Comparing]
6107 * - {Converting}[#class-Numeric-label-Converting]
6108 * - {Other}[#class-Numeric-label-Other]
6110 * === Querying
6112 * - #finite?:: Returns true unless +self+ is infinite or not a number.
6113 * - #infinite?:: Returns -1, +nil+ or +1, depending on whether +self+
6114 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6115 * - #integer?:: Returns whether +self+ is an integer.
6116 * - #negative?:: Returns whether +self+ is negative.
6117 * - #nonzero?:: Returns whether +self+ is not zero.
6118 * - #positive?:: Returns whether +self+ is positive.
6119 * - #real?:: Returns whether +self+ is a real value.
6120 * - #zero?:: Returns whether +self+ is zero.
6122 * === Comparing
6124 * - {<=>}[#method-i-3C-3D-3E]:: Returns:
6125 * - -1 if +self+ is less than the given value.
6126 * - 0 if +self+ is equal to the given value.
6127 * - 1 if +self+ is greater than the given value.
6128 * - +nil+ if +self+ and the given value are not comparable.
6129 * - #eql?:: Returns whether +self+ and the given value have the same value and type.
6131 * === Converting
6133 * - #% (aliased as #modulo):: Returns the remainder of +self+ divided by the given value.
6134 * - #-@:: Returns the value of +self+, negated.
6135 * - #abs (aliased as #magnitude):: Returns the absolute value of +self+.
6136 * - #abs2:: Returns the square of +self+.
6137 * - #angle (aliased as #arg and #phase):: Returns 0 if +self+ is positive,
6138 * Math::PI otherwise.
6139 * - #ceil:: Returns the smallest number greater than or equal to +self+,
6140 * to a given precision.
6141 * - #coerce:: Returns array <tt>[coerced_self, coerced_other]</tt>
6142 * for the given other value.
6143 * - #conj (aliased as #conjugate):: Returns the complex conjugate of +self+.
6144 * - #denominator:: Returns the denominator (always positive)
6145 * of the Rational representation of +self+.
6146 * - #div:: Returns the value of +self+ divided by the given value
6147 * and converted to an integer.
6148 * - #divmod:: Returns array <tt>[quotient, modulus]</tt> resulting
6149 * from dividing +self+ the given divisor.
6150 * - #fdiv:: Returns the Float result of dividing +self+ by the given divisor.
6151 * - #floor:: Returns the largest number less than or equal to +self+,
6152 * to a given precision.
6153 * - #i:: Returns the Complex object <tt>Complex(0, self)</tt>.
6154 * the given value.
6155 * - #imaginary (aliased as #imag):: Returns the imaginary part of the +self+.
6156 * - #numerator:: Returns the numerator of the Rational representation of +self+;
6157 * has the same sign as +self+.
6158 * - #polar:: Returns the array <tt>[self.abs, self.arg]</tt>.
6159 * - #quo:: Returns the value of +self+ divided by the given value.
6160 * - #real:: Returns the real part of +self+.
6161 * - #rect (aliased as #rectangular):: Returns the array <tt>[self, 0]</tt>.
6162 * - #remainder:: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6163 * - #round:: Returns the value of +self+ rounded to the nearest value
6164 * for the given a precision.
6165 * - #to_c:: Returns the Complex representation of +self+.
6166 * - #to_int:: Returns the Integer representation of +self+, truncating if necessary.
6167 * - #truncate:: Returns +self+ truncated (toward zero) to a given precision.
6169 * === Other
6171 * - #clone:: Returns +self+; does not allow freezing.
6172 * - #dup (aliased as #+@):: Returns +self+.
6173 * - #step:: Invokes the given block with the sequence of specified numbers.
6176 void
6177 Init_Numeric(void)
6179 #ifdef _UNICOSMP
6180 /* Turn off floating point exceptions for divide by zero, etc. */
6181 _set_Creg(0, 0);
6182 #endif
6183 id_coerce = rb_intern_const("coerce");
6184 id_to = rb_intern_const("to");
6185 id_by = rb_intern_const("by");
6187 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6188 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6189 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6191 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6192 rb_include_module(rb_cNumeric, rb_mComparable);
6193 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6194 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6195 rb_define_method(rb_cNumeric, "dup", num_dup, 0);
6197 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6198 rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
6199 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6200 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6201 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6202 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6203 rb_define_method(rb_cNumeric, "div", num_div, 1);
6204 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6205 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6206 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6207 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6208 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6209 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6210 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6212 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6213 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6215 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6216 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6217 rb_define_method(rb_cNumeric, "round", num_round, -1);
6218 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6219 rb_define_method(rb_cNumeric, "step", num_step, -1);
6220 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6221 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6223 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6224 rb_undef_alloc_func(rb_cInteger);
6225 rb_undef_method(CLASS_OF(rb_cInteger), "new");
6226 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6227 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6229 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6230 rb_define_alias(rb_cInteger, "inspect", "to_s");
6231 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6232 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6233 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6234 rb_define_method(rb_cInteger, "upto", int_upto, 1);
6235 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6236 rb_define_method(rb_cInteger, "times", int_dotimes, 0);
6237 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6238 rb_define_method(rb_cInteger, "next", int_succ, 0);
6239 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6240 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6241 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6242 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6243 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6244 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6245 rb_define_method(rb_cInteger, "round", int_round, -1);
6246 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6248 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6249 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6250 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6251 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6252 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6253 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6254 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6255 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6256 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6257 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6258 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6260 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6262 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6263 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6264 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6265 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6266 rb_define_method(rb_cInteger, "<", int_lt, 1);
6267 rb_define_method(rb_cInteger, "<=", int_le, 1);
6269 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6270 rb_define_method(rb_cInteger, "|", int_or, 1);
6271 rb_define_method(rb_cInteger, "^", int_xor, 1);
6272 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6274 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6275 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6277 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6279 rb_fix_to_s_static[0] = rb_fstring_literal("0");
6280 rb_fix_to_s_static[1] = rb_fstring_literal("1");
6281 rb_fix_to_s_static[2] = rb_fstring_literal("2");
6282 rb_fix_to_s_static[3] = rb_fstring_literal("3");
6283 rb_fix_to_s_static[4] = rb_fstring_literal("4");
6284 rb_fix_to_s_static[5] = rb_fstring_literal("5");
6285 rb_fix_to_s_static[6] = rb_fstring_literal("6");
6286 rb_fix_to_s_static[7] = rb_fstring_literal("7");
6287 rb_fix_to_s_static[8] = rb_fstring_literal("8");
6288 rb_fix_to_s_static[9] = rb_fstring_literal("9");
6289 for(int i = 0; i < 10; i++) {
6290 rb_gc_register_mark_object(rb_fix_to_s_static[i]);
6293 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6295 rb_undef_alloc_func(rb_cFloat);
6296 rb_undef_method(CLASS_OF(rb_cFloat), "new");
6299 * The base of the floating point, or number of unique digits used to
6300 * represent the number.
6302 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6304 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6306 * The number of base digits for the +double+ data type.
6308 * Usually defaults to 53.
6310 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6312 * The minimum number of significant decimal digits in a double-precision
6313 * floating point.
6315 * Usually defaults to 15.
6317 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6319 * The smallest possible exponent value in a double-precision floating
6320 * point.
6322 * Usually defaults to -1021.
6324 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6326 * The largest possible exponent value in a double-precision floating
6327 * point.
6329 * Usually defaults to 1024.
6331 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6333 * The smallest negative exponent in a double-precision floating point
6334 * where 10 raised to this power minus 1.
6336 * Usually defaults to -307.
6338 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6340 * The largest positive exponent in a double-precision floating point where
6341 * 10 raised to this power minus 1.
6343 * Usually defaults to 308.
6345 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6347 * The smallest positive normalized number in a double-precision floating point.
6349 * Usually defaults to 2.2250738585072014e-308.
6351 * If the platform supports denormalized numbers,
6352 * there are numbers between zero and Float::MIN.
6353 * 0.0.next_float returns the smallest positive floating point number
6354 * including denormalized numbers.
6356 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6358 * The largest possible integer in a double-precision floating point number.
6360 * Usually defaults to 1.7976931348623157e+308.
6362 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6364 * The difference between 1 and the smallest double-precision floating
6365 * point number greater than 1.
6367 * Usually defaults to 2.2204460492503131e-16.
6369 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6371 * An expression representing positive infinity.
6373 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6375 * An expression representing a value which is "not a number".
6377 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6379 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6380 rb_define_alias(rb_cFloat, "inspect", "to_s");
6381 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6382 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6383 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6384 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6385 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6386 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6387 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6388 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6389 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6390 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6391 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6392 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6393 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6394 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6395 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6396 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6397 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6398 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6399 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6400 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6402 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6403 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6404 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6405 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6406 rb_define_method(rb_cFloat, "round", flo_round, -1);
6407 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6409 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6410 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6411 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6412 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6413 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6416 #undef rb_float_value
6417 double
6418 rb_float_value(VALUE v)
6420 return rb_float_value_inline(v);
6423 #undef rb_float_new
6424 VALUE
6425 rb_float_new(double d)
6427 return rb_float_new_inline(d);
6430 #include "numeric.rbinc"