1 /**********************************************************************
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"
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"
45 /* use IEEE 64bit values if not defined */
50 #define DBL_MIN 2.2250738585072014e-308
53 #define DBL_MAX 1.7976931348623157e+308
56 #define DBL_MIN_EXP (-1021)
59 #define DBL_MAX_EXP 1024
61 #ifndef DBL_MIN_10_EXP
62 #define DBL_MIN_10_EXP (-307)
64 #ifndef DBL_MAX_10_EXP
65 #define DBL_MAX_10_EXP 308
71 #define DBL_MANT_DIG 53
74 #define DBL_EPSILON 2.2204460492503131e-16
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}};
81 const union bytesequence4_or_float rb_infinity
= {{0x7f, 0x80, 0x00, 0x00}};
85 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
86 const union bytesequence4_or_float rb_nan
= {{0x00, 0x00, 0xc0, 0x7f}};
88 const union bytesequence4_or_float rb_nan
= {{0x7f, 0xc0, 0x00, 0x00}};
99 x
= f
+ (x
- f
>= 0.5);
103 x
= f
- (f
- x
>= 0.5);
110 round_half_up(double x
, double s
)
112 double f
, xs
= x
* s
;
115 if (s
== 1.0) return f
;
117 if ((double)((f
+ 0.5) / s
) <= x
) f
+= 1;
121 if ((double)((f
- 0.5) / s
) >= x
) f
-= 1;
128 round_half_down(double x
, double s
)
130 double f
, xs
= x
* s
;
134 if ((double)((f
- 0.5) / s
) >= x
) f
-= 1;
138 if ((double)((f
+ 0.5) / s
) <= x
) f
+= 1;
145 round_half_even(double x
, double s
)
147 double u
, v
, us
, vs
, f
, d
, uf
;
159 else if (d
== 0.5 || ((double)((uf
+ 0.5) / s
) <= x
))
171 else if (d
== 0.5 || ((double)((uf
- 0.5) / s
) >= x
))
180 static VALUE
fix_lshift(long, unsigned long);
181 static VALUE
fix_rshift(long, unsigned long);
182 static VALUE
int_pow(long x
, unsigned long y
);
183 static VALUE
rb_int_floor(VALUE num
, int ndigits
);
184 static VALUE
rb_int_ceil(VALUE num
, int ndigits
);
185 static VALUE
flo_to_i(VALUE num
);
186 static int float_round_overflow(int ndigits
, int binexp
);
187 static int float_round_underflow(int ndigits
, int binexp
);
191 #define id_divmod idDivmod
192 #define id_to_i idTo_i
200 VALUE rb_eZeroDivError
;
201 VALUE rb_eFloatDomainError
;
203 static ID id_to
, id_by
;
208 rb_raise(rb_eZeroDivError
, "divided by 0");
211 enum ruby_num_rounding_mode
212 rb_num_get_rounding_option(VALUE opts
)
214 static ID round_kwds
[1];
220 if (!round_kwds
[0]) {
221 round_kwds
[0] = rb_intern_const("half");
223 if (!rb_get_kwargs(opts
, round_kwds
, 0, 1, &rounding
)) goto noopt
;
224 if (SYMBOL_P(rounding
)) {
225 str
= rb_sym2str(rounding
);
227 else if (NIL_P(rounding
)) {
230 else if (!RB_TYPE_P(str
= rounding
, T_STRING
)) {
231 str
= rb_check_string_type(rounding
);
232 if (NIL_P(str
)) goto invalid
;
234 rb_must_asciicompat(str
);
235 s
= RSTRING_PTR(str
);
236 switch (RSTRING_LEN(str
)) {
238 if (rb_memcicmp(s
, "up", 2) == 0)
239 return RUBY_NUM_ROUND_HALF_UP
;
242 if (rb_memcicmp(s
, "even", 4) == 0)
243 return RUBY_NUM_ROUND_HALF_EVEN
;
244 if (strncasecmp(s
, "down", 4) == 0)
245 return RUBY_NUM_ROUND_HALF_DOWN
;
249 rb_raise(rb_eArgError
, "invalid rounding mode: % "PRIsVALUE
, rounding
);
252 return RUBY_NUM_ROUND_DEFAULT
;
255 /* experimental API */
257 rb_num_to_uint(VALUE val
, unsigned int *ret
)
259 #define NUMERR_TYPE 1
260 #define NUMERR_NEGATIVE 2
261 #define NUMERR_TOOLARGE 3
263 long v
= FIX2LONG(val
);
264 #if SIZEOF_INT < SIZEOF_LONG
265 if (v
> (long)UINT_MAX
) return NUMERR_TOOLARGE
;
267 if (v
< 0) return NUMERR_NEGATIVE
;
268 *ret
= (unsigned int)v
;
272 if (RB_BIGNUM_TYPE_P(val
)) {
273 if (BIGNUM_NEGATIVE_P(val
)) return NUMERR_NEGATIVE
;
274 #if SIZEOF_INT < SIZEOF_LONG
276 return NUMERR_TOOLARGE
;
279 if (rb_absint_size(val
, NULL
) > sizeof(int)) return NUMERR_TOOLARGE
;
280 *ret
= (unsigned int)rb_big2ulong((VALUE
)val
);
287 #define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
293 return FIXNUM_POSITIVE_P(num
);
295 else if (RB_BIGNUM_TYPE_P(num
)) {
296 return BIGNUM_POSITIVE_P(num
);
298 rb_raise(rb_eTypeError
, "not an Integer");
305 return FIXNUM_NEGATIVE_P(num
);
307 else if (RB_BIGNUM_TYPE_P(num
)) {
308 return BIGNUM_NEGATIVE_P(num
);
310 rb_raise(rb_eTypeError
, "not an Integer");
314 rb_int_positive_p(VALUE num
)
316 return int_pos_p(num
);
320 rb_int_negative_p(VALUE num
)
322 return int_neg_p(num
);
326 rb_num_negative_p(VALUE num
)
328 return rb_num_negative_int_p(num
);
332 num_funcall_op_0(VALUE x
, VALUE arg
, int recursive
)
336 const char *name
= rb_id2name(func
);
337 if (ISALNUM(name
[0])) {
338 rb_name_error(func
, "%"PRIsVALUE
".%"PRIsVALUE
,
341 else if (name
[0] && name
[1] == '@' && !name
[2]) {
342 rb_name_error(func
, "%c%"PRIsVALUE
,
346 rb_name_error(func
, "%"PRIsVALUE
"%"PRIsVALUE
,
350 return rb_funcallv(x
, func
, 0, 0);
354 num_funcall0(VALUE x
, ID func
)
356 return rb_exec_recursive(num_funcall_op_0
, x
, (VALUE
)func
);
359 NORETURN(static void num_funcall_op_1_recursion(VALUE x
, ID func
, VALUE y
));
362 num_funcall_op_1_recursion(VALUE x
, ID func
, VALUE y
)
364 const char *name
= rb_id2name(func
);
365 if (ISALNUM(name
[0])) {
366 rb_name_error(func
, "%"PRIsVALUE
".%"PRIsVALUE
"(%"PRIsVALUE
")",
370 rb_name_error(func
, "%"PRIsVALUE
"%"PRIsVALUE
"%"PRIsVALUE
,
376 num_funcall_op_1(VALUE y
, VALUE arg
, int recursive
)
378 ID func
= (ID
)((VALUE
*)arg
)[0];
379 VALUE x
= ((VALUE
*)arg
)[1];
381 num_funcall_op_1_recursion(x
, func
, y
);
383 return rb_funcall(x
, func
, 1, y
);
387 num_funcall1(VALUE x
, ID func
, VALUE y
)
390 args
[0] = (VALUE
)func
;
392 return rb_exec_recursive_paired(num_funcall_op_1
, y
, x
, (VALUE
)args
);
397 * coerce(other) -> array
399 * Returns a 2-element array containing two numeric elements,
400 * formed from the two operands +self+ and +other+,
401 * of a common compatible type.
403 * Of the Core and Standard Library classes,
404 * Integer, Rational, and Complex use this implementation.
409 * i.coerce(3) # => [3, 2]
410 * i.coerce(3.0) # => [3.0, 2.0]
411 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
412 * i.coerce(Complex(3, 4)) # Raises RangeError.
414 * r = Rational(5, 2) # => (5/2)
415 * r.coerce(2) # => [(2/1), (5/2)]
416 * r.coerce(2.0) # => [2.0, 2.5]
417 * r.coerce(Rational(2, 3)) # => [(2/3), (5/2)]
418 * r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)]
420 * c = Complex(2, 3) # => (2+3i)
421 * c.coerce(2) # => [(2+0i), (2+3i)]
422 * c.coerce(2.0) # => [(2.0+0i), (2+3i)]
423 * c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)]
424 * c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
426 * Raises an exception if any type conversion fails.
431 num_coerce(VALUE x
, VALUE y
)
433 if (CLASS_OF(x
) == CLASS_OF(y
))
434 return rb_assoc_new(y
, x
);
437 return rb_assoc_new(y
, x
);
440 NORETURN(static void coerce_failed(VALUE x
, VALUE y
));
442 coerce_failed(VALUE x
, VALUE y
)
444 if (SPECIAL_CONST_P(y
) || SYMBOL_P(y
) || RB_FLOAT_TYPE_P(y
)) {
450 rb_raise(rb_eTypeError
, "%"PRIsVALUE
" can't be coerced into %"PRIsVALUE
,
455 do_coerce(VALUE
*x
, VALUE
*y
, int err
)
457 VALUE ary
= rb_check_funcall(*y
, id_coerce
, 1, x
);
460 coerce_failed(*x
, *y
);
464 if (!err
&& NIL_P(ary
)) {
467 if (!RB_TYPE_P(ary
, T_ARRAY
) || RARRAY_LEN(ary
) != 2) {
468 rb_raise(rb_eTypeError
, "coerce must return [x, y]");
471 *x
= RARRAY_AREF(ary
, 0);
472 *y
= RARRAY_AREF(ary
, 1);
477 rb_num_coerce_bin(VALUE x
, VALUE y
, ID func
)
479 do_coerce(&x
, &y
, TRUE
);
480 return rb_funcall(x
, func
, 1, y
);
484 rb_num_coerce_cmp(VALUE x
, VALUE y
, ID func
)
486 if (do_coerce(&x
, &y
, FALSE
))
487 return rb_funcall(x
, func
, 1, y
);
492 ensure_cmp(VALUE c
, VALUE x
, VALUE y
)
494 if (NIL_P(c
)) rb_cmperr(x
, y
);
499 rb_num_coerce_relop(VALUE x
, VALUE y
, ID func
)
501 VALUE x0
= x
, y0
= y
;
503 if (!do_coerce(&x
, &y
, FALSE
)) {
505 UNREACHABLE_RETURN(Qnil
);
507 return ensure_cmp(rb_funcall(x
, func
, 1, y
), x0
, y0
);
510 NORETURN(static VALUE
num_sadded(VALUE x
, VALUE name
));
515 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
517 * Numerics should be values; singleton_methods should not be added to them.
521 num_sadded(VALUE x
, VALUE name
)
523 ID mid
= rb_to_id(name
);
524 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
525 rb_remove_method_id(rb_singleton_class(x
), mid
);
526 rb_raise(rb_eTypeError
,
527 "can't define singleton method \"%"PRIsVALUE
"\" for %"PRIsVALUE
,
531 UNREACHABLE_RETURN(Qnil
);
537 * clone(freeze: true) -> self
541 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
543 * Related: Numeric#dup.
547 num_clone(int argc
, VALUE
*argv
, VALUE x
)
549 return rb_immutable_obj_clone(argc
, argv
, x
);
552 # define num_clone rb_immutable_obj_clone
562 * Related: Numeric#clone.
571 # define num_dup num_uplus
592 * Returns <tt>Complex(0, self)</tt>:
596 * 2.0.i # => (0+2.0i)
597 * Rational(1, 2).i # => (0+(1/2)*i)
598 * Complex(3, 4).i # Raises NoMethodError.
603 num_imaginary(VALUE num
)
605 return rb_complex_new(INT2FIX(0), num
);
612 * Unary Minus---Returns the receiver, negated.
616 num_uminus(VALUE num
)
621 do_coerce(&zero
, &num
, TRUE
);
623 return num_funcall1(zero
, '-', num
);
628 * fdiv(other) -> float
630 * Returns the quotient <tt>self/other</tt> as a float,
631 * using method +/+ in the derived class of +self+.
632 * (\Numeric itself does not define method +/+.)
634 * Of the Core and Standard Library classes,
635 * only BigDecimal uses this implementation.
640 num_fdiv(VALUE x
, VALUE y
)
642 return rb_funcall(rb_Float(x
), '/', 1, y
);
647 * div(other) -> integer
649 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
650 * using method +/+ in the derived class of +self+.
651 * (\Numeric itself does not define method +/+.)
653 * Of the Core and Standard Library classes,
654 * Only Float and Rational use this implementation.
659 num_div(VALUE x
, VALUE y
)
661 if (rb_equal(INT2FIX(0), y
)) rb_num_zerodiv();
662 return rb_funcall(num_funcall1(x
, '/', y
), rb_intern("floor"), 0);
667 * self % other -> real_numeric
669 * Returns +self+ modulo +other+ as a real number.
671 * Of the Core and Standard Library classes,
672 * only Rational uses this implementation.
674 * For Rational +r+ and real number +n+, these expressions are equivalent:
680 * See Numeric#divmod.
684 * r = Rational(1, 2) # => (1/2)
685 * r2 = Rational(2, 3) # => (2/3)
690 * r = Rational(301,100) # => (301/100)
691 * r2 = Rational(7,5) # => (7/5)
692 * r % r2 # => (21/100)
693 * r % -r2 # => (-119/100)
694 * (-r) % r2 # => (119/100)
695 * (-r) %-r2 # => (-21/100)
700 num_modulo(VALUE x
, VALUE y
)
702 VALUE q
= num_funcall1(x
, id_div
, y
);
703 return rb_funcall(x
, '-', 1,
704 rb_funcall(y
, '*', 1, q
));
709 * remainder(other) -> real_number
711 * Returns the remainder after dividing +self+ by +other+.
713 * Of the Core and Standard Library classes,
714 * only Float and Rational use this implementation.
718 * 11.0.remainder(4) # => 3.0
719 * 11.0.remainder(-4) # => 3.0
720 * -11.0.remainder(4) # => -3.0
721 * -11.0.remainder(-4) # => -3.0
723 * 12.0.remainder(4) # => 0.0
724 * 12.0.remainder(-4) # => 0.0
725 * -12.0.remainder(4) # => -0.0
726 * -12.0.remainder(-4) # => -0.0
728 * 13.0.remainder(4.0) # => 1.0
729 * 13.0.remainder(Rational(4, 1)) # => 1.0
731 * Rational(13, 1).remainder(4) # => (1/1)
732 * Rational(13, 1).remainder(-4) # => (1/1)
733 * Rational(-13, 1).remainder(4) # => (-1/1)
734 * Rational(-13, 1).remainder(-4) # => (-1/1)
739 num_remainder(VALUE x
, VALUE y
)
741 if (!rb_obj_is_kind_of(y
, rb_cNumeric
)) {
742 do_coerce(&x
, &y
, TRUE
);
744 VALUE z
= num_funcall1(x
, '%', y
);
746 if ((!rb_equal(z
, INT2FIX(0))) &&
747 ((rb_num_negative_int_p(x
) &&
748 rb_num_positive_int_p(y
)) ||
749 (rb_num_positive_int_p(x
) &&
750 rb_num_negative_int_p(y
)))) {
751 if (RB_FLOAT_TYPE_P(y
)) {
752 if (isinf(RFLOAT_VALUE(y
))) {
756 return rb_funcall(z
, '-', 1, y
);
763 * divmod(other) -> array
765 * Returns a 2-element array <tt>[q, r]</tt>, where
767 * q = (self/other).floor # Quotient
768 * r = self % other # Remainder
770 * Of the Core and Standard Library classes,
771 * only Rational uses this implementation.
775 * Rational(11, 1).divmod(4) # => [2, (3/1)]
776 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
777 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
778 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
780 * Rational(12, 1).divmod(4) # => [3, (0/1)]
781 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
782 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
783 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
785 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
786 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
790 num_divmod(VALUE x
, VALUE y
)
792 return rb_assoc_new(num_div(x
, y
), num_modulo(x
, y
));
799 * Returns the absolute value of +self+.
802 * (-34.56).abs #=> 34.56
803 * -34.56.abs #=> 34.56
810 if (rb_num_negative_int_p(num
)) {
811 return num_funcall0(num
, idUMinus
);
818 * zero? -> true or false
820 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
822 * Of the Core and Standard Library classes,
823 * only Rational and Complex use this implementation.
828 num_zero_p(VALUE num
)
830 return rb_equal(num
, INT2FIX(0));
834 int_zero_p(VALUE num
)
837 return FIXNUM_ZERO_P(num
);
839 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
840 return rb_bigzero_p(num
);
844 rb_int_zero_p(VALUE num
)
846 return RBOOL(int_zero_p(num
));
851 * nonzero? -> self or nil
853 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
854 * uses method <tt>zero?</tt> for the evaluation.
856 * The returned +self+ allows the method to be chained:
858 * a = %w[z Bb bB bb BB a aA Aa AA A]
859 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
860 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
862 * Of the Core and Standard Library classes,
863 * Integer, Float, Rational, and Complex use this implementation.
870 num_nonzero_p(VALUE num
)
872 if (RTEST(num_funcall0(num
, rb_intern("zero?")))) {
882 * Returns +self+ as an integer;
883 * converts using method +to_i+ in the derived class.
885 * Of the Core and Standard Library classes,
886 * only Rational and Complex use this implementation.
890 * Rational(1, 2).to_int # => 0
891 * Rational(2, 1).to_int # => 2
892 * Complex(2, 0).to_int # => 2
893 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
898 num_to_int(VALUE num
)
900 return num_funcall0(num
, id_to_i
);
905 * positive? -> true or false
907 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
912 num_positive_p(VALUE num
)
917 if (method_basic_p(rb_cInteger
))
918 return RBOOL((SIGNED_VALUE
)num
> (SIGNED_VALUE
)INT2FIX(0));
920 else if (RB_BIGNUM_TYPE_P(num
)) {
921 if (method_basic_p(rb_cInteger
))
922 return RBOOL(BIGNUM_POSITIVE_P(num
) && !rb_bigzero_p(num
));
924 return rb_num_compare_with_zero(num
, mid
);
929 * negative? -> true or false
931 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
936 num_negative_p(VALUE num
)
938 return RBOOL(rb_num_negative_int_p(num
));
942 /********************************************************************
944 * Document-class: Float
946 * A \Float object represents a sometimes-inexact real number using the native
947 * architecture's double-precision floating point representation.
949 * Floating point has a different arithmetic and is an inexact number.
950 * So you should know its esoteric system. See following:
952 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
953 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#-why-are-rubys-floats-imprecise
954 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
956 * You can create a \Float object explicitly with:
958 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
960 * You can convert certain objects to Floats with:
966 * First, what's elsewhere. \Class \Float:
969 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
970 * and {class Object}[rdoc-ref:Object@What-27s+Here].
971 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
973 * Here, class \Float provides methods for:
975 * - {Querying}[rdoc-ref:Float@Querying]
976 * - {Comparing}[rdoc-ref:Float@Comparing]
977 * - {Converting}[rdoc-ref:Float@Converting]
981 * - #finite?: Returns whether +self+ is finite.
982 * - #hash: Returns the integer hash code for +self+.
983 * - #infinite?: Returns whether +self+ is infinite.
984 * - #nan?: Returns whether +self+ is a NaN (not-a-number).
988 * - #<: Returns whether +self+ is less than the given value.
989 * - #<=: Returns whether +self+ is less than or equal to the given value.
990 * - #<=>: Returns a number indicating whether +self+ is less than, equal
991 * to, or greater than the given value.
992 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
994 * - #>: Returns whether +self+ is greater than the given value.
995 * - #>=: Returns whether +self+ is greater than or equal to the given value.
999 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
1000 * - #*: Returns the product of +self+ and the given value.
1001 * - #**: Returns the value of +self+ raised to the power of the given value.
1002 * - #+: Returns the sum of +self+ and the given value.
1003 * - #-: Returns the difference of +self+ and the given value.
1004 * - #/: Returns the quotient of +self+ and the given value.
1005 * - #ceil: Returns the smallest number greater than or equal to +self+.
1006 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
1008 * - #divmod: Returns a 2-element array containing the quotient and remainder
1009 * results of dividing +self+ by the given value.
1010 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
1011 * - #floor: Returns the greatest number smaller than or equal to +self+.
1012 * - #next_float: Returns the next-larger representable \Float.
1013 * - #prev_float: Returns the next-smaller representable \Float.
1014 * - #quo: Returns the quotient from dividing +self+ by the given value.
1015 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
1016 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
1017 * - #to_s (aliased as #inspect): Returns a string containing the place-value
1018 * representation of +self+ in the given radix.
1019 * - #truncate: Returns +self+ truncated to a given precision.
1024 rb_float_new_in_heap(double d
)
1026 NEWOBJ_OF(flt
, struct RFloat
, rb_cFloat
, T_FLOAT
| (RGENGC_WB_PROTECTED_FLOAT
? FL_WB_PROTECTED
: 0), sizeof(struct RFloat
), 0);
1028 #if SIZEOF_DOUBLE <= SIZEOF_VALUE
1029 flt
->float_value
= d
;
1033 rb_float_value_type v
;
1035 flt
->float_value
= u
.v
;
1037 OBJ_FREEZE((VALUE
)flt
);
1045 * Returns a string containing a representation of +self+;
1046 * depending of the value of +self+, the string representation
1049 * - A fixed-point number.
1050 * - A number in "scientific notation" (containing an exponent).
1053 * - 'NaN' (indicating not-a-number).
1055 * 3.14.to_s # => "3.14"
1056 * (10.1**50).to_s # => "1.644631821843879e+50"
1057 * (10.1**500).to_s # => "Infinity"
1058 * (-10.1**500).to_s # => "-Infinity"
1059 * (0.0/0.0).to_s # => "NaN"
1066 enum {decimal_mant
= DBL_MANT_DIG
-DBL_DIG
};
1067 enum {float_dig
= DBL_DIG
+1};
1068 char buf
[float_dig
+ roomof(decimal_mant
, CHAR_BIT
) + 10];
1069 double value
= RFLOAT_VALUE(flt
);
1072 int sign
, decpt
, digs
;
1075 static const char minf
[] = "-Infinity";
1076 const int pos
= (value
> 0); /* skip "-" */
1077 return rb_usascii_str_new(minf
+pos
, strlen(minf
)-pos
);
1079 else if (isnan(value
))
1080 return rb_usascii_str_new2("NaN");
1082 p
= ruby_dtoa(value
, 0, 0, &decpt
, &sign
, &e
);
1083 s
= sign
? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1084 if ((digs
= (int)(e
- p
)) >= (int)sizeof(buf
)) digs
= (int)sizeof(buf
) - 1;
1085 memcpy(buf
, p
, digs
);
1089 memmove(buf
+ decpt
+ 1, buf
+ decpt
, digs
- decpt
);
1091 rb_str_cat(s
, buf
, digs
+ 1);
1093 else if (decpt
<= DBL_DIG
) {
1096 rb_str_cat(s
, buf
, digs
);
1097 rb_str_resize(s
, (len
= RSTRING_LEN(s
)) + decpt
- digs
+ 2);
1098 ptr
= RSTRING_PTR(s
) + len
;
1100 memset(ptr
, '0', decpt
- digs
);
1101 ptr
+= decpt
- digs
;
1103 memcpy(ptr
, ".0", 2);
1109 else if (decpt
> -4) {
1112 rb_str_cat(s
, "0.", 2);
1113 rb_str_resize(s
, (len
= RSTRING_LEN(s
)) - decpt
+ digs
);
1114 ptr
= RSTRING_PTR(s
);
1115 memset(ptr
+= len
, '0', -decpt
);
1116 memcpy(ptr
-= decpt
, buf
, digs
);
1125 memmove(buf
+ 2, buf
+ 1, digs
- 1);
1132 rb_str_cat(s
, buf
, digs
+ 1);
1133 rb_str_catf(s
, "e%+03d", decpt
- 1);
1139 * coerce(other) -> array
1141 * Returns a 2-element array containing +other+ converted to a \Float
1144 * f = 3.14 # => 3.14
1145 * f.coerce(2) # => [2.0, 3.14]
1146 * f.coerce(2.0) # => [2.0, 3.14]
1147 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1148 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1150 * Raises an exception if a type conversion fails.
1155 flo_coerce(VALUE x
, VALUE y
)
1157 return rb_assoc_new(rb_Float(y
), x
);
1161 rb_float_uminus(VALUE flt
)
1163 return DBL2NUM(-RFLOAT_VALUE(flt
));
1168 * self + other -> numeric
1170 * Returns a new \Float which is the sum of +self+ and +other+:
1173 * f + 1 # => 4.140000000000001
1174 * f + 1.0 # => 4.140000000000001
1175 * f + Rational(1, 1) # => 4.140000000000001
1176 * f + Complex(1, 0) # => (4.140000000000001+0i)
1181 rb_float_plus(VALUE x
, VALUE y
)
1184 return DBL2NUM(RFLOAT_VALUE(x
) + (double)FIX2LONG(y
));
1186 else if (RB_BIGNUM_TYPE_P(y
)) {
1187 return DBL2NUM(RFLOAT_VALUE(x
) + rb_big2dbl(y
));
1189 else if (RB_FLOAT_TYPE_P(y
)) {
1190 return DBL2NUM(RFLOAT_VALUE(x
) + RFLOAT_VALUE(y
));
1193 return rb_num_coerce_bin(x
, y
, '+');
1199 * self - other -> numeric
1201 * Returns a new \Float which is the difference of +self+ and +other+:
1206 * f - Rational(1, 1) # => 2.14
1207 * f - Complex(1, 0) # => (2.14+0i)
1212 rb_float_minus(VALUE x
, VALUE y
)
1215 return DBL2NUM(RFLOAT_VALUE(x
) - (double)FIX2LONG(y
));
1217 else if (RB_BIGNUM_TYPE_P(y
)) {
1218 return DBL2NUM(RFLOAT_VALUE(x
) - rb_big2dbl(y
));
1220 else if (RB_FLOAT_TYPE_P(y
)) {
1221 return DBL2NUM(RFLOAT_VALUE(x
) - RFLOAT_VALUE(y
));
1224 return rb_num_coerce_bin(x
, y
, '-');
1230 * self * other -> numeric
1232 * Returns a new \Float which is the product of +self+ and +other+:
1237 * f * Rational(1, 2) # => 1.57
1238 * f * Complex(2, 0) # => (6.28+0.0i)
1242 rb_float_mul(VALUE x
, VALUE y
)
1245 return DBL2NUM(RFLOAT_VALUE(x
) * (double)FIX2LONG(y
));
1247 else if (RB_BIGNUM_TYPE_P(y
)) {
1248 return DBL2NUM(RFLOAT_VALUE(x
) * rb_big2dbl(y
));
1250 else if (RB_FLOAT_TYPE_P(y
)) {
1251 return DBL2NUM(RFLOAT_VALUE(x
) * RFLOAT_VALUE(y
));
1254 return rb_num_coerce_bin(x
, y
, '*');
1259 double_div_double(double x
, double y
)
1261 if (LIKELY(y
!= 0.0)) {
1264 else if (x
== 0.0) {
1268 double z
= signbit(y
) ? -1.0 : 1.0;
1269 return x
* z
* HUGE_VAL
;
1274 rb_flo_div_flo(VALUE x
, VALUE y
)
1276 double num
= RFLOAT_VALUE(x
);
1277 double den
= RFLOAT_VALUE(y
);
1278 double ret
= double_div_double(num
, den
);
1279 return DBL2NUM(ret
);
1284 * self / other -> numeric
1286 * Returns a new \Float which is the result of dividing +self+ by +other+:
1291 * f / Rational(2, 1) # => 1.57
1292 * f / Complex(2, 0) # => (1.57+0.0i)
1297 rb_float_div(VALUE x
, VALUE y
)
1299 double num
= RFLOAT_VALUE(x
);
1306 else if (RB_BIGNUM_TYPE_P(y
)) {
1307 den
= rb_big2dbl(y
);
1309 else if (RB_FLOAT_TYPE_P(y
)) {
1310 den
= RFLOAT_VALUE(y
);
1313 return rb_num_coerce_bin(x
, y
, '/');
1316 ret
= double_div_double(num
, den
);
1317 return DBL2NUM(ret
);
1322 * quo(other) -> numeric
1324 * Returns the quotient from dividing +self+ by +other+:
1327 * f.quo(2) # => 1.57
1328 * f.quo(-2) # => -1.57
1329 * f.quo(Rational(2, 1)) # => 1.57
1330 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1335 flo_quo(VALUE x
, VALUE y
)
1337 return num_funcall1(x
, '/', y
);
1341 flodivmod(double x
, double y
, double *divp
, double *modp
)
1346 /* y is NaN so all results are NaN */
1347 if (modp
) *modp
= y
;
1348 if (divp
) *divp
= y
;
1351 if (y
== 0.0) rb_num_zerodiv();
1352 if ((x
== 0.0) || (isinf(y
) && !isinf(x
)))
1364 if (isinf(x
) && !isinf(y
))
1367 div
= (x
- mod
) / y
;
1368 if (modp
&& divp
) div
= round(div
);
1374 if (modp
) *modp
= mod
;
1375 if (divp
) *divp
= div
;
1379 * Returns the modulo of division of x by y.
1380 * An error will be raised if y == 0.
1384 ruby_float_mod(double x
, double y
)
1387 flodivmod(x
, y
, 0, &mod
);
1393 * self % other -> float
1395 * Returns +self+ modulo +other+ as a float.
1397 * For float +f+ and real number +r+, these expressions are equivalent:
1403 * See Numeric#divmod.
1411 * 10.0 % -2 # => 0.0
1412 * 10.0 % -3 # => -2.0
1413 * 10.0 % -4 # => -2.0
1415 * 10.0 % 4.0 # => 2.0
1416 * 10.0 % Rational(4, 1) # => 2.0
1421 flo_mod(VALUE x
, VALUE y
)
1426 fy
= (double)FIX2LONG(y
);
1428 else if (RB_BIGNUM_TYPE_P(y
)) {
1431 else if (RB_FLOAT_TYPE_P(y
)) {
1432 fy
= RFLOAT_VALUE(y
);
1435 return rb_num_coerce_bin(x
, y
, '%');
1437 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x
), fy
));
1444 return LONG2FIX((long)d
);
1446 return rb_dbl2big(d
);
1451 * divmod(other) -> array
1453 * Returns a 2-element array <tt>[q, r]</tt>, where
1455 * q = (self/other).floor # Quotient
1456 * r = self % other # Remainder
1460 * 11.0.divmod(4) # => [2, 3.0]
1461 * 11.0.divmod(-4) # => [-3, -1.0]
1462 * -11.0.divmod(4) # => [-3, 1.0]
1463 * -11.0.divmod(-4) # => [2, -3.0]
1465 * 12.0.divmod(4) # => [3, 0.0]
1466 * 12.0.divmod(-4) # => [-3, 0.0]
1467 * -12.0.divmod(4) # => [-3, -0.0]
1468 * -12.0.divmod(-4) # => [3, -0.0]
1470 * 13.0.divmod(4.0) # => [3, 1.0]
1471 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1476 flo_divmod(VALUE x
, VALUE y
)
1478 double fy
, div
, mod
;
1479 volatile VALUE a
, b
;
1482 fy
= (double)FIX2LONG(y
);
1484 else if (RB_BIGNUM_TYPE_P(y
)) {
1487 else if (RB_FLOAT_TYPE_P(y
)) {
1488 fy
= RFLOAT_VALUE(y
);
1491 return rb_num_coerce_bin(x
, y
, id_divmod
);
1493 flodivmod(RFLOAT_VALUE(x
), fy
, &div
, &mod
);
1496 return rb_assoc_new(a
, b
);
1501 * self ** other -> numeric
1503 * Raises +self+ to the power of +other+:
1506 * f ** 2 # => 9.8596
1507 * f ** -2 # => 0.1014239928597509
1508 * f ** 2.1 # => 11.054834900588839
1509 * f ** Rational(2, 1) # => 9.8596
1510 * f ** Complex(2, 0) # => (9.8596+0i)
1515 rb_float_pow(VALUE x
, VALUE y
)
1518 if (y
== INT2FIX(2)) {
1519 dx
= RFLOAT_VALUE(x
);
1520 return DBL2NUM(dx
* dx
);
1522 else if (FIXNUM_P(y
)) {
1523 dx
= RFLOAT_VALUE(x
);
1524 dy
= (double)FIX2LONG(y
);
1526 else if (RB_BIGNUM_TYPE_P(y
)) {
1527 dx
= RFLOAT_VALUE(x
);
1530 else if (RB_FLOAT_TYPE_P(y
)) {
1531 dx
= RFLOAT_VALUE(x
);
1532 dy
= RFLOAT_VALUE(y
);
1533 if (dx
< 0 && dy
!= round(dy
))
1534 return rb_dbl_complex_new_polar_pi(pow(-dx
, dy
), dy
);
1537 return rb_num_coerce_bin(x
, y
, idPow
);
1539 return DBL2NUM(pow(dx
, dy
));
1544 * eql?(other) -> true or false
1546 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1548 * Of the Core and Standard Library classes,
1549 * only Integer, Rational, and Complex use this implementation.
1553 * 1.eql?(1) # => true
1554 * 1.eql?(1.0) # => false
1555 * 1.eql?(Rational(1, 1)) # => false
1556 * 1.eql?(Complex(1, 0)) # => false
1558 * \Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1559 * while <tt>==</tt> does not.
1564 num_eql(VALUE x
, VALUE y
)
1566 if (TYPE(x
) != TYPE(y
)) return Qfalse
;
1568 if (RB_BIGNUM_TYPE_P(x
)) {
1569 return rb_big_eql(x
, y
);
1572 return rb_equal(x
, y
);
1577 * self <=> other -> zero or nil
1579 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1581 * No subclass in the Ruby Core or Standard Library uses this implementation.
1586 num_cmp(VALUE x
, VALUE y
)
1588 if (x
== y
) return INT2FIX(0);
1593 num_equal(VALUE x
, VALUE y
)
1596 if (x
== y
) return Qtrue
;
1597 result
= num_funcall1(y
, id_eq
, x
);
1598 return RBOOL(RTEST(result
));
1603 * self == other -> true or false
1605 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1607 * 2.0 == 2 # => true
1608 * 2.0 == 2.0 # => true
1609 * 2.0 == Rational(2, 1) # => true
1610 * 2.0 == Complex(2, 0) # => true
1612 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1614 * Related: Float#eql? (requires +other+ to be a \Float).
1619 rb_float_equal(VALUE x
, VALUE y
)
1621 volatile double a
, b
;
1623 if (RB_INTEGER_TYPE_P(y
)) {
1624 return rb_integer_float_eq(y
, x
);
1626 else if (RB_FLOAT_TYPE_P(y
)) {
1627 b
= RFLOAT_VALUE(y
);
1628 #if MSC_VERSION_BEFORE(1300)
1629 if (isnan(b
)) return Qfalse
;
1633 return num_equal(x
, y
);
1635 a
= RFLOAT_VALUE(x
);
1636 #if MSC_VERSION_BEFORE(1300)
1637 if (isnan(a
)) return Qfalse
;
1639 return RBOOL(a
== b
);
1642 #define flo_eq rb_float_equal
1643 static VALUE
rb_dbl_hash(double d
);
1649 * Returns the integer hash value for +self+.
1651 * See also Object#hash.
1657 return rb_dbl_hash(RFLOAT_VALUE(num
));
1661 rb_dbl_hash(double d
)
1663 return ST2FIX(rb_dbl_long_hash(d
));
1667 rb_dbl_cmp(double a
, double b
)
1669 if (isnan(a
) || isnan(b
)) return Qnil
;
1670 if (a
== b
) return INT2FIX(0);
1671 if (a
> b
) return INT2FIX(1);
1672 if (a
< b
) return INT2FIX(-1);
1678 * self <=> other -> -1, 0, +1, or nil
1680 * Returns a value that depends on the numeric relation
1681 * between +self+ and +other+:
1683 * - -1, if +self+ is less than +other+.
1684 * - 0, if +self+ is equal to +other+.
1685 * - 1, if +self+ is greater than +other+.
1686 * - +nil+, if the two values are incommensurate.
1691 * 2.0 <=> 2.0 # => 0
1692 * 2.0 <=> Rational(2, 1) # => 0
1693 * 2.0 <=> Complex(2, 0) # => 0
1694 * 2.0 <=> 1.9 # => 1
1695 * 2.0 <=> 2.1 # => -1
1696 * 2.0 <=> 'foo' # => nil
1698 * This is the basis for the tests in the Comparable module.
1700 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1705 flo_cmp(VALUE x
, VALUE y
)
1710 a
= RFLOAT_VALUE(x
);
1711 if (isnan(a
)) return Qnil
;
1712 if (RB_INTEGER_TYPE_P(y
)) {
1713 VALUE rel
= rb_integer_float_cmp(y
, x
);
1715 return LONG2FIX(-FIX2LONG(rel
));
1718 else if (RB_FLOAT_TYPE_P(y
)) {
1719 b
= RFLOAT_VALUE(y
);
1722 if (isinf(a
) && !UNDEF_P(i
= rb_check_funcall(y
, rb_intern("infinite?"), 0, 0))) {
1724 int j
= rb_cmpint(i
, x
, y
);
1725 j
= (a
> 0.0) ? (j
> 0 ? 0 : +1) : (j
< 0 ? 0 : -1);
1728 if (a
> 0.0) return INT2FIX(1);
1731 return rb_num_coerce_cmp(x
, y
, id_cmp
);
1733 return rb_dbl_cmp(a
, b
);
1737 rb_float_cmp(VALUE x
, VALUE y
)
1739 return NUM2INT(ensure_cmp(flo_cmp(x
, y
), x
, y
));
1744 * self > other -> true or false
1746 * Returns +true+ if +self+ is numerically greater than +other+:
1749 * 2.0 > 1.0 # => true
1750 * 2.0 > Rational(1, 2) # => true
1751 * 2.0 > 2.0 # => false
1753 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1758 rb_float_gt(VALUE x
, VALUE y
)
1762 a
= RFLOAT_VALUE(x
);
1763 if (RB_INTEGER_TYPE_P(y
)) {
1764 VALUE rel
= rb_integer_float_cmp(y
, x
);
1766 return RBOOL(-FIX2LONG(rel
) > 0);
1769 else if (RB_FLOAT_TYPE_P(y
)) {
1770 b
= RFLOAT_VALUE(y
);
1771 #if MSC_VERSION_BEFORE(1300)
1772 if (isnan(b
)) return Qfalse
;
1776 return rb_num_coerce_relop(x
, y
, '>');
1778 #if MSC_VERSION_BEFORE(1300)
1779 if (isnan(a
)) return Qfalse
;
1781 return RBOOL(a
> b
);
1786 * self >= other -> true or false
1788 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1790 * 2.0 >= 1 # => true
1791 * 2.0 >= 1.0 # => true
1792 * 2.0 >= Rational(1, 2) # => true
1793 * 2.0 >= 2.0 # => true
1794 * 2.0 >= 2.1 # => false
1796 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1801 flo_ge(VALUE x
, VALUE y
)
1805 a
= RFLOAT_VALUE(x
);
1806 if (RB_TYPE_P(y
, T_FIXNUM
) || RB_BIGNUM_TYPE_P(y
)) {
1807 VALUE rel
= rb_integer_float_cmp(y
, x
);
1809 return RBOOL(-FIX2LONG(rel
) >= 0);
1812 else if (RB_FLOAT_TYPE_P(y
)) {
1813 b
= RFLOAT_VALUE(y
);
1814 #if MSC_VERSION_BEFORE(1300)
1815 if (isnan(b
)) return Qfalse
;
1819 return rb_num_coerce_relop(x
, y
, idGE
);
1821 #if MSC_VERSION_BEFORE(1300)
1822 if (isnan(a
)) return Qfalse
;
1824 return RBOOL(a
>= b
);
1829 * self < other -> true or false
1831 * Returns +true+ if +self+ is numerically less than +other+:
1834 * 2.0 < 3.0 # => true
1835 * 2.0 < Rational(3, 1) # => true
1836 * 2.0 < 2.0 # => false
1838 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1843 flo_lt(VALUE x
, VALUE y
)
1847 a
= RFLOAT_VALUE(x
);
1848 if (RB_INTEGER_TYPE_P(y
)) {
1849 VALUE rel
= rb_integer_float_cmp(y
, x
);
1851 return RBOOL(-FIX2LONG(rel
) < 0);
1854 else if (RB_FLOAT_TYPE_P(y
)) {
1855 b
= RFLOAT_VALUE(y
);
1856 #if MSC_VERSION_BEFORE(1300)
1857 if (isnan(b
)) return Qfalse
;
1861 return rb_num_coerce_relop(x
, y
, '<');
1863 #if MSC_VERSION_BEFORE(1300)
1864 if (isnan(a
)) return Qfalse
;
1866 return RBOOL(a
< b
);
1871 * self <= other -> true or false
1873 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1875 * 2.0 <= 3 # => true
1876 * 2.0 <= 3.0 # => true
1877 * 2.0 <= Rational(3, 1) # => true
1878 * 2.0 <= 2.0 # => true
1879 * 2.0 <= 1.0 # => false
1881 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1886 flo_le(VALUE x
, VALUE y
)
1890 a
= RFLOAT_VALUE(x
);
1891 if (RB_INTEGER_TYPE_P(y
)) {
1892 VALUE rel
= rb_integer_float_cmp(y
, x
);
1894 return RBOOL(-FIX2LONG(rel
) <= 0);
1897 else if (RB_FLOAT_TYPE_P(y
)) {
1898 b
= RFLOAT_VALUE(y
);
1899 #if MSC_VERSION_BEFORE(1300)
1900 if (isnan(b
)) return Qfalse
;
1904 return rb_num_coerce_relop(x
, y
, idLE
);
1906 #if MSC_VERSION_BEFORE(1300)
1907 if (isnan(a
)) return Qfalse
;
1909 return RBOOL(a
<= b
);
1914 * eql?(other) -> true or false
1916 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1917 * +false+ otherwise:
1919 * 2.0.eql?(2.0) # => true
1920 * 2.0.eql?(1.0) # => false
1921 * 2.0.eql?(1) # => false
1922 * 2.0.eql?(Rational(2, 1)) # => false
1923 * 2.0.eql?(Complex(2, 0)) # => false
1925 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1927 * Related: Float#== (performs type conversions).
1931 rb_float_eql(VALUE x
, VALUE y
)
1933 if (RB_FLOAT_TYPE_P(y
)) {
1934 double a
= RFLOAT_VALUE(x
);
1935 double b
= RFLOAT_VALUE(y
);
1936 #if MSC_VERSION_BEFORE(1300)
1937 if (isnan(a
) || isnan(b
)) return Qfalse
;
1939 return RBOOL(a
== b
);
1944 #define flo_eql rb_float_eql
1947 rb_float_abs(VALUE flt
)
1949 double val
= fabs(RFLOAT_VALUE(flt
));
1950 return DBL2NUM(val
);
1955 * nan? -> true or false
1957 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1961 * f = 0.0/0.0 #=> NaN
1966 flo_is_nan_p(VALUE num
)
1968 double value
= RFLOAT_VALUE(num
);
1970 return RBOOL(isnan(value
));
1975 * infinite? -> -1, 1, or nil
1979 * - 1, if +self+ is <tt>Infinity</tt>.
1980 * - -1 if +self+ is <tt>-Infinity</tt>.
1981 * - +nil+, otherwise.
1985 * f = 1.0/0.0 # => Infinity
1986 * f.infinite? # => 1
1987 * f = -1.0/0.0 # => -Infinity
1988 * f.infinite? # => -1
1990 * f.infinite? # => nil
1991 * f = 0.0/0.0 # => NaN
1992 * f.infinite? # => nil
1997 rb_flo_is_infinite_p(VALUE num
)
1999 double value
= RFLOAT_VALUE(num
);
2002 return INT2FIX( value
< 0 ? -1 : 1 );
2010 * finite? -> true or false
2012 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
2013 * +false+ otherwise:
2016 * f.finite? # => true
2017 * f = 1.0/0.0 # => Infinity
2018 * f.finite? # => false
2019 * f = -1.0/0.0 # => -Infinity
2020 * f.finite? # => false
2021 * f = 0.0/0.0 # => NaN
2022 * f.finite? # => false
2027 rb_flo_is_finite_p(VALUE num
)
2029 double value
= RFLOAT_VALUE(num
);
2031 return RBOOL(isfinite(value
));
2035 flo_nextafter(VALUE flo
, double value
)
2039 y
= nextafter(x
, value
);
2045 * next_float -> float
2047 * Returns the next-larger representable \Float.
2049 * These examples show the internally stored values (64-bit hexadecimal)
2050 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2052 * f = 0.0 # 0x0000000000000000
2053 * f.next_float # 0x0000000000000001
2055 * f = 0.01 # 0x3f847ae147ae147b
2056 * f.next_float # 0x3f847ae147ae147c
2058 * In the remaining examples here, the output is shown in the usual way
2061 * 0.01.next_float # => 0.010000000000000002
2062 * 1.0.next_float # => 1.0000000000000002
2063 * 100.0.next_float # => 100.00000000000001
2066 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2070 * 0 0x1.47ae147ae147bp-7 0.01
2071 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2072 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2073 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2075 * f = 0.0; 100.times { f += 0.1 }
2076 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2077 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2078 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2079 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2080 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2081 * "%a" % 10 # => "0x1.4p+3"
2082 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2084 * Related: Float#prev_float
2088 flo_next_float(VALUE vx
)
2090 return flo_nextafter(vx
, HUGE_VAL
);
2095 * float.prev_float -> float
2097 * Returns the next-smaller representable \Float.
2099 * These examples show the internally stored values (64-bit hexadecimal)
2100 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2102 * f = 5e-324 # 0x0000000000000001
2103 * f.prev_float # 0x0000000000000000
2105 * f = 0.01 # 0x3f847ae147ae147b
2106 * f.prev_float # 0x3f847ae147ae147a
2108 * In the remaining examples here, the output is shown in the usual way
2111 * 0.01.prev_float # => 0.009999999999999998
2112 * 1.0.prev_float # => 0.9999999999999999
2113 * 100.0.prev_float # => 99.99999999999999
2116 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2120 * 0 0x1.47ae147ae147bp-7 0.01
2121 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2122 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2123 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2125 * Related: Float#next_float.
2129 flo_prev_float(VALUE vx
)
2131 return flo_nextafter(vx
, -HUGE_VAL
);
2135 rb_float_floor(VALUE num
, int ndigits
)
2138 number
= RFLOAT_VALUE(num
);
2139 if (number
== 0.0) {
2140 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2145 frexp(number
, &binexp
);
2146 if (float_round_overflow(ndigits
, binexp
)) return num
;
2147 if (number
> 0.0 && float_round_underflow(ndigits
, binexp
))
2148 return DBL2NUM(0.0);
2149 f
= pow(10, ndigits
);
2150 mul
= floor(number
* f
);
2151 res
= (mul
+ 1) / f
;
2154 return DBL2NUM(res
);
2157 num
= dbl2ival(floor(number
));
2158 if (ndigits
< 0) num
= rb_int_floor(num
, ndigits
);
2164 flo_ndigits(int argc
, VALUE
*argv
)
2166 if (rb_check_arity(argc
, 0, 1)) {
2167 return NUM2INT(argv
[0]);
2174 * floor(ndigits = 0) -> float or integer
2176 * Returns the largest number less than or equal to +self+ with
2177 * a precision of +ndigits+ decimal digits.
2179 * When +ndigits+ is positive, returns a float with +ndigits+
2180 * digits after the decimal point (as available):
2183 * f.floor(1) # => 12345.6
2184 * f.floor(3) # => 12345.678
2186 * f.floor(1) # => -12345.7
2187 * f.floor(3) # => -12345.679
2189 * When +ndigits+ is non-positive, returns an integer with at least
2190 * <code>ndigits.abs</code> trailing zeros:
2193 * f.floor(0) # => 12345
2194 * f.floor(-3) # => 12000
2196 * f.floor(0) # => -12346
2197 * f.floor(-3) # => -13000
2199 * Note that the limited precision of floating-point arithmetic
2200 * may lead to surprising results:
2202 * (0.3 / 0.1).floor #=> 2 (!)
2204 * Related: Float#ceil.
2209 flo_floor(int argc
, VALUE
*argv
, VALUE num
)
2211 int ndigits
= flo_ndigits(argc
, argv
);
2212 return rb_float_floor(num
, ndigits
);
2217 * ceil(ndigits = 0) -> float or integer
2219 * Returns the smallest number greater than or equal to +self+ with
2220 * a precision of +ndigits+ decimal digits.
2222 * When +ndigits+ is positive, returns a float with +ndigits+
2223 * digits after the decimal point (as available):
2226 * f.ceil(1) # => 12345.7
2227 * f.ceil(3) # => 12345.679
2229 * f.ceil(1) # => -12345.6
2230 * f.ceil(3) # => -12345.678
2232 * When +ndigits+ is non-positive, returns an integer with at least
2233 * <code>ndigits.abs</code> trailing zeros:
2236 * f.ceil(0) # => 12346
2237 * f.ceil(-3) # => 13000
2239 * f.ceil(0) # => -12345
2240 * f.ceil(-3) # => -12000
2242 * Note that the limited precision of floating-point arithmetic
2243 * may lead to surprising results:
2245 * (2.1 / 0.7).ceil #=> 4 (!)
2247 * Related: Float#floor.
2252 flo_ceil(int argc
, VALUE
*argv
, VALUE num
)
2254 int ndigits
= flo_ndigits(argc
, argv
);
2255 return rb_float_ceil(num
, ndigits
);
2259 rb_float_ceil(VALUE num
, int ndigits
)
2263 number
= RFLOAT_VALUE(num
);
2264 if (number
== 0.0) {
2265 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2269 frexp(number
, &binexp
);
2270 if (float_round_overflow(ndigits
, binexp
)) return num
;
2271 if (number
< 0.0 && float_round_underflow(ndigits
, binexp
))
2272 return DBL2NUM(0.0);
2273 f
= pow(10, ndigits
);
2274 f
= ceil(number
* f
) / f
;
2278 num
= dbl2ival(ceil(number
));
2279 if (ndigits
< 0) num
= rb_int_ceil(num
, ndigits
);
2285 int_round_zero_p(VALUE num
, int ndigits
)
2288 /* If 10**N / 2 > num, then return 0 */
2289 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2290 if (FIXNUM_P(num
)) {
2291 bytes
= sizeof(long);
2293 else if (RB_BIGNUM_TYPE_P(num
)) {
2294 bytes
= rb_big_size(num
);
2297 bytes
= NUM2LONG(rb_funcall(num
, idSize
, 0));
2299 return (-0.415241 * ndigits
- 0.125 > bytes
);
2303 int_round_half_even(SIGNED_VALUE x
, SIGNED_VALUE y
)
2305 SIGNED_VALUE z
= +(x
+ y
/ 2) / y
;
2306 if ((z
* y
- x
) * 2 == y
) {
2313 int_round_half_up(SIGNED_VALUE x
, SIGNED_VALUE y
)
2315 return (x
+ y
/ 2) / y
* y
;
2319 int_round_half_down(SIGNED_VALUE x
, SIGNED_VALUE y
)
2321 return (x
+ y
/ 2 - 1) / y
* y
;
2325 int_half_p_half_even(VALUE num
, VALUE n
, VALUE f
)
2327 return (int)rb_int_odd_p(rb_int_idiv(n
, f
));
2331 int_half_p_half_up(VALUE num
, VALUE n
, VALUE f
)
2333 return int_pos_p(num
);
2337 int_half_p_half_down(VALUE num
, VALUE n
, VALUE f
)
2339 return int_neg_p(num
);
2343 * Assumes num is an \Integer, ndigits <= 0
2346 rb_int_round(VALUE num
, int ndigits
, enum ruby_num_rounding_mode mode
)
2350 if (int_round_zero_p(num
, ndigits
)) {
2354 f
= int_pow(10, -ndigits
);
2355 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2356 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2359 x
= ROUND_CALL(mode
, int_round
, (x
, y
));
2363 if (RB_FLOAT_TYPE_P(f
)) {
2364 /* then int_pow overflow */
2367 h
= rb_int_idiv(f
, INT2FIX(2));
2368 r
= rb_int_modulo(num
, f
);
2369 n
= rb_int_minus(num
, r
);
2370 r
= rb_int_cmp(r
, h
);
2371 if (FIXNUM_POSITIVE_P(r
) ||
2372 (FIXNUM_ZERO_P(r
) && ROUND_CALL(mode
, int_half_p
, (num
, n
, f
)))) {
2373 n
= rb_int_plus(n
, f
);
2379 rb_int_floor(VALUE num
, int ndigits
)
2383 if (int_round_zero_p(num
, ndigits
))
2385 f
= int_pow(10, -ndigits
);
2386 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2387 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2389 if (neg
) x
= -x
+ y
- 1;
2394 if (RB_FLOAT_TYPE_P(f
)) {
2395 /* then int_pow overflow */
2398 return rb_int_minus(num
, rb_int_modulo(num
, f
));
2402 rb_int_ceil(VALUE num
, int ndigits
)
2406 if (int_round_zero_p(num
, ndigits
))
2408 f
= int_pow(10, -ndigits
);
2409 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2410 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2418 if (RB_FLOAT_TYPE_P(f
)) {
2419 /* then int_pow overflow */
2422 return rb_int_plus(num
, rb_int_minus(f
, rb_int_modulo(num
, f
)));
2426 rb_int_truncate(VALUE num
, int ndigits
)
2431 if (int_round_zero_p(num
, ndigits
))
2433 f
= int_pow(10, -ndigits
);
2434 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2435 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2442 if (RB_FLOAT_TYPE_P(f
)) {
2443 /* then int_pow overflow */
2446 m
= rb_int_modulo(num
, f
);
2447 if (int_neg_p(num
)) {
2448 return rb_int_plus(num
, rb_int_minus(f
, m
));
2451 return rb_int_minus(num
, m
);
2457 * round(ndigits = 0, half: :up) -> integer or float
2459 * Returns +self+ rounded to the nearest value with
2460 * a precision of +ndigits+ decimal digits.
2462 * When +ndigits+ is non-negative, returns a float with +ndigits+
2463 * after the decimal point (as available):
2466 * f.round(1) # => 12345.7
2467 * f.round(3) # => 12345.679
2469 * f.round(1) # => -12345.7
2470 * f.round(3) # => -12345.679
2472 * When +ndigits+ is negative, returns an integer
2473 * with at least <tt>ndigits.abs</tt> trailing zeros:
2476 * f.round(0) # => 12346
2477 * f.round(-3) # => 12000
2479 * f.round(0) # => -12346
2480 * f.round(-3) # => -12000
2482 * If keyword argument +half+ is given,
2483 * and +self+ is equidistant from the two candidate values,
2484 * the rounding is according to the given +half+ value:
2486 * - +:up+ or +nil+: round away from zero:
2488 * 2.5.round(half: :up) # => 3
2489 * 3.5.round(half: :up) # => 4
2490 * (-2.5).round(half: :up) # => -3
2492 * - +:down+: round toward zero:
2494 * 2.5.round(half: :down) # => 2
2495 * 3.5.round(half: :down) # => 3
2496 * (-2.5).round(half: :down) # => -2
2498 * - +:even+: round toward the candidate whose last nonzero digit is even:
2500 * 2.5.round(half: :even) # => 2
2501 * 3.5.round(half: :even) # => 4
2502 * (-2.5).round(half: :even) # => -2
2504 * Raises and exception if the value for +half+ is invalid.
2506 * Related: Float#truncate.
2511 flo_round(int argc
, VALUE
*argv
, VALUE num
)
2513 double number
, f
, x
;
2516 enum ruby_num_rounding_mode mode
;
2518 if (rb_scan_args(argc
, argv
, "01:", &nd
, &opt
)) {
2519 ndigits
= NUM2INT(nd
);
2521 mode
= rb_num_get_rounding_option(opt
);
2522 number
= RFLOAT_VALUE(num
);
2523 if (number
== 0.0) {
2524 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2527 return rb_int_round(flo_to_i(num
), ndigits
, mode
);
2530 x
= ROUND_CALL(mode
, round
, (number
, 1.0));
2533 if (isfinite(number
)) {
2535 frexp(number
, &binexp
);
2536 if (float_round_overflow(ndigits
, binexp
)) return num
;
2537 if (float_round_underflow(ndigits
, binexp
)) return DBL2NUM(0);
2539 /* In this case, pow(10, ndigits) may not be accurate. */
2540 return rb_flo_round_by_rational(argc
, argv
, num
);
2542 f
= pow(10, ndigits
);
2543 x
= ROUND_CALL(mode
, round
, (number
, f
));
2544 return DBL2NUM(x
/ f
);
2550 float_round_overflow(int ndigits
, int binexp
)
2552 enum {float_dig
= DBL_DIG
+2};
2554 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2555 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2556 Recall that up to float_dig digits can be needed to represent a double,
2557 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2558 will be an integer and thus the result is the original number.
2559 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2560 if ndigits + exp < 0, the result is 0.
2562 2 ** (binexp-1) <= |number| < 2 ** binexp
2563 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2564 If binexp >= 0, and since log_2(10) = 3.322259:
2565 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2566 floor(binexp/4) <= exp <= ceil(binexp/3)
2567 If binexp <= 0, swap the /4 and the /3
2568 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2569 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2571 if (ndigits
>= float_dig
- (binexp
> 0 ? binexp
/ 4 : binexp
/ 3 - 1)) {
2578 float_round_underflow(int ndigits
, int binexp
)
2580 if (ndigits
< - (binexp
> 0 ? binexp
/ 3 + 1 : binexp
/ 4)) {
2590 * Returns +self+ truncated to an Integer.
2593 * (-1.2).to_i # => -1
2595 * Note that the limited precision of floating-point arithmetic
2596 * may lead to surprising results:
2598 * (0.3 / 0.1).to_i # => 2 (!)
2605 double f
= RFLOAT_VALUE(num
);
2607 if (f
> 0.0) f
= floor(f
);
2608 if (f
< 0.0) f
= ceil(f
);
2615 * truncate(ndigits = 0) -> float or integer
2617 * Returns +self+ truncated (toward zero) to
2618 * a precision of +ndigits+ decimal digits.
2620 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2621 * after the decimal point (as available):
2624 * f.truncate(1) # => 12345.6
2625 * f.truncate(3) # => 12345.678
2627 * f.truncate(1) # => -12345.6
2628 * f.truncate(3) # => -12345.678
2630 * When +ndigits+ is negative, returns an integer
2631 * with at least <tt>ndigits.abs</tt> trailing zeros:
2634 * f.truncate(0) # => 12345
2635 * f.truncate(-3) # => 12000
2637 * f.truncate(0) # => -12345
2638 * f.truncate(-3) # => -12000
2640 * Note that the limited precision of floating-point arithmetic
2641 * may lead to surprising results:
2643 * (0.3 / 0.1).truncate #=> 2 (!)
2645 * Related: Float#round.
2649 flo_truncate(int argc
, VALUE
*argv
, VALUE num
)
2651 if (signbit(RFLOAT_VALUE(num
)))
2652 return flo_ceil(argc
, argv
, num
);
2654 return flo_floor(argc
, argv
, num
);
2659 * floor(digits = 0) -> integer or float
2661 * Returns the largest number that is less than or equal to +self+ with
2662 * a precision of +digits+ decimal digits.
2664 * \Numeric implements this by converting +self+ to a Float and
2665 * invoking Float#floor.
2669 num_floor(int argc
, VALUE
*argv
, VALUE num
)
2671 return flo_floor(argc
, argv
, rb_Float(num
));
2676 * ceil(digits = 0) -> integer or float
2678 * Returns the smallest number that is greater than or equal to +self+ with
2679 * a precision of +digits+ decimal digits.
2681 * \Numeric implements this by converting +self+ to a Float and
2682 * invoking Float#ceil.
2686 num_ceil(int argc
, VALUE
*argv
, VALUE num
)
2688 return flo_ceil(argc
, argv
, rb_Float(num
));
2693 * round(digits = 0) -> integer or float
2695 * Returns +self+ rounded to the nearest value with
2696 * a precision of +digits+ decimal digits.
2698 * \Numeric implements this by converting +self+ to a Float and
2699 * invoking Float#round.
2703 num_round(int argc
, VALUE
* argv
, VALUE num
)
2705 return flo_round(argc
, argv
, rb_Float(num
));
2710 * truncate(digits = 0) -> integer or float
2712 * Returns +self+ truncated (toward zero) to
2713 * a precision of +digits+ decimal digits.
2715 * \Numeric implements this by converting +self+ to a Float and
2716 * invoking Float#truncate.
2720 num_truncate(int argc
, VALUE
*argv
, VALUE num
)
2722 return flo_truncate(argc
, argv
, rb_Float(num
));
2726 ruby_float_step_size(double beg
, double end
, double unit
, int excl
)
2728 const double epsilon
= DBL_EPSILON
;
2735 return unit
> 0 ? beg
<= end
: beg
>= end
;
2737 n
= (end
- beg
)/unit
;
2738 err
= (fabs(beg
) + fabs(end
) + fabs(end
-beg
)) / fabs(unit
) * epsilon
;
2739 if (err
>0.5) err
=0.5;
2746 d
= +((n
+ 1) * unit
) + beg
;
2751 else if (beg
> end
) {
2759 d
= +((n
+ 1) * unit
) + beg
;
2764 else if (beg
> end
) {
2773 ruby_float_step(VALUE from
, VALUE to
, VALUE step
, int excl
, int allow_endless
)
2775 if (RB_FLOAT_TYPE_P(from
) || RB_FLOAT_TYPE_P(to
) || RB_FLOAT_TYPE_P(step
)) {
2776 double unit
= NUM2DBL(step
);
2777 double beg
= NUM2DBL(from
);
2778 double end
= (allow_endless
&& NIL_P(to
)) ? (unit
< 0 ? -1 : 1)*HUGE_VAL
: NUM2DBL(to
);
2779 double n
= ruby_float_step_size(beg
, end
, unit
, excl
);
2783 /* if unit is infinity, i*unit+beg is NaN */
2784 if (n
) rb_yield(DBL2NUM(beg
));
2786 else if (unit
== 0) {
2787 VALUE val
= DBL2NUM(beg
);
2792 for (i
=0; i
<n
; i
++) {
2793 double d
= i
*unit
+beg
;
2794 if (unit
>= 0 ? end
< d
: d
< end
) d
= end
;
2795 rb_yield(DBL2NUM(d
));
2804 ruby_num_interval_step_size(VALUE from
, VALUE to
, VALUE step
, int excl
)
2806 if (FIXNUM_P(from
) && FIXNUM_P(to
) && FIXNUM_P(step
)) {
2809 diff
= FIX2LONG(step
);
2811 return DBL2NUM(HUGE_VAL
);
2813 delta
= FIX2LONG(to
) - FIX2LONG(from
);
2824 return ULONG2NUM(delta
/ diff
+ 1UL);
2826 else if (RB_FLOAT_TYPE_P(from
) || RB_FLOAT_TYPE_P(to
) || RB_FLOAT_TYPE_P(step
)) {
2827 double n
= ruby_float_step_size(NUM2DBL(from
), NUM2DBL(to
), NUM2DBL(step
), excl
);
2829 if (isinf(n
)) return DBL2NUM(n
);
2830 if (POSFIXABLE(n
)) return LONG2FIX((long)n
);
2831 return rb_dbl2big(n
);
2836 switch (rb_cmpint(rb_num_coerce_cmp(step
, INT2FIX(0), id_cmp
), step
, INT2FIX(0))) {
2837 case 0: return DBL2NUM(HUGE_VAL
);
2838 case -1: cmp
= '<'; break;
2840 if (RTEST(rb_funcall(from
, cmp
, 1, to
))) return INT2FIX(0);
2841 result
= rb_funcall(rb_funcall(to
, '-', 1, from
), id_div
, 1, step
);
2842 if (!excl
|| RTEST(rb_funcall(to
, cmp
, 1, rb_funcall(from
, '+', 1, rb_funcall(result
, '*', 1, step
))))) {
2843 result
= rb_funcall(result
, '+', 1, INT2FIX(1));
2850 num_step_negative_p(VALUE num
)
2853 VALUE zero
= INT2FIX(0);
2856 if (FIXNUM_P(num
)) {
2857 if (method_basic_p(rb_cInteger
))
2858 return (SIGNED_VALUE
)num
< 0;
2860 else if (RB_BIGNUM_TYPE_P(num
)) {
2861 if (method_basic_p(rb_cInteger
))
2862 return BIGNUM_NEGATIVE_P(num
);
2865 r
= rb_check_funcall(num
, '>', 1, &zero
);
2867 coerce_failed(num
, INT2FIX(0));
2873 num_step_extract_args(int argc
, const VALUE
*argv
, VALUE
*to
, VALUE
*step
, VALUE
*by
)
2877 argc
= rb_scan_args(argc
, argv
, "02:", to
, step
, &hash
);
2883 rb_get_kwargs(hash
, keys
, 0, 2, values
);
2884 if (!UNDEF_P(values
[0])) {
2885 if (argc
> 0) rb_raise(rb_eArgError
, "to is given twice");
2888 if (!UNDEF_P(values
[1])) {
2889 if (argc
> 1) rb_raise(rb_eArgError
, "step is given twice");
2898 num_step_check_fix_args(int argc
, VALUE
*to
, VALUE
*step
, VALUE by
, int fix_nil
, int allow_zero_step
)
2906 if (argc
> 1 && NIL_P(*step
)) {
2907 rb_raise(rb_eTypeError
, "step must be numeric");
2910 if (!allow_zero_step
&& rb_equal(*step
, INT2FIX(0))) {
2911 rb_raise(rb_eArgError
, "step can't be 0");
2916 desc
= num_step_negative_p(*step
);
2917 if (fix_nil
&& NIL_P(*to
)) {
2918 *to
= desc
? DBL2NUM(-HUGE_VAL
) : DBL2NUM(HUGE_VAL
);
2924 num_step_scan_args(int argc
, const VALUE
*argv
, VALUE
*to
, VALUE
*step
, int fix_nil
, int allow_zero_step
)
2927 argc
= num_step_extract_args(argc
, argv
, to
, step
, &by
);
2928 return num_step_check_fix_args(argc
, to
, step
, by
, fix_nil
, allow_zero_step
);
2932 num_step_size(VALUE from
, VALUE args
, VALUE eobj
)
2935 int argc
= args
? RARRAY_LENINT(args
) : 0;
2936 const VALUE
*argv
= args
? RARRAY_CONST_PTR(args
) : 0;
2938 num_step_scan_args(argc
, argv
, &to
, &step
, TRUE
, FALSE
);
2940 return ruby_num_interval_step_size(from
, to
, step
, FALSE
);
2945 * step(to = nil, by = 1) {|n| ... } -> self
2946 * step(to = nil, by = 1) -> enumerator
2947 * step(to = nil, by: 1) {|n| ... } -> self
2948 * step(to = nil, by: 1) -> enumerator
2949 * step(by: 1, to: ) {|n| ... } -> self
2950 * step(by: 1, to: ) -> enumerator
2951 * step(by: , to: nil) {|n| ... } -> self
2952 * step(by: , to: nil) -> enumerator
2954 * Generates a sequence of numbers; with a block given, traverses the sequence.
2956 * Of the Core and Standard Library classes,
2957 * Integer, Float, and Rational use this implementation.
2962 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2963 * squares # => [1, 9, 25, 49, 81]
2965 * The generated sequence:
2967 * - Begins with +self+.
2968 * - Continues at intervals of +by+ (which may not be zero).
2969 * - Ends with the last number that is within or equal to +to+;
2970 * that is, less than or equal to +to+ if +by+ is positive,
2971 * greater than or equal to +to+ if +by+ is negative.
2972 * If +to+ is +nil+, the sequence is of infinite length.
2974 * If a block is given, calls the block with each number in the sequence;
2975 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2977 * <b>Keyword Arguments</b>
2979 * With keyword arguments +by+ and +to+,
2980 * their values (or defaults) determine the step and limit:
2982 * # Both keywords given.
2984 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2985 * squares # => [16, 36, 64, 100]
2987 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2988 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2990 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2991 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2994 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2995 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2997 * # Only keyword to given.
2999 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
3000 * squares # => [16, 25, 36, 49, 64, 81, 100]
3003 * # Only keyword by given
3005 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3006 * squares # => [16, 36, 64, 100, 144]
3009 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3010 * e.class # => Enumerator::ArithmeticSequence
3012 * <b>Positional Arguments</b>
3014 * With optional positional arguments +to+ and +by+,
3015 * their values (or defaults) determine the step and limit:
3018 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3019 * squares # => [16, 36, 64, 100]
3021 * 4.step(10) {|i| squares.push(i*i) }
3022 * squares # => [16, 25, 36, 49, 64, 81, 100]
3024 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3025 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3027 * <b>Implementation Notes</b>
3029 * If all the arguments are integers, the loop operates using an integer
3032 * If any of the arguments are floating point numbers, all are converted
3033 * to floats, and the loop is executed
3034 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3035 * where <i>n = (limit - self)/step</i>.
3040 num_step(int argc
, VALUE
*argv
, VALUE from
)
3045 if (!rb_block_given_p()) {
3048 num_step_extract_args(argc
, argv
, &to
, &step
, &by
);
3055 else if (rb_equal(step
, INT2FIX(0))) {
3056 rb_raise(rb_eArgError
, "step can't be 0");
3058 if ((NIL_P(to
) || rb_obj_is_kind_of(to
, rb_cNumeric
)) &&
3059 rb_obj_is_kind_of(step
, rb_cNumeric
)) {
3060 return rb_arith_seq_new(from
, ID2SYM(rb_frame_this_func()), argc
, argv
,
3061 num_step_size
, from
, to
, step
, FALSE
);
3064 return SIZED_ENUMERATOR_KW(from
, 2, ((VALUE
[2]){to
, step
}), num_step_size
, FALSE
);
3067 desc
= num_step_scan_args(argc
, argv
, &to
, &step
, TRUE
, FALSE
);
3068 if (rb_equal(step
, INT2FIX(0))) {
3071 else if (RB_FLOAT_TYPE_P(to
)) {
3072 double f
= RFLOAT_VALUE(to
);
3073 inf
= isinf(f
) && (signbit(f
) ? desc
: !desc
);
3077 if (FIXNUM_P(from
) && (inf
|| FIXNUM_P(to
)) && FIXNUM_P(step
)) {
3078 long i
= FIX2LONG(from
);
3079 long diff
= FIX2LONG(step
);
3083 rb_yield(LONG2FIX(i
));
3086 long end
= FIX2LONG(to
);
3089 for (; i
>= end
; i
+= diff
)
3090 rb_yield(LONG2FIX(i
));
3093 for (; i
<= end
; i
+= diff
)
3094 rb_yield(LONG2FIX(i
));
3098 else if (!ruby_float_step(from
, to
, step
, FALSE
, FALSE
)) {
3102 for (;; i
= rb_funcall(i
, '+', 1, step
))
3106 ID cmp
= desc
? '<' : '>';
3108 for (; !RTEST(rb_funcall(i
, cmp
, 1, to
)); i
= rb_funcall(i
, '+', 1, step
))
3116 out_of_range_float(char (*pbuf
)[24], VALUE val
)
3118 char *const buf
= *pbuf
;
3121 snprintf(buf
, sizeof(*pbuf
), "%-.10g", RFLOAT_VALUE(val
));
3122 if ((s
= strchr(buf
, ' ')) != 0) *s
= '\0';
3126 #define FLOAT_OUT_OF_RANGE(val, type) do { \
3128 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3129 out_of_range_float(&buf, (val))); \
3132 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3133 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3134 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3135 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3136 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3138 LONG_MIN_MINUS_ONE < (n))
3141 rb_num2long(VALUE val
)
3145 rb_raise(rb_eTypeError
, "no implicit conversion from nil to integer");
3148 if (FIXNUM_P(val
)) return FIX2LONG(val
);
3150 else if (RB_FLOAT_TYPE_P(val
)) {
3151 if (RFLOAT_VALUE(val
) < LONG_MAX_PLUS_ONE
3152 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val
))) {
3153 return (long)RFLOAT_VALUE(val
);
3156 FLOAT_OUT_OF_RANGE(val
, "integer");
3159 else if (RB_BIGNUM_TYPE_P(val
)) {
3160 return rb_big2long(val
);
3163 val
= rb_to_int(val
);
3168 static unsigned long
3169 rb_num2ulong_internal(VALUE val
, int *wrap_p
)
3173 rb_raise(rb_eTypeError
, "no implicit conversion of nil into Integer");
3176 if (FIXNUM_P(val
)) {
3177 long l
= FIX2LONG(val
); /* this is FIX2LONG, intended */
3180 return (unsigned long)l
;
3182 else if (RB_FLOAT_TYPE_P(val
)) {
3183 double d
= RFLOAT_VALUE(val
);
3184 if (d
< ULONG_MAX_PLUS_ONE
&& LONG_MIN_MINUS_ONE_IS_LESS_THAN(d
)) {
3186 *wrap_p
= d
<= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3188 return (unsigned long)d
;
3189 return (unsigned long)(long)d
;
3192 FLOAT_OUT_OF_RANGE(val
, "integer");
3195 else if (RB_BIGNUM_TYPE_P(val
)) {
3197 unsigned long ul
= rb_big2ulong(val
);
3199 *wrap_p
= BIGNUM_NEGATIVE_P(val
);
3204 val
= rb_to_int(val
);
3210 rb_num2ulong(VALUE val
)
3212 return rb_num2ulong_internal(val
, NULL
);
3216 rb_out_of_int(SIGNED_VALUE num
)
3218 rb_raise(rb_eRangeError
, "integer %"PRIdVALUE
" too %s to convert to 'int'",
3219 num
, num
< 0 ? "small" : "big");
3222 #if SIZEOF_INT < SIZEOF_LONG
3226 if ((long)(int)num
!= num
) {
3232 check_uint(unsigned long num
, int sign
)
3236 if (num
< (unsigned long)INT_MIN
)
3237 rb_raise(rb_eRangeError
, "integer %ld too small to convert to 'unsigned int'", (long)num
);
3242 rb_raise(rb_eRangeError
, "integer %lu too big to convert to 'unsigned int'", num
);
3247 rb_num2int(VALUE val
)
3249 long num
= rb_num2long(val
);
3256 rb_fix2int(VALUE val
)
3258 long num
= FIXNUM_P(val
)?FIX2LONG(val
):rb_num2long(val
);
3265 rb_num2uint(VALUE val
)
3268 unsigned long num
= rb_num2ulong_internal(val
, &wrap
);
3270 check_uint(num
, wrap
);
3275 rb_fix2uint(VALUE val
)
3279 if (!FIXNUM_P(val
)) {
3280 return rb_num2uint(val
);
3282 num
= FIX2ULONG(val
);
3284 check_uint(num
, FIXNUM_NEGATIVE_P(val
));
3289 rb_num2int(VALUE val
)
3291 return rb_num2long(val
);
3295 rb_fix2int(VALUE val
)
3297 return FIX2INT(val
);
3301 rb_num2uint(VALUE val
)
3303 return rb_num2ulong(val
);
3307 rb_fix2uint(VALUE val
)
3309 return RB_FIX2ULONG(val
);
3313 NORETURN(static void rb_out_of_short(SIGNED_VALUE num
));
3315 rb_out_of_short(SIGNED_VALUE num
)
3317 rb_raise(rb_eRangeError
, "integer %"PRIdVALUE
" too %s to convert to 'short'",
3318 num
, num
< 0 ? "small" : "big");
3322 check_short(long num
)
3324 if ((long)(short)num
!= num
) {
3325 rb_out_of_short(num
);
3330 check_ushort(unsigned long num
, int sign
)
3334 if (num
< (unsigned long)SHRT_MIN
)
3335 rb_raise(rb_eRangeError
, "integer %ld too small to convert to 'unsigned short'", (long)num
);
3339 if (USHRT_MAX
< num
)
3340 rb_raise(rb_eRangeError
, "integer %lu too big to convert to 'unsigned short'", num
);
3345 rb_num2short(VALUE val
)
3347 long num
= rb_num2long(val
);
3354 rb_fix2short(VALUE val
)
3356 long num
= FIXNUM_P(val
)?FIX2LONG(val
):rb_num2long(val
);
3363 rb_num2ushort(VALUE val
)
3366 unsigned long num
= rb_num2ulong_internal(val
, &wrap
);
3368 check_ushort(num
, wrap
);
3373 rb_fix2ushort(VALUE val
)
3377 if (!FIXNUM_P(val
)) {
3378 return rb_num2ushort(val
);
3380 num
= FIX2ULONG(val
);
3382 check_ushort(num
, FIXNUM_NEGATIVE_P(val
));
3387 rb_num2fix(VALUE val
)
3391 if (FIXNUM_P(val
)) return val
;
3393 v
= rb_num2long(val
);
3395 rb_raise(rb_eRangeError
, "integer %ld out of range of fixnum", v
);
3401 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3402 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3403 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3405 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3407 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3408 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3410 LLONG_MIN_MINUS_ONE < (n))
3413 rb_num2ll(VALUE val
)
3416 rb_raise(rb_eTypeError
, "no implicit conversion from nil");
3419 if (FIXNUM_P(val
)) return (LONG_LONG
)FIX2LONG(val
);
3421 else if (RB_FLOAT_TYPE_P(val
)) {
3422 double d
= RFLOAT_VALUE(val
);
3423 if (d
< LLONG_MAX_PLUS_ONE
&& (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d
))) {
3424 return (LONG_LONG
)d
;
3427 FLOAT_OUT_OF_RANGE(val
, "long long");
3430 else if (RB_BIGNUM_TYPE_P(val
)) {
3431 return rb_big2ll(val
);
3433 else if (RB_TYPE_P(val
, T_STRING
)) {
3434 rb_raise(rb_eTypeError
, "no implicit conversion from string");
3436 else if (RB_TYPE_P(val
, T_TRUE
) || RB_TYPE_P(val
, T_FALSE
)) {
3437 rb_raise(rb_eTypeError
, "no implicit conversion from boolean");
3440 val
= rb_to_int(val
);
3445 rb_num2ull(VALUE val
)
3448 rb_raise(rb_eTypeError
, "no implicit conversion of nil into Integer");
3450 else if (FIXNUM_P(val
)) {
3451 return (LONG_LONG
)FIX2LONG(val
); /* this is FIX2LONG, intended */
3453 else if (RB_FLOAT_TYPE_P(val
)) {
3454 double d
= RFLOAT_VALUE(val
);
3455 if (d
< ULLONG_MAX_PLUS_ONE
&& LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d
)) {
3457 return (unsigned LONG_LONG
)d
;
3458 return (unsigned LONG_LONG
)(LONG_LONG
)d
;
3461 FLOAT_OUT_OF_RANGE(val
, "unsigned long long");
3464 else if (RB_BIGNUM_TYPE_P(val
)) {
3465 return rb_big2ull(val
);
3468 val
= rb_to_int(val
);
3469 return NUM2ULL(val
);
3473 #endif /* HAVE_LONG_LONG */
3475 /********************************************************************
3477 * Document-class: Integer
3479 * An \Integer object represents an integer value.
3481 * You can create an \Integer object explicitly with:
3483 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3485 * You can convert certain objects to Integers with:
3487 * - \Method #Integer.
3489 * An attempt to add a singleton method to an instance of this class
3490 * causes an exception to be raised.
3494 * First, what's elsewhere. \Class \Integer:
3497 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3498 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3499 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3501 * Here, class \Integer provides methods for:
3503 * - {Querying}[rdoc-ref:Integer@Querying]
3504 * - {Comparing}[rdoc-ref:Integer@Comparing]
3505 * - {Converting}[rdoc-ref:Integer@Converting]
3506 * - {Other}[rdoc-ref:Integer@Other]
3510 * - #allbits?: Returns whether all bits in +self+ are set.
3511 * - #anybits?: Returns whether any bits in +self+ are set.
3512 * - #nobits?: Returns whether no bits in +self+ are set.
3516 * - #<: Returns whether +self+ is less than the given value.
3517 * - #<=: Returns whether +self+ is less than or equal to the given value.
3518 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3519 * to, or greater than the given value.
3520 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3522 * - #>: Returns whether +self+ is greater than the given value.
3523 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3527 * - ::sqrt: Returns the integer square root of the given value.
3528 * - ::try_convert: Returns the given value converted to an \Integer.
3529 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3530 * - #&: Returns the bitwise AND of +self+ and the given value.
3531 * - #*: Returns the product of +self+ and the given value.
3532 * - #**: Returns the value of +self+ raised to the power of the given value.
3533 * - #+: Returns the sum of +self+ and the given value.
3534 * - #-: Returns the difference of +self+ and the given value.
3535 * - #/: Returns the quotient of +self+ and the given value.
3536 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3537 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3538 * - #[]: Returns a slice of bits from +self+.
3539 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3540 * - #ceil: Returns the smallest number greater than or equal to +self+.
3541 * - #chr: Returns a 1-character string containing the character
3542 * represented by the value of +self+.
3543 * - #digits: Returns an array of integers representing the base-radix digits
3545 * - #div: Returns the integer result of dividing +self+ by the given value.
3546 * - #divmod: Returns a 2-element array containing the quotient and remainder
3547 * results of dividing +self+ by the given value.
3548 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3549 * - #floor: Returns the greatest number smaller than or equal to +self+.
3550 * - #pow: Returns the modular exponentiation of +self+.
3551 * - #pred: Returns the integer predecessor of +self+.
3552 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3553 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3554 * - #succ (aliased as #next): Returns the integer successor of +self+.
3555 * - #to_f: Returns +self+ converted to a Float.
3556 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3557 * representation of +self+ in the given radix.
3558 * - #truncate: Returns +self+ truncated to the given precision.
3559 * - #|: Returns the bitwise OR of +self+ and the given value.
3563 * - #downto: Calls the given block with each integer value from +self+
3564 * down to the given value.
3565 * - #times: Calls the given block +self+ times with each integer
3566 * in <tt>(0..self-1)</tt>.
3567 * - #upto: Calls the given block with each integer value from +self+
3568 * up to the given value.
3573 rb_int_odd_p(VALUE num
)
3575 if (FIXNUM_P(num
)) {
3576 return RBOOL(num
& 2);
3579 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3580 return rb_big_odd_p(num
);
3585 int_even_p(VALUE num
)
3587 if (FIXNUM_P(num
)) {
3588 return RBOOL((num
& 2) == 0);
3591 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3592 return rb_big_even_p(num
);
3597 rb_int_even_p(VALUE num
)
3599 return int_even_p(num
);
3604 * allbits?(mask) -> true or false
3606 * Returns +true+ if all bits that are set (=1) in +mask+
3607 * are also set in +self+; returns +false+ otherwise.
3613 * 0b1010100 self & mask
3614 * true self.allbits?(mask)
3618 * 0b1010100 self & mask
3619 * false self.allbits?(mask)
3621 * Related: Integer#anybits?, Integer#nobits?.
3626 int_allbits_p(VALUE num
, VALUE mask
)
3628 mask
= rb_to_int(mask
);
3629 return rb_int_equal(rb_int_and(num
, mask
), mask
);
3634 * anybits?(mask) -> true or false
3636 * Returns +true+ if any bit that is set (=1) in +mask+
3637 * is also set in +self+; returns +false+ otherwise.
3643 * 0b10000010 self & mask
3644 * true self.anybits?(mask)
3648 * 0b00000000 self & mask
3649 * false self.anybits?(mask)
3651 * Related: Integer#allbits?, Integer#nobits?.
3656 int_anybits_p(VALUE num
, VALUE mask
)
3658 mask
= rb_to_int(mask
);
3659 return RBOOL(!int_zero_p(rb_int_and(num
, mask
)));
3664 * nobits?(mask) -> true or false
3666 * Returns +true+ if no bit that is set (=1) in +mask+
3667 * is also set in +self+; returns +false+ otherwise.
3673 * 0b00000000 self & mask
3674 * true self.nobits?(mask)
3678 * 0b00000001 self & mask
3679 * false self.nobits?(mask)
3681 * Related: Integer#allbits?, Integer#anybits?.
3686 int_nobits_p(VALUE num
, VALUE mask
)
3688 mask
= rb_to_int(mask
);
3689 return RBOOL(int_zero_p(rb_int_and(num
, mask
)));
3694 * succ -> next_integer
3696 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3701 * Related: Integer#pred (predecessor value).
3705 rb_int_succ(VALUE num
)
3707 if (FIXNUM_P(num
)) {
3708 long i
= FIX2LONG(num
) + 1;
3711 if (RB_BIGNUM_TYPE_P(num
)) {
3712 return rb_big_plus(num
, INT2FIX(1));
3714 return num_funcall1(num
, '+', INT2FIX(1));
3717 #define int_succ rb_int_succ
3721 * pred -> next_integer
3723 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3728 * Related: Integer#succ (successor value).
3733 rb_int_pred(VALUE num
)
3735 if (FIXNUM_P(num
)) {
3736 long i
= FIX2LONG(num
) - 1;
3739 if (RB_BIGNUM_TYPE_P(num
)) {
3740 return rb_big_minus(num
, INT2FIX(1));
3742 return num_funcall1(num
, '-', INT2FIX(1));
3745 #define int_pred rb_int_pred
3748 rb_enc_uint_chr(unsigned int code
, rb_encoding
*enc
)
3752 switch (n
= rb_enc_codelen(code
, enc
)) {
3753 case ONIGERR_INVALID_CODE_POINT_VALUE
:
3754 rb_raise(rb_eRangeError
, "invalid codepoint 0x%X in %s", code
, rb_enc_name(enc
));
3756 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE
:
3758 rb_raise(rb_eRangeError
, "%u out of char range", code
);
3761 str
= rb_enc_str_new(0, n
, enc
);
3762 rb_enc_mbcput(code
, RSTRING_PTR(str
), enc
);
3763 if (rb_enc_precise_mbclen(RSTRING_PTR(str
), RSTRING_END(str
), enc
) != n
) {
3764 rb_raise(rb_eRangeError
, "invalid codepoint 0x%X in %s", code
, rb_enc_name(enc
));
3771 * chr(encoding) -> string
3773 * Returns a 1-character string containing the character
3774 * represented by the value of +self+, according to the given +encoding+.
3778 * 255.chr # => "\xFF"
3779 * string = 255.chr(Encoding::UTF_8)
3780 * string.encoding # => Encoding::UTF_8
3782 * Raises an exception if +self+ is negative.
3784 * Related: Integer#ord.
3789 int_chr(int argc
, VALUE
*argv
, VALUE num
)
3795 if (rb_num_to_uint(num
, &i
) == 0) {
3797 else if (FIXNUM_P(num
)) {
3798 rb_raise(rb_eRangeError
, "%ld out of char range", FIX2LONG(num
));
3801 rb_raise(rb_eRangeError
, "bignum out of char range");
3807 enc
= rb_default_internal_encoding();
3809 rb_raise(rb_eRangeError
, "%u out of char range", i
);
3815 return rb_usascii_str_new(&c
, 1);
3818 return rb_str_new(&c
, 1);
3823 rb_error_arity(argc
, 0, 1);
3825 enc
= rb_to_encoding(argv
[0]);
3826 if (!enc
) enc
= rb_ascii8bit_encoding();
3828 return rb_enc_uint_chr(i
, enc
);
3836 fix_uminus(VALUE num
)
3838 return LONG2NUM(-FIX2LONG(num
));
3842 rb_int_uminus(VALUE num
)
3844 if (FIXNUM_P(num
)) {
3845 return fix_uminus(num
);
3848 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3849 return rb_big_uminus(num
);
3854 rb_fix2str(VALUE x
, int base
)
3856 char buf
[SIZEOF_VALUE
*CHAR_BIT
+ 1], *const e
= buf
+ sizeof buf
, *b
= e
;
3857 long val
= FIX2LONG(x
);
3861 if (base
< 2 || 36 < base
) {
3862 rb_raise(rb_eArgError
, "invalid radix %d", base
);
3864 #if SIZEOF_LONG < SIZEOF_VOIDP
3865 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3866 if ((val
>= 0 && (x
& 0xFFFFFFFF00000000ull
)) ||
3867 (val
< 0 && (x
& 0xFFFFFFFF00000000ull
) != 0xFFFFFFFF00000000ull
)) {
3868 rb_bug("Unnormalized Fixnum value %p", (void *)x
);
3871 /* should do something like above code, but currently ruby does not know */
3872 /* such platforms */
3876 return rb_usascii_str_new2("0");
3879 u
= 1 + (unsigned long)(-(val
+ 1)); /* u = -val avoiding overflow */
3886 *--b
= ruby_digitmap
[(int)(u
% base
)];
3887 } while (u
/= base
);
3892 return rb_usascii_str_new(b
, e
- b
);
3895 static VALUE rb_fix_to_s_static
[10];
3898 rb_fix_to_s(VALUE x
)
3900 long i
= FIX2LONG(x
);
3901 if (i
>= 0 && i
< 10) {
3902 return rb_fix_to_s_static
[i
];
3904 return rb_fix2str(x
, 10);
3909 * to_s(base = 10) -> string
3911 * Returns a string containing the place-value representation of +self+
3912 * in radix +base+ (in 2..36).
3914 * 12345.to_s # => "12345"
3915 * 12345.to_s(2) # => "11000000111001"
3916 * 12345.to_s(8) # => "30071"
3917 * 12345.to_s(10) # => "12345"
3918 * 12345.to_s(16) # => "3039"
3919 * 12345.to_s(36) # => "9ix"
3920 * 78546939656932.to_s(36) # => "rubyrules"
3922 * Raises an exception if +base+ is out of range.
3926 rb_int_to_s(int argc
, VALUE
*argv
, VALUE x
)
3930 if (rb_check_arity(argc
, 0, 1))
3931 base
= NUM2INT(argv
[0]);
3934 return rb_int2str(x
, base
);
3938 rb_int2str(VALUE x
, int base
)
3941 return rb_fix2str(x
, base
);
3943 else if (RB_BIGNUM_TYPE_P(x
)) {
3944 return rb_big2str(x
, base
);
3947 return rb_any_to_s(x
);
3951 fix_plus(VALUE x
, VALUE y
)
3954 return rb_fix_plus_fix(x
, y
);
3956 else if (RB_BIGNUM_TYPE_P(y
)) {
3957 return rb_big_plus(y
, x
);
3959 else if (RB_FLOAT_TYPE_P(y
)) {
3960 return DBL2NUM((double)FIX2LONG(x
) + RFLOAT_VALUE(y
));
3962 else if (RB_TYPE_P(y
, T_COMPLEX
)) {
3963 return rb_complex_plus(y
, x
);
3966 return rb_num_coerce_bin(x
, y
, '+');
3971 rb_fix_plus(VALUE x
, VALUE y
)
3973 return fix_plus(x
, y
);
3978 * self + numeric -> numeric_result
3980 * Performs addition:
3986 * 2 + Rational(2, 1) # => (4/1)
3987 * 2 + Complex(2, 0) # => (4+0i)
3992 rb_int_plus(VALUE x
, VALUE y
)
3995 return fix_plus(x
, y
);
3997 else if (RB_BIGNUM_TYPE_P(x
)) {
3998 return rb_big_plus(x
, y
);
4000 return rb_num_coerce_bin(x
, y
, '+');
4004 fix_minus(VALUE x
, VALUE y
)
4007 return rb_fix_minus_fix(x
, y
);
4009 else if (RB_BIGNUM_TYPE_P(y
)) {
4010 x
= rb_int2big(FIX2LONG(x
));
4011 return rb_big_minus(x
, y
);
4013 else if (RB_FLOAT_TYPE_P(y
)) {
4014 return DBL2NUM((double)FIX2LONG(x
) - RFLOAT_VALUE(y
));
4017 return rb_num_coerce_bin(x
, y
, '-');
4023 * self - numeric -> numeric_result
4025 * Performs subtraction:
4031 * 4 - Rational(2, 1) # => (2/1)
4032 * 4 - Complex(2, 0) # => (2+0i)
4037 rb_int_minus(VALUE x
, VALUE y
)
4040 return fix_minus(x
, y
);
4042 else if (RB_BIGNUM_TYPE_P(x
)) {
4043 return rb_big_minus(x
, y
);
4045 return rb_num_coerce_bin(x
, y
, '-');
4049 #define SQRT_LONG_MAX HALF_LONG_MSB
4050 /*tests if N*N would overflow*/
4051 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4054 fix_mul(VALUE x
, VALUE y
)
4057 return rb_fix_mul_fix(x
, y
);
4059 else if (RB_BIGNUM_TYPE_P(y
)) {
4061 case INT2FIX(0): return x
;
4062 case INT2FIX(1): return y
;
4064 return rb_big_mul(y
, x
);
4066 else if (RB_FLOAT_TYPE_P(y
)) {
4067 return DBL2NUM((double)FIX2LONG(x
) * RFLOAT_VALUE(y
));
4069 else if (RB_TYPE_P(y
, T_COMPLEX
)) {
4070 return rb_complex_mul(y
, x
);
4073 return rb_num_coerce_bin(x
, y
, '*');
4079 * self * numeric -> numeric_result
4081 * Performs multiplication:
4087 * 4 * Rational(1, 3) # => (4/3)
4088 * 4 * Complex(2, 0) # => (8+0i)
4092 rb_int_mul(VALUE x
, VALUE y
)
4095 return fix_mul(x
, y
);
4097 else if (RB_BIGNUM_TYPE_P(x
)) {
4098 return rb_big_mul(x
, y
);
4100 return rb_num_coerce_bin(x
, y
, '*');
4104 fix_fdiv_double(VALUE x
, VALUE y
)
4107 long iy
= FIX2LONG(y
);
4108 #if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4109 if ((iy
< 0 ? -iy
: iy
) >= (1L << DBL_MANT_DIG
)) {
4110 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x
)), rb_int2big(iy
));
4113 return double_div_double(FIX2LONG(x
), iy
);
4115 else if (RB_BIGNUM_TYPE_P(y
)) {
4116 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x
)), y
);
4118 else if (RB_FLOAT_TYPE_P(y
)) {
4119 return double_div_double(FIX2LONG(x
), RFLOAT_VALUE(y
));
4122 return NUM2DBL(rb_num_coerce_bin(x
, y
, idFdiv
));
4127 rb_int_fdiv_double(VALUE x
, VALUE y
)
4129 if (RB_INTEGER_TYPE_P(y
) && !FIXNUM_ZERO_P(y
)) {
4130 VALUE gcd
= rb_gcd(x
, y
);
4131 if (!FIXNUM_ZERO_P(gcd
) && gcd
!= INT2FIX(1)) {
4132 x
= rb_int_idiv(x
, gcd
);
4133 y
= rb_int_idiv(y
, gcd
);
4137 return fix_fdiv_double(x
, y
);
4139 else if (RB_BIGNUM_TYPE_P(x
)) {
4140 return rb_big_fdiv_double(x
, y
);
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.
4164 rb_int_fdiv(VALUE x
, VALUE y
)
4166 if (RB_INTEGER_TYPE_P(x
)) {
4167 return DBL2NUM(rb_int_fdiv_double(x
, y
));
4173 fix_divide(VALUE x
, VALUE y
, ID op
)
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
)) {
4185 double d
= FIX2LONG(x
);
4186 return rb_flo_div_flo(DBL2NUM(d
), y
);
4190 if (RFLOAT_VALUE(y
) == 0) rb_num_zerodiv();
4191 v
= fix_divide(x
, y
, '/');
4192 return flo_floor(0, 0, v
);
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
);
4204 fix_div(VALUE x
, VALUE y
)
4206 return fix_divide(x
, y
, '/');
4211 * self / numeric -> numeric_result
4213 * Performs division; for integer +numeric+, truncates the result to an integer:
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)
4229 rb_int_div(VALUE x
, VALUE y
)
4232 return fix_div(x
, y
);
4234 else if (RB_BIGNUM_TYPE_P(x
)) {
4235 return rb_big_div(x
, y
);
4241 fix_idiv(VALUE x
, VALUE y
)
4243 return fix_divide(x
, y
, id_div
);
4248 * div(numeric) -> integer
4250 * Performs integer division; returns the integer result of dividing +self+
4258 * 4.div(Rational(3, 1)) # => 1
4260 * Raises an exception if +numeric+ does not have method +div+.
4265 rb_int_idiv(VALUE x
, VALUE y
)
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
);
4277 fix_mod(VALUE x
, VALUE 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
)));
4291 return rb_num_coerce_bin(x
, y
, '%');
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:
4307 * See Numeric#divmod.
4320 * 10 % Rational(3, 1) # => (1/1)
4324 rb_int_modulo(VALUE x
, VALUE y
)
4327 return fix_mod(x
, y
);
4329 else if (RB_BIGNUM_TYPE_P(x
)) {
4330 return rb_big_modulo(x
, y
);
4332 return num_modulo(x
, y
);
4337 * remainder(other) -> real_number
4339 * Returns the remainder after dividing +self+ by +other+.
4343 * 11.remainder(4) # => 3
4344 * 11.remainder(-4) # => 3
4345 * -11.remainder(4) # => -3
4346 * -11.remainder(-4) # => -3
4348 * 12.remainder(4) # => 0
4349 * 12.remainder(-4) # => 0
4350 * -12.remainder(4) # => 0
4351 * -12.remainder(-4) # => 0
4353 * 13.remainder(4.0) # => 1.0
4354 * 13.remainder(Rational(4, 1)) # => (1/1)
4359 int_remainder(VALUE x
, VALUE y
)
4363 VALUE z
= fix_mod(x
, y
);
4364 RUBY_ASSERT(FIXNUM_P(z
));
4365 if (z
!= INT2FIX(0) && (SIGNED_VALUE
)(x
^ y
) < 0)
4366 z
= fix_minus(z
, y
);
4369 else if (!RB_BIGNUM_TYPE_P(y
)) {
4370 return num_remainder(x
, y
);
4372 x
= rb_int2big(FIX2LONG(x
));
4374 else if (!RB_BIGNUM_TYPE_P(x
)) {
4377 return rb_big_remainder(x
, y
);
4381 fix_divmod(VALUE x
, VALUE y
)
4385 if (FIXNUM_ZERO_P(y
)) rb_num_zerodiv();
4386 rb_fix_divmod_fix(x
, y
, &div
, &mod
);
4387 return rb_assoc_new(div
, mod
);
4389 else if (RB_BIGNUM_TYPE_P(y
)) {
4390 x
= rb_int2big(FIX2LONG(x
));
4391 return rb_big_divmod(x
, y
);
4393 else if (RB_FLOAT_TYPE_P(y
)) {
4396 volatile VALUE a
, b
;
4398 flodivmod((double)FIX2LONG(x
), RFLOAT_VALUE(y
), &div
, &mod
);
4401 return rb_assoc_new(a
, b
);
4405 return rb_num_coerce_bin(x
, y
, id_divmod
);
4411 * divmod(other) -> array
4413 * Returns a 2-element array <tt>[q, r]</tt>, where
4415 * q = (self/other).floor # Quotient
4416 * r = self % other # Remainder
4420 * 11.divmod(4) # => [2, 3]
4421 * 11.divmod(-4) # => [-3, -1]
4422 * -11.divmod(4) # => [-3, 1]
4423 * -11.divmod(-4) # => [2, -3]
4425 * 12.divmod(4) # => [3, 0]
4426 * 12.divmod(-4) # => [-3, 0]
4427 * -12.divmod(4) # => [-3, 0]
4428 * -12.divmod(-4) # => [3, 0]
4430 * 13.divmod(4.0) # => [3, 1.0]
4431 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4435 rb_int_divmod(VALUE x
, VALUE y
)
4438 return fix_divmod(x
, y
);
4440 else if (RB_BIGNUM_TYPE_P(x
)) {
4441 return rb_big_divmod(x
, y
);
4448 * self ** numeric -> numeric_result
4450 * Raises +self+ to the power of +numeric+:
4453 * 2 ** -3 # => (1/8)
4455 * -2 ** -3 # => (-1/8)
4456 * 2 ** 3.3 # => 9.849155306759329
4457 * 2 ** Rational(3, 1) # => (8/1)
4458 * 2 ** Complex(3, 0) # => (8+0i)
4463 int_pow(long x
, unsigned long y
)
4468 if (y
== 0) return INT2FIX(1);
4469 if (y
== 1) return LONG2NUM(x
);
4477 while (y
% 2 == 0) {
4478 if (!FIT_SQRT_LONG(x
)) {
4485 if (MUL_OVERFLOW_FIXNUM_P(x
, z
)) {
4496 v
= rb_big_pow(rb_int2big(x
), LONG2NUM(y
));
4497 if (RB_FLOAT_TYPE_P(v
)) /* infinity due to overflow */
4499 if (z
!= 1) v
= rb_big_mul(rb_int2big(neg
? -z
: z
), v
);
4504 rb_int_positive_pow(long x
, unsigned long y
)
4506 return int_pow(x
, y
);
4510 fix_pow_inverted(VALUE x
, VALUE minusb
)
4512 if (x
== INT2FIX(0)) {
4514 UNREACHABLE_RETURN(Qundef
);
4517 VALUE y
= rb_int_pow(x
, minusb
);
4519 if (RB_FLOAT_TYPE_P(y
)) {
4520 double d
= pow((double)FIX2LONG(x
), RFLOAT_VALUE(y
));
4521 return DBL2NUM(1.0 / d
);
4524 return rb_rational_raw(INT2FIX(1), y
);
4530 fix_pow(VALUE x
, VALUE y
)
4532 long a
= FIX2LONG(x
);
4535 long b
= FIX2LONG(y
);
4537 if (a
== 1) return INT2FIX(1);
4538 if (a
== -1) return INT2FIX(b
% 2 ? -1 : 1);
4539 if (b
< 0) return fix_pow_inverted(x
, fix_uminus(y
));
4540 if (b
== 0) return INT2FIX(1);
4541 if (b
== 1) return x
;
4542 if (a
== 0) return INT2FIX(0);
4543 return int_pow(a
, b
);
4545 else if (RB_BIGNUM_TYPE_P(y
)) {
4546 if (a
== 1) return INT2FIX(1);
4547 if (a
== -1) return INT2FIX(int_even_p(y
) ? 1 : -1);
4548 if (BIGNUM_NEGATIVE_P(y
)) return fix_pow_inverted(x
, rb_big_uminus(y
));
4549 if (a
== 0) return INT2FIX(0);
4550 x
= rb_int2big(FIX2LONG(x
));
4551 return rb_big_pow(x
, y
);
4553 else if (RB_FLOAT_TYPE_P(y
)) {
4554 double dy
= RFLOAT_VALUE(y
);
4555 if (dy
== 0.0) return DBL2NUM(1.0);
4557 return DBL2NUM(dy
< 0 ? HUGE_VAL
: 0.0);
4559 if (a
== 1) return DBL2NUM(1.0);
4560 if (a
< 0 && dy
!= round(dy
))
4561 return rb_dbl_complex_new_polar_pi(pow(-(double)a
, dy
), dy
);
4562 return DBL2NUM(pow((double)a
, dy
));
4565 return rb_num_coerce_bin(x
, y
, idPow
);
4571 * self ** numeric -> numeric_result
4573 * Raises +self+ to the power of +numeric+:
4576 * 2 ** -3 # => (1/8)
4578 * -2 ** -3 # => (-1/8)
4579 * 2 ** 3.3 # => 9.849155306759329
4580 * 2 ** Rational(3, 1) # => (8/1)
4581 * 2 ** Complex(3, 0) # => (8+0i)
4585 rb_int_pow(VALUE x
, VALUE y
)
4588 return fix_pow(x
, y
);
4590 else if (RB_BIGNUM_TYPE_P(x
)) {
4591 return rb_big_pow(x
, y
);
4597 rb_num_pow(VALUE x
, VALUE y
)
4599 VALUE z
= rb_int_pow(x
, y
);
4600 if (!NIL_P(z
)) return z
;
4601 if (RB_FLOAT_TYPE_P(x
)) return rb_float_pow(x
, y
);
4602 if (SPECIAL_CONST_P(x
)) return Qnil
;
4603 switch (BUILTIN_TYPE(x
)) {
4605 return rb_complex_pow(x
, y
);
4607 return rb_rational_pow(x
, y
);
4615 fix_equal(VALUE x
, VALUE y
)
4617 if (x
== y
) return Qtrue
;
4618 if (FIXNUM_P(y
)) return Qfalse
;
4619 else if (RB_BIGNUM_TYPE_P(y
)) {
4620 return rb_big_eq(y
, x
);
4622 else if (RB_FLOAT_TYPE_P(y
)) {
4623 return rb_integer_float_eq(x
, y
);
4626 return num_equal(x
, y
);
4632 * self == other -> true or false
4634 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4639 * Related: Integer#eql? (requires +other+ to be an \Integer).
4643 rb_int_equal(VALUE x
, VALUE y
)
4646 return fix_equal(x
, y
);
4648 else if (RB_BIGNUM_TYPE_P(x
)) {
4649 return rb_big_eq(x
, y
);
4655 fix_cmp(VALUE x
, VALUE y
)
4657 if (x
== y
) return INT2FIX(0);
4659 if (FIX2LONG(x
) > FIX2LONG(y
)) return INT2FIX(1);
4662 else if (RB_BIGNUM_TYPE_P(y
)) {
4663 VALUE cmp
= rb_big_cmp(y
, x
);
4665 case INT2FIX(+1): return INT2FIX(-1);
4666 case INT2FIX(-1): return INT2FIX(+1);
4670 else if (RB_FLOAT_TYPE_P(y
)) {
4671 return rb_integer_float_cmp(x
, y
);
4674 return rb_num_coerce_cmp(x
, y
, id_cmp
);
4680 * self <=> other -> -1, 0, +1, or nil
4684 * - -1, if +self+ is less than +other+.
4685 * - 0, if +self+ is equal to +other+.
4686 * - 1, if +self+ is greater then +other+.
4687 * - +nil+, if +self+ and +other+ are incomparable.
4694 * 1 <=> 'foo' # => nil
4697 * 1 <=> Rational(1, 1) # => 0
4698 * 1 <=> Complex(1, 0) # => 0
4700 * This method is the basis for comparisons in module Comparable.
4705 rb_int_cmp(VALUE x
, VALUE y
)
4708 return fix_cmp(x
, y
);
4710 else if (RB_BIGNUM_TYPE_P(x
)) {
4711 return rb_big_cmp(x
, y
);
4714 rb_raise(rb_eNotImpError
, "need to define '<=>' in %s", rb_obj_classname(x
));
4719 fix_gt(VALUE x
, VALUE y
)
4722 return RBOOL(FIX2LONG(x
) > FIX2LONG(y
));
4724 else if (RB_BIGNUM_TYPE_P(y
)) {
4725 return RBOOL(rb_big_cmp(y
, x
) == INT2FIX(-1));
4727 else if (RB_FLOAT_TYPE_P(y
)) {
4728 return RBOOL(rb_integer_float_cmp(x
, y
) == INT2FIX(1));
4731 return rb_num_coerce_relop(x
, y
, '>');
4737 * self > other -> true or false
4739 * Returns +true+ if the value of +self+ is greater than that of +other+:
4745 * 1 > Rational(1, 2) # => true
4747 * Raises an exception if the comparison cannot be made.
4752 rb_int_gt(VALUE x
, VALUE y
)
4755 return fix_gt(x
, y
);
4757 else if (RB_BIGNUM_TYPE_P(x
)) {
4758 return rb_big_gt(x
, y
);
4764 fix_ge(VALUE x
, VALUE y
)
4767 return RBOOL(FIX2LONG(x
) >= FIX2LONG(y
));
4769 else if (RB_BIGNUM_TYPE_P(y
)) {
4770 return RBOOL(rb_big_cmp(y
, x
) != INT2FIX(+1));
4772 else if (RB_FLOAT_TYPE_P(y
)) {
4773 VALUE rel
= rb_integer_float_cmp(x
, y
);
4774 return RBOOL(rel
== INT2FIX(1) || rel
== INT2FIX(0));
4777 return rb_num_coerce_relop(x
, y
, idGE
);
4783 * self >= real -> true or false
4785 * Returns +true+ if the value of +self+ is greater than or equal to
4791 * 1 >= 0.5 # => true
4792 * 1 >= Rational(1, 2) # => true
4794 * Raises an exception if the comparison cannot be made.
4799 rb_int_ge(VALUE x
, VALUE y
)
4802 return fix_ge(x
, y
);
4804 else if (RB_BIGNUM_TYPE_P(x
)) {
4805 return rb_big_ge(x
, y
);
4811 fix_lt(VALUE x
, VALUE y
)
4814 return RBOOL(FIX2LONG(x
) < FIX2LONG(y
));
4816 else if (RB_BIGNUM_TYPE_P(y
)) {
4817 return RBOOL(rb_big_cmp(y
, x
) == INT2FIX(+1));
4819 else if (RB_FLOAT_TYPE_P(y
)) {
4820 return RBOOL(rb_integer_float_cmp(x
, y
) == INT2FIX(-1));
4823 return rb_num_coerce_relop(x
, y
, '<');
4829 * self < other -> true or false
4831 * Returns +true+ if the value of +self+ is less than that of +other+:
4836 * 1 < 0.5 # => false
4837 * 1 < Rational(1, 2) # => false
4839 * Raises an exception if the comparison cannot be made.
4844 int_lt(VALUE x
, VALUE y
)
4847 return fix_lt(x
, y
);
4849 else if (RB_BIGNUM_TYPE_P(x
)) {
4850 return rb_big_lt(x
, y
);
4856 fix_le(VALUE x
, VALUE y
)
4859 return RBOOL(FIX2LONG(x
) <= FIX2LONG(y
));
4861 else if (RB_BIGNUM_TYPE_P(y
)) {
4862 return RBOOL(rb_big_cmp(y
, x
) != INT2FIX(-1));
4864 else if (RB_FLOAT_TYPE_P(y
)) {
4865 VALUE rel
= rb_integer_float_cmp(x
, y
);
4866 return RBOOL(rel
== INT2FIX(-1) || rel
== INT2FIX(0));
4869 return rb_num_coerce_relop(x
, y
, idLE
);
4875 * self <= real -> true or false
4877 * Returns +true+ if the value of +self+ is less than or equal to
4883 * 1 <= 0.5 # => false
4884 * 1 <= Rational(1, 2) # => false
4886 * Raises an exception if the comparison cannot be made.
4891 int_le(VALUE x
, VALUE y
)
4894 return fix_le(x
, y
);
4896 else if (RB_BIGNUM_TYPE_P(x
)) {
4897 return rb_big_le(x
, y
);
4905 return ~num
| FIXNUM_FLAG
;
4909 rb_int_comp(VALUE num
)
4911 if (FIXNUM_P(num
)) {
4912 return fix_comp(num
);
4914 else if (RB_BIGNUM_TYPE_P(num
)) {
4915 return rb_big_comp(num
);
4921 num_funcall_bit_1(VALUE y
, VALUE arg
, int recursive
)
4923 ID func
= (ID
)((VALUE
*)arg
)[0];
4924 VALUE x
= ((VALUE
*)arg
)[1];
4926 num_funcall_op_1_recursion(x
, func
, y
);
4928 return rb_check_funcall(x
, func
, 1, &y
);
4932 rb_num_coerce_bit(VALUE x
, VALUE y
, ID func
)
4936 args
[0] = (VALUE
)func
;
4939 do_coerce(&args
[1], &args
[2], TRUE
);
4940 ret
= rb_exec_recursive_paired(num_funcall_bit_1
,
4941 args
[2], args
[1], (VALUE
)args
);
4943 /* show the original object, not coerced object */
4944 coerce_failed(x
, y
);
4950 fix_and(VALUE x
, VALUE y
)
4953 long val
= FIX2LONG(x
) & FIX2LONG(y
);
4954 return LONG2NUM(val
);
4957 if (RB_BIGNUM_TYPE_P(y
)) {
4958 return rb_big_and(y
, x
);
4961 return rb_num_coerce_bit(x
, y
, '&');
4966 * self & other -> integer
4968 * Bitwise AND; each bit in the result is 1 if both corresponding bits
4969 * in +self+ and +other+ are 1, 0 otherwise:
4971 * "%04b" % (0b0101 & 0b0110) # => "0100"
4973 * Raises an exception if +other+ is not an \Integer.
4975 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
4980 rb_int_and(VALUE x
, VALUE y
)
4983 return fix_and(x
, y
);
4985 else if (RB_BIGNUM_TYPE_P(x
)) {
4986 return rb_big_and(x
, y
);
4992 fix_or(VALUE x
, VALUE y
)
4995 long val
= FIX2LONG(x
) | FIX2LONG(y
);
4996 return LONG2NUM(val
);
4999 if (RB_BIGNUM_TYPE_P(y
)) {
5000 return rb_big_or(y
, x
);
5003 return rb_num_coerce_bit(x
, y
, '|');
5008 * self | other -> integer
5010 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5011 * in +self+ or +other+ is 1, 0 otherwise:
5013 * "%04b" % (0b0101 | 0b0110) # => "0111"
5015 * Raises an exception if +other+ is not an \Integer.
5017 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5022 int_or(VALUE x
, VALUE y
)
5025 return fix_or(x
, y
);
5027 else if (RB_BIGNUM_TYPE_P(x
)) {
5028 return rb_big_or(x
, y
);
5034 fix_xor(VALUE x
, VALUE y
)
5037 long val
= FIX2LONG(x
) ^ FIX2LONG(y
);
5038 return LONG2NUM(val
);
5041 if (RB_BIGNUM_TYPE_P(y
)) {
5042 return rb_big_xor(y
, x
);
5045 return rb_num_coerce_bit(x
, y
, '^');
5050 * self ^ other -> integer
5052 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5053 * in +self+ and +other+ are different, 0 otherwise:
5055 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5057 * Raises an exception if +other+ is not an \Integer.
5059 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5064 int_xor(VALUE x
, VALUE y
)
5067 return fix_xor(x
, y
);
5069 else if (RB_BIGNUM_TYPE_P(x
)) {
5070 return rb_big_xor(x
, y
);
5076 rb_fix_lshift(VALUE x
, VALUE y
)
5081 if (!val
) return (rb_to_int(y
), INT2FIX(0));
5083 return rb_big_lshift(rb_int2big(val
), y
);
5084 width
= FIX2LONG(y
);
5086 return fix_rshift(val
, (unsigned long)-width
);
5087 return fix_lshift(val
, width
);
5091 fix_lshift(long val
, unsigned long width
)
5093 if (width
> (SIZEOF_LONG
*CHAR_BIT
-1)
5094 || ((unsigned long)val
)>>(SIZEOF_LONG
*CHAR_BIT
-1-width
) > 0) {
5095 return rb_big_lshift(rb_int2big(val
), ULONG2NUM(width
));
5098 return LONG2NUM(val
);
5103 * self << count -> integer
5105 * Returns +self+ with bits shifted +count+ positions to the left,
5106 * or to the right if +count+ is negative:
5109 * "%08b" % (n << 1) # => "111100000"
5110 * "%08b" % (n << 3) # => "11110000000"
5111 * "%08b" % (n << -1) # => "01111000"
5112 * "%08b" % (n << -3) # => "00011110"
5114 * Related: Integer#>>.
5119 rb_int_lshift(VALUE x
, VALUE y
)
5122 return rb_fix_lshift(x
, y
);
5124 else if (RB_BIGNUM_TYPE_P(x
)) {
5125 return rb_big_lshift(x
, y
);
5131 rb_fix_rshift(VALUE x
, VALUE y
)
5136 if (!val
) return (rb_to_int(y
), INT2FIX(0));
5138 return rb_big_rshift(rb_int2big(val
), y
);
5140 if (i
== 0) return x
;
5142 return fix_lshift(val
, (unsigned long)-i
);
5143 return fix_rshift(val
, i
);
5147 fix_rshift(long val
, unsigned long i
)
5149 if (i
>= sizeof(long)*CHAR_BIT
-1) {
5150 if (val
< 0) return INT2FIX(-1);
5153 val
= RSHIFT(val
, i
);
5154 return LONG2FIX(val
);
5159 * self >> count -> integer
5161 * Returns +self+ with bits shifted +count+ positions to the right,
5162 * or to the left if +count+ is negative:
5165 * "%08b" % (n >> 1) # => "01111000"
5166 * "%08b" % (n >> 3) # => "00011110"
5167 * "%08b" % (n >> -1) # => "111100000"
5168 * "%08b" % (n >> -3) # => "11110000000"
5170 * Related: Integer#<<.
5175 rb_int_rshift(VALUE x
, VALUE y
)
5178 return rb_fix_rshift(x
, y
);
5180 else if (RB_BIGNUM_TYPE_P(x
)) {
5181 return rb_big_rshift(x
, y
);
5187 rb_fix_aref(VALUE fix
, VALUE idx
)
5189 long val
= FIX2LONG(fix
);
5192 idx
= rb_to_int(idx
);
5193 if (!FIXNUM_P(idx
)) {
5194 idx
= rb_big_norm(idx
);
5195 if (!FIXNUM_P(idx
)) {
5196 if (!BIGNUM_SIGN(idx
) || val
>= 0)
5203 if (i
< 0) return INT2FIX(0);
5204 if (SIZEOF_LONG
*CHAR_BIT
-1 <= i
) {
5205 if (val
< 0) return INT2FIX(1);
5214 /* copied from "r_less" in range.c */
5215 /* compares _a_ and _b_ and returns:
5218 * > 0: a > b or non-comparable
5221 compare_indexes(VALUE a
, VALUE b
)
5223 VALUE r
= rb_funcall(a
, id_cmp
, 1, b
);
5227 return rb_cmpint(r
, a
, b
);
5231 generate_mask(VALUE len
)
5233 return rb_int_minus(rb_int_lshift(INT2FIX(1), len
), INT2FIX(1));
5237 int_aref1(VALUE num
, VALUE arg
)
5239 VALUE orig_num
= num
, beg
, end
;
5242 if (rb_range_values(arg
, &beg
, &end
, &excl
)) {
5244 /* beginless range */
5245 if (!RTEST(num_negative_p(end
))) {
5246 if (!excl
) end
= rb_int_plus(end
, INT2FIX(1));
5247 VALUE mask
= generate_mask(end
);
5248 if (int_zero_p(rb_int_and(num
, mask
))) {
5252 rb_raise(rb_eArgError
, "The beginless range for Integer#[] results in infinity");
5259 num
= rb_int_rshift(num
, beg
);
5261 int cmp
= compare_indexes(beg
, end
);
5262 if (!NIL_P(end
) && cmp
< 0) {
5263 VALUE len
= rb_int_minus(end
, beg
);
5264 if (!excl
) len
= rb_int_plus(len
, INT2FIX(1));
5265 VALUE mask
= generate_mask(len
);
5266 num
= rb_int_and(num
, mask
);
5268 else if (cmp
== 0) {
5269 if (excl
) return INT2FIX(0);
5278 if (FIXNUM_P(num
)) {
5279 return rb_fix_aref(num
, arg
);
5281 else if (RB_BIGNUM_TYPE_P(num
)) {
5282 return rb_big_aref(num
, arg
);
5288 int_aref2(VALUE num
, VALUE beg
, VALUE len
)
5290 num
= rb_int_rshift(num
, beg
);
5291 VALUE mask
= generate_mask(len
);
5292 num
= rb_int_and(num
, mask
);
5298 * self[offset] -> 0 or 1
5299 * self[offset, size] -> integer
5300 * self[range] -> integer
5302 * Returns a slice of bits from +self+.
5304 * With argument +offset+, returns the bit at the given offset,
5305 * where offset 0 refers to the least significant bit:
5313 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5314 * Thus, negative index always returns zero:
5318 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5319 * beginning at +offset+ and including bits of greater significance:
5321 * n = 0b111000 # => 56
5322 * "%010b" % n[0, 10] # => "0000111000"
5323 * "%010b" % n[4, 10] # => "0000000011"
5325 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5326 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5328 * n = 0b111000 # => 56
5329 * "%010b" % n[0..9] # => "0000111000"
5330 * "%010b" % n[4..9] # => "0000000011"
5332 * Raises an exception if the slice cannot be constructed.
5336 int_aref(int const argc
, VALUE
* const argv
, VALUE
const num
)
5338 rb_check_arity(argc
, 1, 2);
5340 return int_aref2(num
, argv
[0], argv
[1]);
5342 return int_aref1(num
, argv
[0]);
5351 * Converts +self+ to a Float:
5356 * If the value of +self+ does not fit in a Float,
5357 * the result is infinity:
5359 * (10**400).to_f # => Infinity
5360 * (-10**400).to_f # => -Infinity
5369 if (FIXNUM_P(num
)) {
5370 val
= (double)FIX2LONG(num
);
5372 else if (RB_BIGNUM_TYPE_P(num
)) {
5373 val
= rb_big2dbl(num
);
5376 rb_raise(rb_eNotImpError
, "Unknown subclass for to_f: %s", rb_obj_classname(num
));
5379 return DBL2NUM(val
);
5385 long i
= FIX2LONG(fix
);
5393 rb_int_abs(VALUE num
)
5395 if (FIXNUM_P(num
)) {
5396 return fix_abs(num
);
5398 else if (RB_BIGNUM_TYPE_P(num
)) {
5399 return rb_big_abs(num
);
5407 return INT2FIX(sizeof(long));
5411 rb_int_size(VALUE num
)
5413 if (FIXNUM_P(num
)) {
5414 return fix_size(num
);
5416 else if (RB_BIGNUM_TYPE_P(num
)) {
5417 return rb_big_size_m(num
);
5423 rb_fix_bit_length(VALUE fix
)
5425 long v
= FIX2LONG(fix
);
5428 return LONG2FIX(bit_length(v
));
5432 rb_int_bit_length(VALUE num
)
5434 if (FIXNUM_P(num
)) {
5435 return rb_fix_bit_length(num
);
5437 else if (RB_BIGNUM_TYPE_P(num
)) {
5438 return rb_big_bit_length(num
);
5444 rb_fix_digits(VALUE fix
, long base
)
5447 long x
= FIX2LONG(fix
);
5449 RUBY_ASSERT(x
>= 0);
5452 rb_raise(rb_eArgError
, "invalid radix %ld", base
);
5455 return rb_ary_new_from_args(1, INT2FIX(0));
5457 digits
= rb_ary_new();
5460 rb_ary_push(digits
, LONG2NUM(q
));
5463 rb_ary_push(digits
, LONG2NUM(x
));
5469 rb_int_digits_bigbase(VALUE num
, VALUE base
)
5471 VALUE digits
, bases
;
5473 RUBY_ASSERT(!rb_num_negative_p(num
));
5475 if (RB_BIGNUM_TYPE_P(base
))
5476 base
= rb_big_norm(base
);
5478 if (FIXNUM_P(base
) && FIX2LONG(base
) < 2)
5479 rb_raise(rb_eArgError
, "invalid radix %ld", FIX2LONG(base
));
5480 else if (RB_BIGNUM_TYPE_P(base
) && BIGNUM_NEGATIVE_P(base
))
5481 rb_raise(rb_eArgError
, "negative radix");
5483 if (FIXNUM_P(base
) && FIXNUM_P(num
))
5484 return rb_fix_digits(num
, FIX2LONG(base
));
5487 return rb_ary_new_from_args(1, num
);
5489 if (int_lt(rb_int_div(rb_int_bit_length(num
), rb_int_bit_length(base
)), INT2FIX(50))) {
5490 digits
= rb_ary_new();
5491 while (!FIXNUM_P(num
) || FIX2LONG(num
) > 0) {
5492 VALUE qr
= rb_int_divmod(num
, base
);
5493 rb_ary_push(digits
, RARRAY_AREF(qr
, 1));
5494 num
= RARRAY_AREF(qr
, 0);
5499 bases
= rb_ary_new();
5500 for (VALUE b
= base
; int_lt(b
, num
) == Qtrue
; b
= rb_int_mul(b
, b
)) {
5501 rb_ary_push(bases
, b
);
5503 digits
= rb_ary_new_from_args(1, num
);
5504 while (RARRAY_LEN(bases
)) {
5505 VALUE b
= rb_ary_pop(bases
);
5506 long i
, last_idx
= RARRAY_LEN(digits
) - 1;
5507 for(i
= last_idx
; i
>= 0; i
--) {
5508 VALUE n
= RARRAY_AREF(digits
, i
);
5509 VALUE divmod
= rb_int_divmod(n
, b
);
5510 VALUE div
= RARRAY_AREF(divmod
, 0);
5511 VALUE mod
= RARRAY_AREF(divmod
, 1);
5512 if (i
!= last_idx
|| div
!= INT2FIX(0)) rb_ary_store(digits
, 2 * i
+ 1, div
);
5513 rb_ary_store(digits
, 2 * i
, mod
);
5522 * digits(base = 10) -> array_of_integers
5524 * Returns an array of integers representing the +base+-radix
5526 * the first element of the array represents the least significant digit:
5528 * 12345.digits # => [5, 4, 3, 2, 1]
5529 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5530 * 12345.digits(100) # => [45, 23, 1]
5532 * Raises an exception if +self+ is negative or +base+ is less than 2.
5537 rb_int_digits(int argc
, VALUE
*argv
, VALUE num
)
5542 if (rb_num_negative_p(num
))
5543 rb_raise(rb_eMathDomainError
, "out of domain");
5545 if (rb_check_arity(argc
, 0, 1)) {
5546 base_value
= rb_to_int(argv
[0]);
5547 if (!RB_INTEGER_TYPE_P(base_value
))
5548 rb_raise(rb_eTypeError
, "wrong argument type %s (expected Integer)",
5549 rb_obj_classname(argv
[0]));
5550 if (RB_BIGNUM_TYPE_P(base_value
))
5551 return rb_int_digits_bigbase(num
, base_value
);
5553 base
= FIX2LONG(base_value
);
5555 rb_raise(rb_eArgError
, "negative radix");
5557 rb_raise(rb_eArgError
, "invalid radix %ld", base
);
5563 return rb_fix_digits(num
, base
);
5564 else if (RB_BIGNUM_TYPE_P(num
))
5565 return rb_int_digits_bigbase(num
, LONG2FIX(base
));
5571 int_upto_size(VALUE from
, VALUE args
, VALUE eobj
)
5573 return ruby_num_interval_step_size(from
, RARRAY_AREF(args
, 0), INT2FIX(1), FALSE
);
5578 * upto(limit) {|i| ... } -> self
5579 * upto(limit) -> enumerator
5581 * Calls the given block with each integer value from +self+ up to +limit+;
5585 * 5.upto(10) {|i| a << i } # => 5
5586 * a # => [5, 6, 7, 8, 9, 10]
5588 * -5.upto(0) {|i| a << i } # => -5
5589 * a # => [-5, -4, -3, -2, -1, 0]
5590 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5592 * With no block given, returns an Enumerator.
5597 int_upto(VALUE from
, VALUE to
)
5599 RETURN_SIZED_ENUMERATOR(from
, 1, &to
, int_upto_size
);
5600 if (FIXNUM_P(from
) && FIXNUM_P(to
)) {
5604 for (i
= FIX2LONG(from
); i
<= end
; i
++) {
5605 rb_yield(LONG2FIX(i
));
5611 while (!(c
= rb_funcall(i
, '>', 1, to
))) {
5613 i
= rb_funcall(i
, '+', 1, INT2FIX(1));
5615 ensure_cmp(c
, i
, to
);
5621 int_downto_size(VALUE from
, VALUE args
, VALUE eobj
)
5623 return ruby_num_interval_step_size(from
, RARRAY_AREF(args
, 0), INT2FIX(-1), FALSE
);
5628 * downto(limit) {|i| ... } -> self
5629 * downto(limit) -> enumerator
5631 * Calls the given block with each integer value from +self+ down to +limit+;
5635 * 10.downto(5) {|i| a << i } # => 10
5636 * a # => [10, 9, 8, 7, 6, 5]
5638 * 0.downto(-5) {|i| a << i } # => 0
5639 * a # => [0, -1, -2, -3, -4, -5]
5640 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5642 * With no block given, returns an Enumerator.
5647 int_downto(VALUE from
, VALUE to
)
5649 RETURN_SIZED_ENUMERATOR(from
, 1, &to
, int_downto_size
);
5650 if (FIXNUM_P(from
) && FIXNUM_P(to
)) {
5654 for (i
=FIX2LONG(from
); i
>= end
; i
--) {
5655 rb_yield(LONG2FIX(i
));
5661 while (!(c
= rb_funcall(i
, '<', 1, to
))) {
5663 i
= rb_funcall(i
, '-', 1, INT2FIX(1));
5665 if (NIL_P(c
)) rb_cmperr(i
, to
);
5671 int_dotimes_size(VALUE num
, VALUE args
, VALUE eobj
)
5673 return int_neg_p(num
) ? INT2FIX(0) : num
;
5678 * round(ndigits= 0, half: :up) -> integer
5680 * Returns +self+ rounded to the nearest value with
5681 * a precision of +ndigits+ decimal digits.
5683 * When +ndigits+ is negative, the returned value
5684 * has at least <tt>ndigits.abs</tt> trailing zeros:
5686 * 555.round(-1) # => 560
5687 * 555.round(-2) # => 600
5688 * 555.round(-3) # => 1000
5689 * -555.round(-2) # => -600
5690 * 555.round(-4) # => 0
5692 * Returns +self+ when +ndigits+ is zero or positive.
5694 * 555.round # => 555
5695 * 555.round(1) # => 555
5696 * 555.round(50) # => 555
5698 * If keyword argument +half+ is given,
5699 * and +self+ is equidistant from the two candidate values,
5700 * the rounding is according to the given +half+ value:
5702 * - +:up+ or +nil+: round away from zero:
5704 * 25.round(-1, half: :up) # => 30
5705 * (-25).round(-1, half: :up) # => -30
5707 * - +:down+: round toward zero:
5709 * 25.round(-1, half: :down) # => 20
5710 * (-25).round(-1, half: :down) # => -20
5713 * - +:even+: round toward the candidate whose last nonzero digit is even:
5715 * 25.round(-1, half: :even) # => 20
5716 * 15.round(-1, half: :even) # => 20
5717 * (-25).round(-1, half: :even) # => -20
5719 * Raises and exception if the value for +half+ is invalid.
5721 * Related: Integer#truncate.
5726 int_round(int argc
, VALUE
* argv
, VALUE num
)
5732 if (!rb_scan_args(argc
, argv
, "01:", &nd
, &opt
)) return num
;
5733 ndigits
= NUM2INT(nd
);
5734 mode
= rb_num_get_rounding_option(opt
);
5738 return rb_int_round(num
, ndigits
, mode
);
5743 * floor(ndigits = 0) -> integer
5745 * Returns the largest number less than or equal to +self+ with
5746 * a precision of +ndigits+ decimal digits.
5748 * When +ndigits+ is negative, the returned value
5749 * has at least <tt>ndigits.abs</tt> trailing zeros:
5751 * 555.floor(-1) # => 550
5752 * 555.floor(-2) # => 500
5753 * -555.floor(-2) # => -600
5754 * 555.floor(-3) # => 0
5756 * Returns +self+ when +ndigits+ is zero or positive.
5758 * 555.floor # => 555
5759 * 555.floor(50) # => 555
5761 * Related: Integer#ceil.
5766 int_floor(int argc
, VALUE
* argv
, VALUE num
)
5770 if (!rb_check_arity(argc
, 0, 1)) return num
;
5771 ndigits
= NUM2INT(argv
[0]);
5775 return rb_int_floor(num
, ndigits
);
5780 * ceil(ndigits = 0) -> integer
5782 * Returns the smallest number greater than or equal to +self+ with
5783 * a precision of +ndigits+ decimal digits.
5785 * When the precision is negative, the returned value is an integer
5786 * with at least <code>ndigits.abs</code> trailing zeros:
5788 * 555.ceil(-1) # => 560
5789 * 555.ceil(-2) # => 600
5790 * -555.ceil(-2) # => -500
5791 * 555.ceil(-3) # => 1000
5793 * Returns +self+ when +ndigits+ is zero or positive.
5796 * 555.ceil(50) # => 555
5798 * Related: Integer#floor.
5803 int_ceil(int argc
, VALUE
* argv
, VALUE num
)
5807 if (!rb_check_arity(argc
, 0, 1)) return num
;
5808 ndigits
= NUM2INT(argv
[0]);
5812 return rb_int_ceil(num
, ndigits
);
5817 * truncate(ndigits = 0) -> integer
5819 * Returns +self+ truncated (toward zero) to
5820 * a precision of +ndigits+ decimal digits.
5822 * When +ndigits+ is negative, the returned value
5823 * has at least <tt>ndigits.abs</tt> trailing zeros:
5825 * 555.truncate(-1) # => 550
5826 * 555.truncate(-2) # => 500
5827 * -555.truncate(-2) # => -500
5829 * Returns +self+ when +ndigits+ is zero or positive.
5831 * 555.truncate # => 555
5832 * 555.truncate(50) # => 555
5834 * Related: Integer#round.
5839 int_truncate(int argc
, VALUE
* argv
, VALUE num
)
5843 if (!rb_check_arity(argc
, 0, 1)) return num
;
5844 ndigits
= NUM2INT(argv
[0]);
5848 return rb_int_truncate(num
, ndigits
);
5851 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5853 prefix##_isqrt(argtype n) \
5855 if (!argtype##_IN_DOUBLE_P(n)) { \
5856 unsigned int b = bit_length(n); \
5858 rettype x = (rettype)(n >> (b/2+1)); \
5859 x |= ((rettype)1LU << (b-1)/2); \
5860 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5863 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5866 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5867 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5869 # define RB_ULONG_IN_DOUBLE_P(n) 1
5871 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5872 #define RB_ULONG unsigned long
5873 DEFINE_INT_SQRT(unsigned long, rb_ulong
, RB_ULONG
)
5875 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5876 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5877 # define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5879 # define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5881 # ifdef ULL_TO_DOUBLE
5882 # define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
5884 # define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
5886 DEFINE_INT_SQRT(BDIGIT
, rb_bdigit_dbl
, BDIGIT_DBL
)
5889 #define domain_error(msg) \
5890 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
5894 * Integer.sqrt(numeric) -> integer
5896 * Returns the integer square root of the non-negative integer +n+,
5897 * which is the largest non-negative integer less than or equal to the
5898 * square root of +numeric+.
5900 * Integer.sqrt(0) # => 0
5901 * Integer.sqrt(1) # => 1
5902 * Integer.sqrt(24) # => 4
5903 * Integer.sqrt(25) # => 5
5904 * Integer.sqrt(10**400) # => 10**200
5906 * If +numeric+ is not an \Integer, it is converted to an \Integer:
5908 * Integer.sqrt(Complex(4, 0)) # => 2
5909 * Integer.sqrt(Rational(4, 1)) # => 2
5910 * Integer.sqrt(4.0) # => 2
5911 * Integer.sqrt(3.14159) # => 1
5913 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
5914 * except that the result of the latter code may differ from the true value
5915 * due to the limited precision of floating point arithmetic.
5917 * Integer.sqrt(10**46) # => 100000000000000000000000
5918 * Math.sqrt(10**46).floor # => 99999999999999991611392
5920 * Raises an exception if +numeric+ is negative.
5925 rb_int_s_isqrt(VALUE self
, VALUE num
)
5927 unsigned long n
, sq
;
5928 num
= rb_to_int(num
);
5929 if (FIXNUM_P(num
)) {
5930 if (FIXNUM_NEGATIVE_P(num
)) {
5931 domain_error("isqrt");
5934 sq
= rb_ulong_isqrt(n
);
5935 return LONG2FIX(sq
);
5939 if (RBIGNUM_NEGATIVE_P(num
)) {
5940 domain_error("isqrt");
5942 biglen
= BIGNUM_LEN(num
);
5943 if (biglen
== 0) return INT2FIX(0);
5944 #if SIZEOF_BDIGIT <= SIZEOF_LONG
5947 n
= BIGNUM_DIGITS(num
)[0];
5948 sq
= rb_ulong_isqrt(n
);
5949 return ULONG2NUM(sq
);
5952 return rb_big_isqrt(num
);
5958 * Integer.try_convert(object) -> object, integer, or nil
5960 * If +object+ is an \Integer object, returns +object+.
5961 * Integer.try_convert(1) # => 1
5963 * Otherwise if +object+ responds to <tt>:to_int</tt>,
5964 * calls <tt>object.to_int</tt> and returns the result.
5965 * Integer.try_convert(1.25) # => 1
5967 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
5968 * Integer.try_convert([]) # => nil
5970 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
5973 int_s_try_convert(VALUE self
, VALUE num
)
5975 return rb_check_integer_type(num
);
5979 * Document-class: ZeroDivisionError
5981 * Raised when attempting to divide an integer by 0.
5983 * 42 / 0 #=> ZeroDivisionError: divided by 0
5985 * Note that only division by an exact 0 will raise the exception:
5987 * 42 / 0.0 #=> Float::INFINITY
5988 * 42 / -0.0 #=> -Float::INFINITY
5993 * Document-class: FloatDomainError
5995 * Raised when attempting to convert special float values (in particular
5996 * +Infinity+ or +NaN+) to numerical classes which don't support them.
5998 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6002 * Document-class: Numeric
6004 * \Numeric is the class from which all higher-level numeric classes should inherit.
6006 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6007 * Integer are implemented as immediates, which means that each Integer is a single immutable
6008 * object which is always passed by value.
6011 * 1.object_id == a.object_id #=> true
6013 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6014 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6016 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6018 * 1.object_id == 1.dup.object_id #=> true
6020 * For this reason, \Numeric should be used when defining other numeric classes.
6022 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6023 * Array containing an object that has been coerced into an instance of the new class
6024 * and +self+ (see #coerce).
6026 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6027 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6028 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6029 * instances of other numeric classes.
6031 * class Tally < Numeric
6032 * def initialize(string)
6045 * [self.class.new('|' * other.to_i), self]
6049 * to_i <=> other.to_i
6053 * self.class.new('|' * (to_i + other.to_i))
6057 * self.class.new('|' * (to_i - other.to_i))
6061 * self.class.new('|' * (to_i * other.to_i))
6065 * self.class.new('|' * (to_i / other.to_i))
6069 * tally = Tally.new('||')
6070 * puts tally * 2 #=> "||||"
6071 * puts tally > 1 #=> true
6075 * First, what's elsewhere. \Class \Numeric:
6077 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6078 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6080 * Here, class \Numeric provides methods for:
6082 * - {Querying}[rdoc-ref:Numeric@Querying]
6083 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6084 * - {Converting}[rdoc-ref:Numeric@Converting]
6085 * - {Other}[rdoc-ref:Numeric@Other]
6089 * - #finite?: Returns true unless +self+ is infinite or not a number.
6090 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6091 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6092 * - #integer?: Returns whether +self+ is an integer.
6093 * - #negative?: Returns whether +self+ is negative.
6094 * - #nonzero?: Returns whether +self+ is not zero.
6095 * - #positive?: Returns whether +self+ is positive.
6096 * - #real?: Returns whether +self+ is a real value.
6097 * - #zero?: Returns whether +self+ is zero.
6103 * - -1 if +self+ is less than the given value.
6104 * - 0 if +self+ is equal to the given value.
6105 * - 1 if +self+ is greater than the given value.
6106 * - +nil+ if +self+ and the given value are not comparable.
6108 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6112 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6113 * - #-@: Returns the value of +self+, negated.
6114 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6115 * - #abs2: Returns the square of +self+.
6116 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6117 * Math::PI otherwise.
6118 * - #ceil: Returns the smallest number greater than or equal to +self+,
6119 * to a given precision.
6120 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6121 * for the given other value.
6122 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6123 * - #denominator: Returns the denominator (always positive)
6124 * of the Rational representation of +self+.
6125 * - #div: Returns the value of +self+ divided by the given value
6126 * and converted to an integer.
6127 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6128 * from dividing +self+ the given divisor.
6129 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6130 * - #floor: Returns the largest number less than or equal to +self+,
6131 * to a given precision.
6132 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6134 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6135 * - #numerator: Returns the numerator of the Rational representation of +self+;
6136 * has the same sign as +self+.
6137 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6138 * - #quo: Returns the value of +self+ divided by the given value.
6139 * - #real: Returns the real part of +self+.
6140 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6141 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6142 * - #round: Returns the value of +self+ rounded to the nearest value
6143 * for the given a precision.
6144 * - #to_c: Returns the Complex representation of +self+.
6145 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6146 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6150 * - #clone: Returns +self+; does not allow freezing.
6151 * - #dup (aliased as #+@): Returns +self+.
6152 * - #step: Invokes the given block with the sequence of specified numbers.
6159 /* Turn off floating point exceptions for divide by zero, etc. */
6162 id_coerce
= rb_intern_const("coerce");
6163 id_to
= rb_intern_const("to");
6164 id_by
= rb_intern_const("by");
6166 rb_eZeroDivError
= rb_define_class("ZeroDivisionError", rb_eStandardError
);
6167 rb_eFloatDomainError
= rb_define_class("FloatDomainError", rb_eRangeError
);
6168 rb_cNumeric
= rb_define_class("Numeric", rb_cObject
);
6170 rb_define_method(rb_cNumeric
, "singleton_method_added", num_sadded
, 1);
6171 rb_include_module(rb_cNumeric
, rb_mComparable
);
6172 rb_define_method(rb_cNumeric
, "coerce", num_coerce
, 1);
6173 rb_define_method(rb_cNumeric
, "clone", num_clone
, -1);
6174 rb_define_method(rb_cNumeric
, "dup", num_dup
, 0);
6176 rb_define_method(rb_cNumeric
, "i", num_imaginary
, 0);
6177 rb_define_method(rb_cNumeric
, "+@", num_uplus
, 0);
6178 rb_define_method(rb_cNumeric
, "-@", num_uminus
, 0);
6179 rb_define_method(rb_cNumeric
, "<=>", num_cmp
, 1);
6180 rb_define_method(rb_cNumeric
, "eql?", num_eql
, 1);
6181 rb_define_method(rb_cNumeric
, "fdiv", num_fdiv
, 1);
6182 rb_define_method(rb_cNumeric
, "div", num_div
, 1);
6183 rb_define_method(rb_cNumeric
, "divmod", num_divmod
, 1);
6184 rb_define_method(rb_cNumeric
, "%", num_modulo
, 1);
6185 rb_define_method(rb_cNumeric
, "modulo", num_modulo
, 1);
6186 rb_define_method(rb_cNumeric
, "remainder", num_remainder
, 1);
6187 rb_define_method(rb_cNumeric
, "abs", num_abs
, 0);
6188 rb_define_method(rb_cNumeric
, "magnitude", num_abs
, 0);
6189 rb_define_method(rb_cNumeric
, "to_int", num_to_int
, 0);
6191 rb_define_method(rb_cNumeric
, "zero?", num_zero_p
, 0);
6192 rb_define_method(rb_cNumeric
, "nonzero?", num_nonzero_p
, 0);
6194 rb_define_method(rb_cNumeric
, "floor", num_floor
, -1);
6195 rb_define_method(rb_cNumeric
, "ceil", num_ceil
, -1);
6196 rb_define_method(rb_cNumeric
, "round", num_round
, -1);
6197 rb_define_method(rb_cNumeric
, "truncate", num_truncate
, -1);
6198 rb_define_method(rb_cNumeric
, "step", num_step
, -1);
6199 rb_define_method(rb_cNumeric
, "positive?", num_positive_p
, 0);
6200 rb_define_method(rb_cNumeric
, "negative?", num_negative_p
, 0);
6202 rb_cInteger
= rb_define_class("Integer", rb_cNumeric
);
6203 rb_undef_alloc_func(rb_cInteger
);
6204 rb_undef_method(CLASS_OF(rb_cInteger
), "new");
6205 rb_define_singleton_method(rb_cInteger
, "sqrt", rb_int_s_isqrt
, 1);
6206 rb_define_singleton_method(rb_cInteger
, "try_convert", int_s_try_convert
, 1);
6208 rb_define_method(rb_cInteger
, "to_s", rb_int_to_s
, -1);
6209 rb_define_alias(rb_cInteger
, "inspect", "to_s");
6210 rb_define_method(rb_cInteger
, "allbits?", int_allbits_p
, 1);
6211 rb_define_method(rb_cInteger
, "anybits?", int_anybits_p
, 1);
6212 rb_define_method(rb_cInteger
, "nobits?", int_nobits_p
, 1);
6213 rb_define_method(rb_cInteger
, "upto", int_upto
, 1);
6214 rb_define_method(rb_cInteger
, "downto", int_downto
, 1);
6215 rb_define_method(rb_cInteger
, "succ", int_succ
, 0);
6216 rb_define_method(rb_cInteger
, "next", int_succ
, 0);
6217 rb_define_method(rb_cInteger
, "pred", int_pred
, 0);
6218 rb_define_method(rb_cInteger
, "chr", int_chr
, -1);
6219 rb_define_method(rb_cInteger
, "to_f", int_to_f
, 0);
6220 rb_define_method(rb_cInteger
, "floor", int_floor
, -1);
6221 rb_define_method(rb_cInteger
, "ceil", int_ceil
, -1);
6222 rb_define_method(rb_cInteger
, "truncate", int_truncate
, -1);
6223 rb_define_method(rb_cInteger
, "round", int_round
, -1);
6224 rb_define_method(rb_cInteger
, "<=>", rb_int_cmp
, 1);
6226 rb_define_method(rb_cInteger
, "+", rb_int_plus
, 1);
6227 rb_define_method(rb_cInteger
, "-", rb_int_minus
, 1);
6228 rb_define_method(rb_cInteger
, "*", rb_int_mul
, 1);
6229 rb_define_method(rb_cInteger
, "/", rb_int_div
, 1);
6230 rb_define_method(rb_cInteger
, "div", rb_int_idiv
, 1);
6231 rb_define_method(rb_cInteger
, "%", rb_int_modulo
, 1);
6232 rb_define_method(rb_cInteger
, "modulo", rb_int_modulo
, 1);
6233 rb_define_method(rb_cInteger
, "remainder", int_remainder
, 1);
6234 rb_define_method(rb_cInteger
, "divmod", rb_int_divmod
, 1);
6235 rb_define_method(rb_cInteger
, "fdiv", rb_int_fdiv
, 1);
6236 rb_define_method(rb_cInteger
, "**", rb_int_pow
, 1);
6238 rb_define_method(rb_cInteger
, "pow", rb_int_powm
, -1); /* in bignum.c */
6240 rb_define_method(rb_cInteger
, "===", rb_int_equal
, 1);
6241 rb_define_method(rb_cInteger
, "==", rb_int_equal
, 1);
6242 rb_define_method(rb_cInteger
, ">", rb_int_gt
, 1);
6243 rb_define_method(rb_cInteger
, ">=", rb_int_ge
, 1);
6244 rb_define_method(rb_cInteger
, "<", int_lt
, 1);
6245 rb_define_method(rb_cInteger
, "<=", int_le
, 1);
6247 rb_define_method(rb_cInteger
, "&", rb_int_and
, 1);
6248 rb_define_method(rb_cInteger
, "|", int_or
, 1);
6249 rb_define_method(rb_cInteger
, "^", int_xor
, 1);
6250 rb_define_method(rb_cInteger
, "[]", int_aref
, -1);
6252 rb_define_method(rb_cInteger
, "<<", rb_int_lshift
, 1);
6253 rb_define_method(rb_cInteger
, ">>", rb_int_rshift
, 1);
6255 rb_define_method(rb_cInteger
, "digits", rb_int_digits
, -1);
6257 #define fix_to_s_static(n) do { \
6258 VALUE lit = rb_fstring_literal(#n); \
6259 rb_fix_to_s_static[n] = lit; \
6260 rb_vm_register_global_object(lit); \
6275 #undef fix_to_s_static
6277 rb_cFloat
= rb_define_class("Float", rb_cNumeric
);
6279 rb_undef_alloc_func(rb_cFloat
);
6280 rb_undef_method(CLASS_OF(rb_cFloat
), "new");
6283 * The base of the floating point, or number of unique digits used to
6284 * represent the number.
6286 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6288 rb_define_const(rb_cFloat
, "RADIX", INT2FIX(FLT_RADIX
));
6290 * The number of base digits for the +double+ data type.
6292 * Usually defaults to 53.
6294 rb_define_const(rb_cFloat
, "MANT_DIG", INT2FIX(DBL_MANT_DIG
));
6296 * The minimum number of significant decimal digits in a double-precision
6299 * Usually defaults to 15.
6301 rb_define_const(rb_cFloat
, "DIG", INT2FIX(DBL_DIG
));
6303 * The smallest possible exponent value in a double-precision floating
6306 * Usually defaults to -1021.
6308 rb_define_const(rb_cFloat
, "MIN_EXP", INT2FIX(DBL_MIN_EXP
));
6310 * The largest possible exponent value in a double-precision floating
6313 * Usually defaults to 1024.
6315 rb_define_const(rb_cFloat
, "MAX_EXP", INT2FIX(DBL_MAX_EXP
));
6317 * The smallest negative exponent in a double-precision floating point
6318 * where 10 raised to this power minus 1.
6320 * Usually defaults to -307.
6322 rb_define_const(rb_cFloat
, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP
));
6324 * The largest positive exponent in a double-precision floating point where
6325 * 10 raised to this power minus 1.
6327 * Usually defaults to 308.
6329 rb_define_const(rb_cFloat
, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP
));
6331 * The smallest positive normalized number in a double-precision floating point.
6333 * Usually defaults to 2.2250738585072014e-308.
6335 * If the platform supports denormalized numbers,
6336 * there are numbers between zero and Float::MIN.
6337 * 0.0.next_float returns the smallest positive floating point number
6338 * including denormalized numbers.
6340 rb_define_const(rb_cFloat
, "MIN", DBL2NUM(DBL_MIN
));
6342 * The largest possible integer in a double-precision floating point number.
6344 * Usually defaults to 1.7976931348623157e+308.
6346 rb_define_const(rb_cFloat
, "MAX", DBL2NUM(DBL_MAX
));
6348 * The difference between 1 and the smallest double-precision floating
6349 * point number greater than 1.
6351 * Usually defaults to 2.2204460492503131e-16.
6353 rb_define_const(rb_cFloat
, "EPSILON", DBL2NUM(DBL_EPSILON
));
6355 * An expression representing positive infinity.
6357 rb_define_const(rb_cFloat
, "INFINITY", DBL2NUM(HUGE_VAL
));
6359 * An expression representing a value which is "not a number".
6361 rb_define_const(rb_cFloat
, "NAN", DBL2NUM(nan("")));
6363 rb_define_method(rb_cFloat
, "to_s", flo_to_s
, 0);
6364 rb_define_alias(rb_cFloat
, "inspect", "to_s");
6365 rb_define_method(rb_cFloat
, "coerce", flo_coerce
, 1);
6366 rb_define_method(rb_cFloat
, "+", rb_float_plus
, 1);
6367 rb_define_method(rb_cFloat
, "-", rb_float_minus
, 1);
6368 rb_define_method(rb_cFloat
, "*", rb_float_mul
, 1);
6369 rb_define_method(rb_cFloat
, "/", rb_float_div
, 1);
6370 rb_define_method(rb_cFloat
, "quo", flo_quo
, 1);
6371 rb_define_method(rb_cFloat
, "fdiv", flo_quo
, 1);
6372 rb_define_method(rb_cFloat
, "%", flo_mod
, 1);
6373 rb_define_method(rb_cFloat
, "modulo", flo_mod
, 1);
6374 rb_define_method(rb_cFloat
, "divmod", flo_divmod
, 1);
6375 rb_define_method(rb_cFloat
, "**", rb_float_pow
, 1);
6376 rb_define_method(rb_cFloat
, "==", flo_eq
, 1);
6377 rb_define_method(rb_cFloat
, "===", flo_eq
, 1);
6378 rb_define_method(rb_cFloat
, "<=>", flo_cmp
, 1);
6379 rb_define_method(rb_cFloat
, ">", rb_float_gt
, 1);
6380 rb_define_method(rb_cFloat
, ">=", flo_ge
, 1);
6381 rb_define_method(rb_cFloat
, "<", flo_lt
, 1);
6382 rb_define_method(rb_cFloat
, "<=", flo_le
, 1);
6383 rb_define_method(rb_cFloat
, "eql?", flo_eql
, 1);
6384 rb_define_method(rb_cFloat
, "hash", flo_hash
, 0);
6386 rb_define_method(rb_cFloat
, "to_i", flo_to_i
, 0);
6387 rb_define_method(rb_cFloat
, "to_int", flo_to_i
, 0);
6388 rb_define_method(rb_cFloat
, "floor", flo_floor
, -1);
6389 rb_define_method(rb_cFloat
, "ceil", flo_ceil
, -1);
6390 rb_define_method(rb_cFloat
, "round", flo_round
, -1);
6391 rb_define_method(rb_cFloat
, "truncate", flo_truncate
, -1);
6393 rb_define_method(rb_cFloat
, "nan?", flo_is_nan_p
, 0);
6394 rb_define_method(rb_cFloat
, "infinite?", rb_flo_is_infinite_p
, 0);
6395 rb_define_method(rb_cFloat
, "finite?", rb_flo_is_finite_p
, 0);
6396 rb_define_method(rb_cFloat
, "next_float", flo_next_float
, 0);
6397 rb_define_method(rb_cFloat
, "prev_float", flo_prev_float
, 0);
6400 #undef rb_float_value
6402 rb_float_value(VALUE v
)
6404 return rb_float_value_inline(v
);
6409 rb_float_new(double d
)
6411 return rb_float_new_inline(d
);
6414 #include "numeric.rbinc"