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
559 * Returns <tt>Complex(0, self)</tt>:
563 * 2.0.i # => (0+2.0i)
564 * Rational(1, 2).i # => (0+(1/2)*i)
565 * Complex(3, 4).i # Raises NoMethodError.
570 num_imaginary(VALUE num
)
572 return rb_complex_new(INT2FIX(0), num
);
579 * Unary Minus---Returns the receiver, negated.
583 num_uminus(VALUE num
)
588 do_coerce(&zero
, &num
, TRUE
);
590 return num_funcall1(zero
, '-', num
);
595 * fdiv(other) -> float
597 * Returns the quotient <tt>self/other</tt> as a float,
598 * using method +/+ in the derived class of +self+.
599 * (\Numeric itself does not define method +/+.)
601 * Of the Core and Standard Library classes,
602 * only BigDecimal uses this implementation.
607 num_fdiv(VALUE x
, VALUE y
)
609 return rb_funcall(rb_Float(x
), '/', 1, y
);
614 * div(other) -> integer
616 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
617 * using method +/+ in the derived class of +self+.
618 * (\Numeric itself does not define method +/+.)
620 * Of the Core and Standard Library classes,
621 * Only Float and Rational use this implementation.
626 num_div(VALUE x
, VALUE y
)
628 if (rb_equal(INT2FIX(0), y
)) rb_num_zerodiv();
629 return rb_funcall(num_funcall1(x
, '/', y
), rb_intern("floor"), 0);
634 * self % other -> real_numeric
636 * Returns +self+ modulo +other+ as a real number.
638 * Of the Core and Standard Library classes,
639 * only Rational uses this implementation.
641 * For Rational +r+ and real number +n+, these expressions are equivalent:
647 * See Numeric#divmod.
651 * r = Rational(1, 2) # => (1/2)
652 * r2 = Rational(2, 3) # => (2/3)
657 * r = Rational(301,100) # => (301/100)
658 * r2 = Rational(7,5) # => (7/5)
659 * r % r2 # => (21/100)
660 * r % -r2 # => (-119/100)
661 * (-r) % r2 # => (119/100)
662 * (-r) %-r2 # => (-21/100)
667 num_modulo(VALUE x
, VALUE y
)
669 VALUE q
= num_funcall1(x
, id_div
, y
);
670 return rb_funcall(x
, '-', 1,
671 rb_funcall(y
, '*', 1, q
));
676 * remainder(other) -> real_number
678 * Returns the remainder after dividing +self+ by +other+.
680 * Of the Core and Standard Library classes,
681 * only Float and Rational use this implementation.
685 * 11.0.remainder(4) # => 3.0
686 * 11.0.remainder(-4) # => 3.0
687 * -11.0.remainder(4) # => -3.0
688 * -11.0.remainder(-4) # => -3.0
690 * 12.0.remainder(4) # => 0.0
691 * 12.0.remainder(-4) # => 0.0
692 * -12.0.remainder(4) # => -0.0
693 * -12.0.remainder(-4) # => -0.0
695 * 13.0.remainder(4.0) # => 1.0
696 * 13.0.remainder(Rational(4, 1)) # => 1.0
698 * Rational(13, 1).remainder(4) # => (1/1)
699 * Rational(13, 1).remainder(-4) # => (1/1)
700 * Rational(-13, 1).remainder(4) # => (-1/1)
701 * Rational(-13, 1).remainder(-4) # => (-1/1)
706 num_remainder(VALUE x
, VALUE y
)
708 if (!rb_obj_is_kind_of(y
, rb_cNumeric
)) {
709 do_coerce(&x
, &y
, TRUE
);
711 VALUE z
= num_funcall1(x
, '%', y
);
713 if ((!rb_equal(z
, INT2FIX(0))) &&
714 ((rb_num_negative_int_p(x
) &&
715 rb_num_positive_int_p(y
)) ||
716 (rb_num_positive_int_p(x
) &&
717 rb_num_negative_int_p(y
)))) {
718 if (RB_FLOAT_TYPE_P(y
)) {
719 if (isinf(RFLOAT_VALUE(y
))) {
723 return rb_funcall(z
, '-', 1, y
);
730 * divmod(other) -> array
732 * Returns a 2-element array <tt>[q, r]</tt>, where
734 * q = (self/other).floor # Quotient
735 * r = self % other # Remainder
737 * Of the Core and Standard Library classes,
738 * only Rational uses this implementation.
742 * Rational(11, 1).divmod(4) # => [2, (3/1)]
743 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
744 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
745 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
747 * Rational(12, 1).divmod(4) # => [3, (0/1)]
748 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
749 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
750 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
752 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
753 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
757 num_divmod(VALUE x
, VALUE y
)
759 return rb_assoc_new(num_div(x
, y
), num_modulo(x
, y
));
766 * Returns the absolute value of +self+.
769 * (-34.56).abs #=> 34.56
770 * -34.56.abs #=> 34.56
777 if (rb_num_negative_int_p(num
)) {
778 return num_funcall0(num
, idUMinus
);
785 * zero? -> true or false
787 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
789 * Of the Core and Standard Library classes,
790 * only Rational and Complex use this implementation.
795 num_zero_p(VALUE num
)
797 return rb_equal(num
, INT2FIX(0));
801 int_zero_p(VALUE num
)
804 return FIXNUM_ZERO_P(num
);
806 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
807 return rb_bigzero_p(num
);
811 rb_int_zero_p(VALUE num
)
813 return RBOOL(int_zero_p(num
));
818 * nonzero? -> self or nil
820 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
821 * uses method <tt>zero?</tt> for the evaluation.
823 * The returned +self+ allows the method to be chained:
825 * a = %w[z Bb bB bb BB a aA Aa AA A]
826 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
827 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
829 * Of the Core and Standard Library classes,
830 * Integer, Float, Rational, and Complex use this implementation.
837 num_nonzero_p(VALUE num
)
839 if (RTEST(num_funcall0(num
, rb_intern("zero?")))) {
849 * Returns +self+ as an integer;
850 * converts using method +to_i+ in the derived class.
852 * Of the Core and Standard Library classes,
853 * only Rational and Complex use this implementation.
857 * Rational(1, 2).to_int # => 0
858 * Rational(2, 1).to_int # => 2
859 * Complex(2, 0).to_int # => 2
860 * Complex(2, 1) # Raises RangeError (non-zero imaginary part)
865 num_to_int(VALUE num
)
867 return num_funcall0(num
, id_to_i
);
872 * positive? -> true or false
874 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
879 num_positive_p(VALUE num
)
884 if (method_basic_p(rb_cInteger
))
885 return RBOOL((SIGNED_VALUE
)num
> (SIGNED_VALUE
)INT2FIX(0));
887 else if (RB_BIGNUM_TYPE_P(num
)) {
888 if (method_basic_p(rb_cInteger
))
889 return RBOOL(BIGNUM_POSITIVE_P(num
) && !rb_bigzero_p(num
));
891 return rb_num_compare_with_zero(num
, mid
);
896 * negative? -> true or false
898 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
903 num_negative_p(VALUE num
)
905 return RBOOL(rb_num_negative_int_p(num
));
909 /********************************************************************
911 * Document-class: Float
913 * A \Float object represents a sometimes-inexact real number using the native
914 * architecture's double-precision floating point representation.
916 * Floating point has a different arithmetic and is an inexact number.
917 * So you should know its esoteric system. See following:
919 * - https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
920 * - https://github.com/rdp/ruby_tutorials_core/wiki/Ruby-Talk-FAQ#-why-are-rubys-floats-imprecise
921 * - https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
923 * You can create a \Float object explicitly with:
925 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
927 * You can convert certain objects to Floats with:
933 * First, what's elsewhere. \Class \Float:
936 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
937 * and {class Object}[rdoc-ref:Object@What-27s+Here].
938 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
940 * Here, class \Float provides methods for:
942 * - {Querying}[rdoc-ref:Float@Querying]
943 * - {Comparing}[rdoc-ref:Float@Comparing]
944 * - {Converting}[rdoc-ref:Float@Converting]
948 * - #finite?: Returns whether +self+ is finite.
949 * - #hash: Returns the integer hash code for +self+.
950 * - #infinite?: Returns whether +self+ is infinite.
951 * - #nan?: Returns whether +self+ is a NaN (not-a-number).
955 * - #<: Returns whether +self+ is less than the given value.
956 * - #<=: Returns whether +self+ is less than or equal to the given value.
957 * - #<=>: Returns a number indicating whether +self+ is less than, equal
958 * to, or greater than the given value.
959 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
961 * - #>: Returns whether +self+ is greater than the given value.
962 * - #>=: Returns whether +self+ is greater than or equal to the given value.
966 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
967 * - #*: Returns the product of +self+ and the given value.
968 * - #**: Returns the value of +self+ raised to the power of the given value.
969 * - #+: Returns the sum of +self+ and the given value.
970 * - #-: Returns the difference of +self+ and the given value.
971 * - #/: Returns the quotient of +self+ and the given value.
972 * - #ceil: Returns the smallest number greater than or equal to +self+.
973 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
975 * - #divmod: Returns a 2-element array containing the quotient and remainder
976 * results of dividing +self+ by the given value.
977 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
978 * - #floor: Returns the greatest number smaller than or equal to +self+.
979 * - #next_float: Returns the next-larger representable \Float.
980 * - #prev_float: Returns the next-smaller representable \Float.
981 * - #quo: Returns the quotient from dividing +self+ by the given value.
982 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
983 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
984 * - #to_s (aliased as #inspect): Returns a string containing the place-value
985 * representation of +self+ in the given radix.
986 * - #truncate: Returns +self+ truncated to a given precision.
991 rb_float_new_in_heap(double d
)
993 NEWOBJ_OF(flt
, struct RFloat
, rb_cFloat
, T_FLOAT
| (RGENGC_WB_PROTECTED_FLOAT
? FL_WB_PROTECTED
: 0), sizeof(struct RFloat
), 0);
995 #if SIZEOF_DOUBLE <= SIZEOF_VALUE
996 flt
->float_value
= d
;
1000 rb_float_value_type v
;
1002 flt
->float_value
= u
.v
;
1004 OBJ_FREEZE((VALUE
)flt
);
1012 * Returns a string containing a representation of +self+;
1013 * depending of the value of +self+, the string representation
1016 * - A fixed-point number.
1017 * 3.14.to_s # => "3.14"
1018 * - A number in "scientific notation" (containing an exponent).
1019 * (10.1**50).to_s # => "1.644631821843879e+50"
1021 * (10.1**500).to_s # => "Infinity"
1023 * (-10.1**500).to_s # => "-Infinity"
1024 * - 'NaN' (indicating not-a-number).
1025 * (0.0/0.0).to_s # => "NaN"
1032 enum {decimal_mant
= DBL_MANT_DIG
-DBL_DIG
};
1033 enum {float_dig
= DBL_DIG
+1};
1034 char buf
[float_dig
+ roomof(decimal_mant
, CHAR_BIT
) + 10];
1035 double value
= RFLOAT_VALUE(flt
);
1038 int sign
, decpt
, digs
;
1041 static const char minf
[] = "-Infinity";
1042 const int pos
= (value
> 0); /* skip "-" */
1043 return rb_usascii_str_new(minf
+pos
, strlen(minf
)-pos
);
1045 else if (isnan(value
))
1046 return rb_usascii_str_new2("NaN");
1048 p
= ruby_dtoa(value
, 0, 0, &decpt
, &sign
, &e
);
1049 s
= sign
? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1050 if ((digs
= (int)(e
- p
)) >= (int)sizeof(buf
)) digs
= (int)sizeof(buf
) - 1;
1051 memcpy(buf
, p
, digs
);
1055 memmove(buf
+ decpt
+ 1, buf
+ decpt
, digs
- decpt
);
1057 rb_str_cat(s
, buf
, digs
+ 1);
1059 else if (decpt
<= DBL_DIG
) {
1062 rb_str_cat(s
, buf
, digs
);
1063 rb_str_resize(s
, (len
= RSTRING_LEN(s
)) + decpt
- digs
+ 2);
1064 ptr
= RSTRING_PTR(s
) + len
;
1066 memset(ptr
, '0', decpt
- digs
);
1067 ptr
+= decpt
- digs
;
1069 memcpy(ptr
, ".0", 2);
1075 else if (decpt
> -4) {
1078 rb_str_cat(s
, "0.", 2);
1079 rb_str_resize(s
, (len
= RSTRING_LEN(s
)) - decpt
+ digs
);
1080 ptr
= RSTRING_PTR(s
);
1081 memset(ptr
+= len
, '0', -decpt
);
1082 memcpy(ptr
-= decpt
, buf
, digs
);
1091 memmove(buf
+ 2, buf
+ 1, digs
- 1);
1098 rb_str_cat(s
, buf
, digs
+ 1);
1099 rb_str_catf(s
, "e%+03d", decpt
- 1);
1105 * coerce(other) -> array
1107 * Returns a 2-element array containing +other+ converted to a \Float
1110 * f = 3.14 # => 3.14
1111 * f.coerce(2) # => [2.0, 3.14]
1112 * f.coerce(2.0) # => [2.0, 3.14]
1113 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1114 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1116 * Raises an exception if a type conversion fails.
1121 flo_coerce(VALUE x
, VALUE y
)
1123 return rb_assoc_new(rb_Float(y
), x
);
1127 rb_float_uminus(VALUE flt
)
1129 return DBL2NUM(-RFLOAT_VALUE(flt
));
1134 * self + other -> numeric
1136 * Returns a new \Float which is the sum of +self+ and +other+:
1139 * f + 1 # => 4.140000000000001
1140 * f + 1.0 # => 4.140000000000001
1141 * f + Rational(1, 1) # => 4.140000000000001
1142 * f + Complex(1, 0) # => (4.140000000000001+0i)
1147 rb_float_plus(VALUE x
, VALUE y
)
1150 return DBL2NUM(RFLOAT_VALUE(x
) + (double)FIX2LONG(y
));
1152 else if (RB_BIGNUM_TYPE_P(y
)) {
1153 return DBL2NUM(RFLOAT_VALUE(x
) + rb_big2dbl(y
));
1155 else if (RB_FLOAT_TYPE_P(y
)) {
1156 return DBL2NUM(RFLOAT_VALUE(x
) + RFLOAT_VALUE(y
));
1159 return rb_num_coerce_bin(x
, y
, '+');
1165 * self - other -> numeric
1167 * Returns a new \Float which is the difference of +self+ and +other+:
1172 * f - Rational(1, 1) # => 2.14
1173 * f - Complex(1, 0) # => (2.14+0i)
1178 rb_float_minus(VALUE x
, VALUE y
)
1181 return DBL2NUM(RFLOAT_VALUE(x
) - (double)FIX2LONG(y
));
1183 else if (RB_BIGNUM_TYPE_P(y
)) {
1184 return DBL2NUM(RFLOAT_VALUE(x
) - rb_big2dbl(y
));
1186 else if (RB_FLOAT_TYPE_P(y
)) {
1187 return DBL2NUM(RFLOAT_VALUE(x
) - RFLOAT_VALUE(y
));
1190 return rb_num_coerce_bin(x
, y
, '-');
1196 * self * other -> numeric
1198 * Returns a new \Float which is the product of +self+ and +other+:
1203 * f * Rational(1, 2) # => 1.57
1204 * f * Complex(2, 0) # => (6.28+0.0i)
1208 rb_float_mul(VALUE x
, VALUE y
)
1211 return DBL2NUM(RFLOAT_VALUE(x
) * (double)FIX2LONG(y
));
1213 else if (RB_BIGNUM_TYPE_P(y
)) {
1214 return DBL2NUM(RFLOAT_VALUE(x
) * rb_big2dbl(y
));
1216 else if (RB_FLOAT_TYPE_P(y
)) {
1217 return DBL2NUM(RFLOAT_VALUE(x
) * RFLOAT_VALUE(y
));
1220 return rb_num_coerce_bin(x
, y
, '*');
1225 double_div_double(double x
, double y
)
1227 if (LIKELY(y
!= 0.0)) {
1230 else if (x
== 0.0) {
1234 double z
= signbit(y
) ? -1.0 : 1.0;
1235 return x
* z
* HUGE_VAL
;
1240 rb_flo_div_flo(VALUE x
, VALUE y
)
1242 double num
= RFLOAT_VALUE(x
);
1243 double den
= RFLOAT_VALUE(y
);
1244 double ret
= double_div_double(num
, den
);
1245 return DBL2NUM(ret
);
1250 * self / other -> numeric
1252 * Returns a new \Float which is the result of dividing +self+ by +other+:
1257 * f / Rational(2, 1) # => 1.57
1258 * f / Complex(2, 0) # => (1.57+0.0i)
1263 rb_float_div(VALUE x
, VALUE y
)
1265 double num
= RFLOAT_VALUE(x
);
1272 else if (RB_BIGNUM_TYPE_P(y
)) {
1273 den
= rb_big2dbl(y
);
1275 else if (RB_FLOAT_TYPE_P(y
)) {
1276 den
= RFLOAT_VALUE(y
);
1279 return rb_num_coerce_bin(x
, y
, '/');
1282 ret
= double_div_double(num
, den
);
1283 return DBL2NUM(ret
);
1288 * quo(other) -> numeric
1290 * Returns the quotient from dividing +self+ by +other+:
1293 * f.quo(2) # => 1.57
1294 * f.quo(-2) # => -1.57
1295 * f.quo(Rational(2, 1)) # => 1.57
1296 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1301 flo_quo(VALUE x
, VALUE y
)
1303 return num_funcall1(x
, '/', y
);
1307 flodivmod(double x
, double y
, double *divp
, double *modp
)
1312 /* y is NaN so all results are NaN */
1313 if (modp
) *modp
= y
;
1314 if (divp
) *divp
= y
;
1317 if (y
== 0.0) rb_num_zerodiv();
1318 if ((x
== 0.0) || (isinf(y
) && !isinf(x
)))
1330 if (isinf(x
) && !isinf(y
))
1333 div
= (x
- mod
) / y
;
1334 if (modp
&& divp
) div
= round(div
);
1340 if (modp
) *modp
= mod
;
1341 if (divp
) *divp
= div
;
1345 * Returns the modulo of division of x by y.
1346 * An error will be raised if y == 0.
1350 ruby_float_mod(double x
, double y
)
1353 flodivmod(x
, y
, 0, &mod
);
1359 * self % other -> float
1361 * Returns +self+ modulo +other+ as a float.
1363 * For float +f+ and real number +r+, these expressions are equivalent:
1369 * See Numeric#divmod.
1377 * 10.0 % -2 # => 0.0
1378 * 10.0 % -3 # => -2.0
1379 * 10.0 % -4 # => -2.0
1381 * 10.0 % 4.0 # => 2.0
1382 * 10.0 % Rational(4, 1) # => 2.0
1387 flo_mod(VALUE x
, VALUE y
)
1392 fy
= (double)FIX2LONG(y
);
1394 else if (RB_BIGNUM_TYPE_P(y
)) {
1397 else if (RB_FLOAT_TYPE_P(y
)) {
1398 fy
= RFLOAT_VALUE(y
);
1401 return rb_num_coerce_bin(x
, y
, '%');
1403 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x
), fy
));
1410 return LONG2FIX((long)d
);
1412 return rb_dbl2big(d
);
1417 * divmod(other) -> array
1419 * Returns a 2-element array <tt>[q, r]</tt>, where
1421 * q = (self/other).floor # Quotient
1422 * r = self % other # Remainder
1426 * 11.0.divmod(4) # => [2, 3.0]
1427 * 11.0.divmod(-4) # => [-3, -1.0]
1428 * -11.0.divmod(4) # => [-3, 1.0]
1429 * -11.0.divmod(-4) # => [2, -3.0]
1431 * 12.0.divmod(4) # => [3, 0.0]
1432 * 12.0.divmod(-4) # => [-3, 0.0]
1433 * -12.0.divmod(4) # => [-3, -0.0]
1434 * -12.0.divmod(-4) # => [3, -0.0]
1436 * 13.0.divmod(4.0) # => [3, 1.0]
1437 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1442 flo_divmod(VALUE x
, VALUE y
)
1444 double fy
, div
, mod
;
1445 volatile VALUE a
, b
;
1448 fy
= (double)FIX2LONG(y
);
1450 else if (RB_BIGNUM_TYPE_P(y
)) {
1453 else if (RB_FLOAT_TYPE_P(y
)) {
1454 fy
= RFLOAT_VALUE(y
);
1457 return rb_num_coerce_bin(x
, y
, id_divmod
);
1459 flodivmod(RFLOAT_VALUE(x
), fy
, &div
, &mod
);
1462 return rb_assoc_new(a
, b
);
1467 * self ** other -> numeric
1469 * Raises +self+ to the power of +other+:
1472 * f ** 2 # => 9.8596
1473 * f ** -2 # => 0.1014239928597509
1474 * f ** 2.1 # => 11.054834900588839
1475 * f ** Rational(2, 1) # => 9.8596
1476 * f ** Complex(2, 0) # => (9.8596+0i)
1481 rb_float_pow(VALUE x
, VALUE y
)
1484 if (y
== INT2FIX(2)) {
1485 dx
= RFLOAT_VALUE(x
);
1486 return DBL2NUM(dx
* dx
);
1488 else if (FIXNUM_P(y
)) {
1489 dx
= RFLOAT_VALUE(x
);
1490 dy
= (double)FIX2LONG(y
);
1492 else if (RB_BIGNUM_TYPE_P(y
)) {
1493 dx
= RFLOAT_VALUE(x
);
1496 else if (RB_FLOAT_TYPE_P(y
)) {
1497 dx
= RFLOAT_VALUE(x
);
1498 dy
= RFLOAT_VALUE(y
);
1499 if (dx
< 0 && dy
!= round(dy
))
1500 return rb_dbl_complex_new_polar_pi(pow(-dx
, dy
), dy
);
1503 return rb_num_coerce_bin(x
, y
, idPow
);
1505 return DBL2NUM(pow(dx
, dy
));
1510 * eql?(other) -> true or false
1512 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1514 * Of the Core and Standard Library classes,
1515 * only Integer, Rational, and Complex use this implementation.
1519 * 1.eql?(1) # => true
1520 * 1.eql?(1.0) # => false
1521 * 1.eql?(Rational(1, 1)) # => false
1522 * 1.eql?(Complex(1, 0)) # => false
1524 * \Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1525 * while <tt>==</tt> does not.
1530 num_eql(VALUE x
, VALUE y
)
1532 if (TYPE(x
) != TYPE(y
)) return Qfalse
;
1534 if (RB_BIGNUM_TYPE_P(x
)) {
1535 return rb_big_eql(x
, y
);
1538 return rb_equal(x
, y
);
1543 * self <=> other -> zero or nil
1545 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1547 * No subclass in the Ruby Core or Standard Library uses this implementation.
1552 num_cmp(VALUE x
, VALUE y
)
1554 if (x
== y
) return INT2FIX(0);
1559 num_equal(VALUE x
, VALUE y
)
1562 if (x
== y
) return Qtrue
;
1563 result
= num_funcall1(y
, id_eq
, x
);
1564 return RBOOL(RTEST(result
));
1569 * self == other -> true or false
1571 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1573 * 2.0 == 2 # => true
1574 * 2.0 == 2.0 # => true
1575 * 2.0 == Rational(2, 1) # => true
1576 * 2.0 == Complex(2, 0) # => true
1578 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1580 * Related: Float#eql? (requires +other+ to be a \Float).
1585 rb_float_equal(VALUE x
, VALUE y
)
1587 volatile double a
, b
;
1589 if (RB_INTEGER_TYPE_P(y
)) {
1590 return rb_integer_float_eq(y
, x
);
1592 else if (RB_FLOAT_TYPE_P(y
)) {
1593 b
= RFLOAT_VALUE(y
);
1594 #if MSC_VERSION_BEFORE(1300)
1595 if (isnan(b
)) return Qfalse
;
1599 return num_equal(x
, y
);
1601 a
= RFLOAT_VALUE(x
);
1602 #if MSC_VERSION_BEFORE(1300)
1603 if (isnan(a
)) return Qfalse
;
1605 return RBOOL(a
== b
);
1608 #define flo_eq rb_float_equal
1609 static VALUE
rb_dbl_hash(double d
);
1615 * Returns the integer hash value for +self+.
1617 * See also Object#hash.
1623 return rb_dbl_hash(RFLOAT_VALUE(num
));
1627 rb_dbl_hash(double d
)
1629 return ST2FIX(rb_dbl_long_hash(d
));
1633 rb_dbl_cmp(double a
, double b
)
1635 if (isnan(a
) || isnan(b
)) return Qnil
;
1636 if (a
== b
) return INT2FIX(0);
1637 if (a
> b
) return INT2FIX(1);
1638 if (a
< b
) return INT2FIX(-1);
1644 * self <=> other -> -1, 0, +1, or nil
1646 * Returns a value that depends on the numeric relation
1647 * between +self+ and +other+:
1649 * - -1, if +self+ is less than +other+.
1650 * - 0, if +self+ is equal to +other+.
1651 * - 1, if +self+ is greater than +other+.
1652 * - +nil+, if the two values are incommensurate.
1657 * 2.0 <=> 2.0 # => 0
1658 * 2.0 <=> Rational(2, 1) # => 0
1659 * 2.0 <=> Complex(2, 0) # => 0
1660 * 2.0 <=> 1.9 # => 1
1661 * 2.0 <=> 2.1 # => -1
1662 * 2.0 <=> 'foo' # => nil
1664 * This is the basis for the tests in the Comparable module.
1666 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1671 flo_cmp(VALUE x
, VALUE y
)
1676 a
= RFLOAT_VALUE(x
);
1677 if (isnan(a
)) return Qnil
;
1678 if (RB_INTEGER_TYPE_P(y
)) {
1679 VALUE rel
= rb_integer_float_cmp(y
, x
);
1681 return LONG2FIX(-FIX2LONG(rel
));
1684 else if (RB_FLOAT_TYPE_P(y
)) {
1685 b
= RFLOAT_VALUE(y
);
1688 if (isinf(a
) && !UNDEF_P(i
= rb_check_funcall(y
, rb_intern("infinite?"), 0, 0))) {
1690 int j
= rb_cmpint(i
, x
, y
);
1691 j
= (a
> 0.0) ? (j
> 0 ? 0 : +1) : (j
< 0 ? 0 : -1);
1694 if (a
> 0.0) return INT2FIX(1);
1697 return rb_num_coerce_cmp(x
, y
, id_cmp
);
1699 return rb_dbl_cmp(a
, b
);
1703 rb_float_cmp(VALUE x
, VALUE y
)
1705 return NUM2INT(ensure_cmp(flo_cmp(x
, y
), x
, y
));
1710 * self > other -> true or false
1712 * Returns +true+ if +self+ is numerically greater than +other+:
1715 * 2.0 > 1.0 # => true
1716 * 2.0 > Rational(1, 2) # => true
1717 * 2.0 > 2.0 # => false
1719 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1724 rb_float_gt(VALUE x
, VALUE y
)
1728 a
= RFLOAT_VALUE(x
);
1729 if (RB_INTEGER_TYPE_P(y
)) {
1730 VALUE rel
= rb_integer_float_cmp(y
, x
);
1732 return RBOOL(-FIX2LONG(rel
) > 0);
1735 else if (RB_FLOAT_TYPE_P(y
)) {
1736 b
= RFLOAT_VALUE(y
);
1737 #if MSC_VERSION_BEFORE(1300)
1738 if (isnan(b
)) return Qfalse
;
1742 return rb_num_coerce_relop(x
, y
, '>');
1744 #if MSC_VERSION_BEFORE(1300)
1745 if (isnan(a
)) return Qfalse
;
1747 return RBOOL(a
> b
);
1752 * self >= other -> true or false
1754 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1756 * 2.0 >= 1 # => true
1757 * 2.0 >= 1.0 # => true
1758 * 2.0 >= Rational(1, 2) # => true
1759 * 2.0 >= 2.0 # => true
1760 * 2.0 >= 2.1 # => false
1762 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1767 flo_ge(VALUE x
, VALUE y
)
1771 a
= RFLOAT_VALUE(x
);
1772 if (RB_TYPE_P(y
, T_FIXNUM
) || RB_BIGNUM_TYPE_P(y
)) {
1773 VALUE rel
= rb_integer_float_cmp(y
, x
);
1775 return RBOOL(-FIX2LONG(rel
) >= 0);
1778 else if (RB_FLOAT_TYPE_P(y
)) {
1779 b
= RFLOAT_VALUE(y
);
1780 #if MSC_VERSION_BEFORE(1300)
1781 if (isnan(b
)) return Qfalse
;
1785 return rb_num_coerce_relop(x
, y
, idGE
);
1787 #if MSC_VERSION_BEFORE(1300)
1788 if (isnan(a
)) return Qfalse
;
1790 return RBOOL(a
>= b
);
1795 * self < other -> true or false
1797 * Returns +true+ if +self+ is numerically less than +other+:
1800 * 2.0 < 3.0 # => true
1801 * 2.0 < Rational(3, 1) # => true
1802 * 2.0 < 2.0 # => false
1804 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1809 flo_lt(VALUE x
, VALUE y
)
1813 a
= RFLOAT_VALUE(x
);
1814 if (RB_INTEGER_TYPE_P(y
)) {
1815 VALUE rel
= rb_integer_float_cmp(y
, x
);
1817 return RBOOL(-FIX2LONG(rel
) < 0);
1820 else if (RB_FLOAT_TYPE_P(y
)) {
1821 b
= RFLOAT_VALUE(y
);
1822 #if MSC_VERSION_BEFORE(1300)
1823 if (isnan(b
)) return Qfalse
;
1827 return rb_num_coerce_relop(x
, y
, '<');
1829 #if MSC_VERSION_BEFORE(1300)
1830 if (isnan(a
)) return Qfalse
;
1832 return RBOOL(a
< b
);
1837 * self <= other -> true or false
1839 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1841 * 2.0 <= 3 # => true
1842 * 2.0 <= 3.0 # => true
1843 * 2.0 <= Rational(3, 1) # => true
1844 * 2.0 <= 2.0 # => true
1845 * 2.0 <= 1.0 # => false
1847 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1852 flo_le(VALUE x
, VALUE y
)
1856 a
= RFLOAT_VALUE(x
);
1857 if (RB_INTEGER_TYPE_P(y
)) {
1858 VALUE rel
= rb_integer_float_cmp(y
, x
);
1860 return RBOOL(-FIX2LONG(rel
) <= 0);
1863 else if (RB_FLOAT_TYPE_P(y
)) {
1864 b
= RFLOAT_VALUE(y
);
1865 #if MSC_VERSION_BEFORE(1300)
1866 if (isnan(b
)) return Qfalse
;
1870 return rb_num_coerce_relop(x
, y
, idLE
);
1872 #if MSC_VERSION_BEFORE(1300)
1873 if (isnan(a
)) return Qfalse
;
1875 return RBOOL(a
<= b
);
1880 * eql?(other) -> true or false
1882 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1883 * +false+ otherwise:
1885 * 2.0.eql?(2.0) # => true
1886 * 2.0.eql?(1.0) # => false
1887 * 2.0.eql?(1) # => false
1888 * 2.0.eql?(Rational(2, 1)) # => false
1889 * 2.0.eql?(Complex(2, 0)) # => false
1891 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1893 * Related: Float#== (performs type conversions).
1897 rb_float_eql(VALUE x
, VALUE y
)
1899 if (RB_FLOAT_TYPE_P(y
)) {
1900 double a
= RFLOAT_VALUE(x
);
1901 double b
= RFLOAT_VALUE(y
);
1902 #if MSC_VERSION_BEFORE(1300)
1903 if (isnan(a
) || isnan(b
)) return Qfalse
;
1905 return RBOOL(a
== b
);
1910 #define flo_eql rb_float_eql
1913 rb_float_abs(VALUE flt
)
1915 double val
= fabs(RFLOAT_VALUE(flt
));
1916 return DBL2NUM(val
);
1921 * nan? -> true or false
1923 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1927 * f = 0.0/0.0 #=> NaN
1932 flo_is_nan_p(VALUE num
)
1934 double value
= RFLOAT_VALUE(num
);
1936 return RBOOL(isnan(value
));
1941 * infinite? -> -1, 1, or nil
1945 * - 1, if +self+ is <tt>Infinity</tt>.
1946 * - -1 if +self+ is <tt>-Infinity</tt>.
1947 * - +nil+, otherwise.
1951 * f = 1.0/0.0 # => Infinity
1952 * f.infinite? # => 1
1953 * f = -1.0/0.0 # => -Infinity
1954 * f.infinite? # => -1
1956 * f.infinite? # => nil
1957 * f = 0.0/0.0 # => NaN
1958 * f.infinite? # => nil
1963 rb_flo_is_infinite_p(VALUE num
)
1965 double value
= RFLOAT_VALUE(num
);
1968 return INT2FIX( value
< 0 ? -1 : 1 );
1976 * finite? -> true or false
1978 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1979 * +false+ otherwise:
1982 * f.finite? # => true
1983 * f = 1.0/0.0 # => Infinity
1984 * f.finite? # => false
1985 * f = -1.0/0.0 # => -Infinity
1986 * f.finite? # => false
1987 * f = 0.0/0.0 # => NaN
1988 * f.finite? # => false
1993 rb_flo_is_finite_p(VALUE num
)
1995 double value
= RFLOAT_VALUE(num
);
1997 return RBOOL(isfinite(value
));
2001 flo_nextafter(VALUE flo
, double value
)
2005 y
= nextafter(x
, value
);
2011 * next_float -> float
2013 * Returns the next-larger representable \Float.
2015 * These examples show the internally stored values (64-bit hexadecimal)
2016 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
2018 * f = 0.0 # 0x0000000000000000
2019 * f.next_float # 0x0000000000000001
2021 * f = 0.01 # 0x3f847ae147ae147b
2022 * f.next_float # 0x3f847ae147ae147c
2024 * In the remaining examples here, the output is shown in the usual way
2027 * 0.01.next_float # => 0.010000000000000002
2028 * 1.0.next_float # => 1.0000000000000002
2029 * 100.0.next_float # => 100.00000000000001
2032 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2036 * 0 0x1.47ae147ae147bp-7 0.01
2037 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
2038 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
2039 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
2041 * f = 0.0; 100.times { f += 0.1 }
2042 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
2043 * 10-f # => 1.9539925233402755e-14 # the floating point error.
2044 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
2045 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
2046 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
2047 * "%a" % 10 # => "0x1.4p+3"
2048 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
2050 * Related: Float#prev_float
2054 flo_next_float(VALUE vx
)
2056 return flo_nextafter(vx
, HUGE_VAL
);
2061 * float.prev_float -> float
2063 * Returns the next-smaller representable \Float.
2065 * These examples show the internally stored values (64-bit hexadecimal)
2066 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
2068 * f = 5e-324 # 0x0000000000000001
2069 * f.prev_float # 0x0000000000000000
2071 * f = 0.01 # 0x3f847ae147ae147b
2072 * f.prev_float # 0x3f847ae147ae147a
2074 * In the remaining examples here, the output is shown in the usual way
2077 * 0.01.prev_float # => 0.009999999999999998
2078 * 1.0.prev_float # => 0.9999999999999999
2079 * 100.0.prev_float # => 99.99999999999999
2082 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2086 * 0 0x1.47ae147ae147bp-7 0.01
2087 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
2088 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
2089 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
2091 * Related: Float#next_float.
2095 flo_prev_float(VALUE vx
)
2097 return flo_nextafter(vx
, -HUGE_VAL
);
2101 rb_float_floor(VALUE num
, int ndigits
)
2104 number
= RFLOAT_VALUE(num
);
2105 if (number
== 0.0) {
2106 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2111 frexp(number
, &binexp
);
2112 if (float_round_overflow(ndigits
, binexp
)) return num
;
2113 if (number
> 0.0 && float_round_underflow(ndigits
, binexp
))
2114 return DBL2NUM(0.0);
2115 f
= pow(10, ndigits
);
2116 mul
= floor(number
* f
);
2117 res
= (mul
+ 1) / f
;
2120 return DBL2NUM(res
);
2123 num
= dbl2ival(floor(number
));
2124 if (ndigits
< 0) num
= rb_int_floor(num
, ndigits
);
2130 flo_ndigits(int argc
, VALUE
*argv
)
2132 if (rb_check_arity(argc
, 0, 1)) {
2133 return NUM2INT(argv
[0]);
2142 * floor(ndigits = 0) -> float or integer
2144 * Returns a float or integer that is a "floor" value for `self`,
2145 * as specified by `ndigits`,
2147 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2149 * When `self` is zero,
2150 * returns a zero value:
2151 * a float if `ndigits` is positive,
2152 * an integer otherwise:
2156 * f.floor(20) # => 0.0
2158 * f.floor(-20) # => 0
2161 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2162 * digits after the decimal point (as available):
2166 * f.floor(1) # => 12345.6
2167 * f.floor(3) # => 12345.678
2168 * f.floor(30) # => 12345.6789
2170 * f.floor(1) # => -12345.7
2171 * f.floor(3) # => -12345.679
2172 * f.floor(30) # => -12345.6789
2175 * When `self` is non-zero and `ndigits` is non-positive,
2176 * returns an integer value based on a computed granularity:
2178 * - The granularity is `10 ** ndigits.abs`.
2179 * - The returned value is the largest multiple of the granularity
2180 * that is less than or equal to `self`.
2182 * Examples with positive `self`:
2184 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2185 * |--------:|------------:|--------------------------:|
2187 * | -1 | 10 | 12340 |
2188 * | -2 | 100 | 12300 |
2189 * | -3 | 1000 | 12000 |
2190 * | -4 | 10000 | 10000 |
2191 * | -5 | 100000 | 0 |
2193 * Examples with negative `self`:
2195 * | ndigits | Granularity | -12345.6789.floor(ndigits) |
2196 * |--------:|------------:|---------------------------:|
2197 * | 0 | 1 | -12346 |
2198 * | -1 | 10 | -12350 |
2199 * | -2 | 100 | -12400 |
2200 * | -3 | 1000 | -13000 |
2201 * | -4 | 10000 | -20000 |
2202 * | -5 | 100000 | -100000 |
2203 * | -6 | 1000000 | -1000000 |
2205 * Note that the limited precision of floating-point arithmetic
2206 * may lead to surprising results:
2209 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2212 * Related: Float#ceil.
2217 flo_floor(int argc
, VALUE
*argv
, VALUE num
)
2219 int ndigits
= flo_ndigits(argc
, argv
);
2220 return rb_float_floor(num
, ndigits
);
2227 * ceil(ndigits = 0) -> float or integer
2229 * Returns a numeric that is a "ceiling" value for `self`,
2230 * as specified by the given `ndigits`,
2232 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2234 * When `ndigits` is positive, returns a Float with `ndigits`
2235 * decimal digits after the decimal point
2236 * (as available, but no fewer than 1):
2240 * f.ceil(1) # => 12345.7
2241 * f.ceil(3) # => 12345.679
2242 * f.ceil(30) # => 12345.6789
2244 * f.ceil(1) # => -12345.6
2245 * f.ceil(3) # => -12345.678
2246 * f.ceil(30) # => -12345.6789
2248 * f.ceil(1) # => 0.0
2249 * f.ceil(100) # => 0.0
2252 * When `ndigits` is non-positive,
2253 * returns an Integer based on a computed granularity:
2255 * - The granularity is `10 ** ndigits.abs`.
2256 * - The returned value is the largest multiple of the granularity
2257 * that is less than or equal to `self`.
2259 * Examples with positive `self`:
2261 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2262 * |--------:|------------:|-------------------------:|
2264 * | -1 | 10 | 12350 |
2265 * | -2 | 100 | 12400 |
2266 * | -3 | 1000 | 13000 |
2267 * | -4 | 10000 | 20000 |
2268 * | -5 | 100000 | 100000 |
2270 * Examples with negative `self`:
2272 * | ndigits | Granularity | -12345.6789.ceil(ndigits) |
2273 * |--------:|------------:|--------------------------:|
2274 * | 0 | 1 | -12345 |
2275 * | -1 | 10 | -12340 |
2276 * | -2 | 100 | -12300 |
2277 * | -3 | 1000 | -12000 |
2278 * | -4 | 10000 | -10000 |
2279 * | -5 | 100000 | 0 |
2281 * When `self` is zero and `ndigits` is non-positive,
2282 * returns Integer zero:
2285 * 0.0.ceil(0) # => 0
2286 * 0.0.ceil(-1) # => 0
2287 * 0.0.ceil(-2) # => 0
2290 * Note that the limited precision of floating-point arithmetic
2291 * may lead to surprising results:
2294 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2297 * Related: Float#floor.
2302 flo_ceil(int argc
, VALUE
*argv
, VALUE num
)
2304 int ndigits
= flo_ndigits(argc
, argv
);
2305 return rb_float_ceil(num
, ndigits
);
2309 rb_float_ceil(VALUE num
, int ndigits
)
2313 number
= RFLOAT_VALUE(num
);
2314 if (number
== 0.0) {
2315 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2319 frexp(number
, &binexp
);
2320 if (float_round_overflow(ndigits
, binexp
)) return num
;
2321 if (number
< 0.0 && float_round_underflow(ndigits
, binexp
))
2322 return DBL2NUM(0.0);
2323 f
= pow(10, ndigits
);
2324 f
= ceil(number
* f
) / f
;
2328 num
= dbl2ival(ceil(number
));
2329 if (ndigits
< 0) num
= rb_int_ceil(num
, ndigits
);
2335 int_round_zero_p(VALUE num
, int ndigits
)
2338 /* If 10**N / 2 > num, then return 0 */
2339 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2340 if (FIXNUM_P(num
)) {
2341 bytes
= sizeof(long);
2343 else if (RB_BIGNUM_TYPE_P(num
)) {
2344 bytes
= rb_big_size(num
);
2347 bytes
= NUM2LONG(rb_funcall(num
, idSize
, 0));
2349 return (-0.415241 * ndigits
- 0.125 > bytes
);
2353 int_round_half_even(SIGNED_VALUE x
, SIGNED_VALUE y
)
2355 SIGNED_VALUE z
= +(x
+ y
/ 2) / y
;
2356 if ((z
* y
- x
) * 2 == y
) {
2363 int_round_half_up(SIGNED_VALUE x
, SIGNED_VALUE y
)
2365 return (x
+ y
/ 2) / y
* y
;
2369 int_round_half_down(SIGNED_VALUE x
, SIGNED_VALUE y
)
2371 return (x
+ y
/ 2 - 1) / y
* y
;
2375 int_half_p_half_even(VALUE num
, VALUE n
, VALUE f
)
2377 return (int)rb_int_odd_p(rb_int_idiv(n
, f
));
2381 int_half_p_half_up(VALUE num
, VALUE n
, VALUE f
)
2383 return int_pos_p(num
);
2387 int_half_p_half_down(VALUE num
, VALUE n
, VALUE f
)
2389 return int_neg_p(num
);
2393 * Assumes num is an \Integer, ndigits <= 0
2396 rb_int_round(VALUE num
, int ndigits
, enum ruby_num_rounding_mode mode
)
2400 if (int_round_zero_p(num
, ndigits
)) {
2404 f
= int_pow(10, -ndigits
);
2405 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2406 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2409 x
= ROUND_CALL(mode
, int_round
, (x
, y
));
2413 if (RB_FLOAT_TYPE_P(f
)) {
2414 /* then int_pow overflow */
2417 h
= rb_int_idiv(f
, INT2FIX(2));
2418 r
= rb_int_modulo(num
, f
);
2419 n
= rb_int_minus(num
, r
);
2420 r
= rb_int_cmp(r
, h
);
2421 if (FIXNUM_POSITIVE_P(r
) ||
2422 (FIXNUM_ZERO_P(r
) && ROUND_CALL(mode
, int_half_p
, (num
, n
, f
)))) {
2423 n
= rb_int_plus(n
, f
);
2429 rb_int_floor(VALUE num
, int ndigits
)
2431 VALUE f
= int_pow(10, -ndigits
);
2432 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2433 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2435 if (neg
) x
= -x
+ y
- 1;
2441 bool neg
= int_neg_p(num
);
2442 if (neg
) num
= rb_int_minus(rb_int_plus(rb_int_uminus(num
), f
), INT2FIX(1));
2443 num
= rb_int_mul(rb_int_div(num
, f
), f
);
2444 if (neg
) num
= rb_int_uminus(num
);
2450 rb_int_ceil(VALUE num
, int ndigits
)
2452 VALUE f
= int_pow(10, -ndigits
);
2453 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2454 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2463 bool neg
= int_neg_p(num
);
2465 num
= rb_int_uminus(num
);
2467 num
= rb_int_plus(num
, rb_int_minus(f
, INT2FIX(1)));
2468 num
= rb_int_mul(rb_int_div(num
, f
), f
);
2469 if (neg
) num
= rb_int_uminus(num
);
2475 rb_int_truncate(VALUE num
, int ndigits
)
2480 if (int_round_zero_p(num
, ndigits
))
2482 f
= int_pow(10, -ndigits
);
2483 if (FIXNUM_P(num
) && FIXNUM_P(f
)) {
2484 SIGNED_VALUE x
= FIX2LONG(num
), y
= FIX2LONG(f
);
2491 if (RB_FLOAT_TYPE_P(f
)) {
2492 /* then int_pow overflow */
2495 m
= rb_int_modulo(num
, f
);
2496 if (int_neg_p(num
)) {
2497 return rb_int_plus(num
, rb_int_minus(f
, m
));
2500 return rb_int_minus(num
, m
);
2506 * round(ndigits = 0, half: :up) -> integer or float
2508 * Returns +self+ rounded to the nearest value with
2509 * a precision of +ndigits+ decimal digits.
2511 * When +ndigits+ is non-negative, returns a float with +ndigits+
2512 * after the decimal point (as available):
2515 * f.round(1) # => 12345.7
2516 * f.round(3) # => 12345.679
2518 * f.round(1) # => -12345.7
2519 * f.round(3) # => -12345.679
2521 * When +ndigits+ is negative, returns an integer
2522 * with at least <tt>ndigits.abs</tt> trailing zeros:
2525 * f.round(0) # => 12346
2526 * f.round(-3) # => 12000
2528 * f.round(0) # => -12346
2529 * f.round(-3) # => -12000
2531 * If keyword argument +half+ is given,
2532 * and +self+ is equidistant from the two candidate values,
2533 * the rounding is according to the given +half+ value:
2535 * - +:up+ or +nil+: round away from zero:
2537 * 2.5.round(half: :up) # => 3
2538 * 3.5.round(half: :up) # => 4
2539 * (-2.5).round(half: :up) # => -3
2541 * - +:down+: round toward zero:
2543 * 2.5.round(half: :down) # => 2
2544 * 3.5.round(half: :down) # => 3
2545 * (-2.5).round(half: :down) # => -2
2547 * - +:even+: round toward the candidate whose last nonzero digit is even:
2549 * 2.5.round(half: :even) # => 2
2550 * 3.5.round(half: :even) # => 4
2551 * (-2.5).round(half: :even) # => -2
2553 * Raises and exception if the value for +half+ is invalid.
2555 * Related: Float#truncate.
2560 flo_round(int argc
, VALUE
*argv
, VALUE num
)
2562 double number
, f
, x
;
2565 enum ruby_num_rounding_mode mode
;
2567 if (rb_scan_args(argc
, argv
, "01:", &nd
, &opt
)) {
2568 ndigits
= NUM2INT(nd
);
2570 mode
= rb_num_get_rounding_option(opt
);
2571 number
= RFLOAT_VALUE(num
);
2572 if (number
== 0.0) {
2573 return ndigits
> 0 ? DBL2NUM(number
) : INT2FIX(0);
2576 return rb_int_round(flo_to_i(num
), ndigits
, mode
);
2579 x
= ROUND_CALL(mode
, round
, (number
, 1.0));
2582 if (isfinite(number
)) {
2584 frexp(number
, &binexp
);
2585 if (float_round_overflow(ndigits
, binexp
)) return num
;
2586 if (float_round_underflow(ndigits
, binexp
)) return DBL2NUM(0);
2588 /* In this case, pow(10, ndigits) may not be accurate. */
2589 return rb_flo_round_by_rational(argc
, argv
, num
);
2591 f
= pow(10, ndigits
);
2592 x
= ROUND_CALL(mode
, round
, (number
, f
));
2593 return DBL2NUM(x
/ f
);
2599 float_round_overflow(int ndigits
, int binexp
)
2601 enum {float_dig
= DBL_DIG
+2};
2603 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2604 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2605 Recall that up to float_dig digits can be needed to represent a double,
2606 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2607 will be an integer and thus the result is the original number.
2608 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2609 if ndigits + exp < 0, the result is 0.
2611 2 ** (binexp-1) <= |number| < 2 ** binexp
2612 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2613 If binexp >= 0, and since log_2(10) = 3.322259:
2614 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2615 floor(binexp/4) <= exp <= ceil(binexp/3)
2616 If binexp <= 0, swap the /4 and the /3
2617 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2618 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2620 if (ndigits
>= float_dig
- (binexp
> 0 ? binexp
/ 4 : binexp
/ 3 - 1)) {
2627 float_round_underflow(int ndigits
, int binexp
)
2629 if (ndigits
< - (binexp
> 0 ? binexp
/ 3 + 1 : binexp
/ 4)) {
2639 * Returns +self+ truncated to an Integer.
2642 * (-1.2).to_i # => -1
2644 * Note that the limited precision of floating-point arithmetic
2645 * may lead to surprising results:
2647 * (0.3 / 0.1).to_i # => 2 (!)
2654 double f
= RFLOAT_VALUE(num
);
2656 if (f
> 0.0) f
= floor(f
);
2657 if (f
< 0.0) f
= ceil(f
);
2664 * truncate(ndigits = 0) -> float or integer
2666 * Returns +self+ truncated (toward zero) to
2667 * a precision of +ndigits+ decimal digits.
2669 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2670 * after the decimal point (as available):
2673 * f.truncate(1) # => 12345.6
2674 * f.truncate(3) # => 12345.678
2676 * f.truncate(1) # => -12345.6
2677 * f.truncate(3) # => -12345.678
2679 * When +ndigits+ is negative, returns an integer
2680 * with at least <tt>ndigits.abs</tt> trailing zeros:
2683 * f.truncate(0) # => 12345
2684 * f.truncate(-3) # => 12000
2686 * f.truncate(0) # => -12345
2687 * f.truncate(-3) # => -12000
2689 * Note that the limited precision of floating-point arithmetic
2690 * may lead to surprising results:
2692 * (0.3 / 0.1).truncate #=> 2 (!)
2694 * Related: Float#round.
2698 flo_truncate(int argc
, VALUE
*argv
, VALUE num
)
2700 if (signbit(RFLOAT_VALUE(num
)))
2701 return flo_ceil(argc
, argv
, num
);
2703 return flo_floor(argc
, argv
, num
);
2708 * floor(ndigits = 0) -> float or integer
2710 * Returns the largest float or integer that is less than or equal to +self+,
2711 * as specified by the given `ndigits`,
2713 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2715 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2717 * Related: #ceil, Float#floor.
2721 num_floor(int argc
, VALUE
*argv
, VALUE num
)
2723 return flo_floor(argc
, argv
, rb_Float(num
));
2728 * ceil(ndigits = 0) -> float or integer
2730 * Returns the smallest float or integer that is greater than or equal to +self+,
2731 * as specified by the given `ndigits`,
2733 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2735 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2737 * Related: #floor, Float#ceil.
2741 num_ceil(int argc
, VALUE
*argv
, VALUE num
)
2743 return flo_ceil(argc
, argv
, rb_Float(num
));
2748 * round(digits = 0) -> integer or float
2750 * Returns +self+ rounded to the nearest value with
2751 * a precision of +digits+ decimal digits.
2753 * \Numeric implements this by converting +self+ to a Float and
2754 * invoking Float#round.
2758 num_round(int argc
, VALUE
* argv
, VALUE num
)
2760 return flo_round(argc
, argv
, rb_Float(num
));
2765 * truncate(digits = 0) -> integer or float
2767 * Returns +self+ truncated (toward zero) to
2768 * a precision of +digits+ decimal digits.
2770 * \Numeric implements this by converting +self+ to a Float and
2771 * invoking Float#truncate.
2775 num_truncate(int argc
, VALUE
*argv
, VALUE num
)
2777 return flo_truncate(argc
, argv
, rb_Float(num
));
2781 ruby_float_step_size(double beg
, double end
, double unit
, int excl
)
2783 const double epsilon
= DBL_EPSILON
;
2790 return unit
> 0 ? beg
<= end
: beg
>= end
;
2792 n
= (end
- beg
)/unit
;
2793 err
= (fabs(beg
) + fabs(end
) + fabs(end
-beg
)) / fabs(unit
) * epsilon
;
2794 if (err
>0.5) err
=0.5;
2801 d
= +((n
+ 1) * unit
) + beg
;
2806 else if (beg
> end
) {
2814 d
= +((n
+ 1) * unit
) + beg
;
2819 else if (beg
> end
) {
2828 ruby_float_step(VALUE from
, VALUE to
, VALUE step
, int excl
, int allow_endless
)
2830 if (RB_FLOAT_TYPE_P(from
) || RB_FLOAT_TYPE_P(to
) || RB_FLOAT_TYPE_P(step
)) {
2831 double unit
= NUM2DBL(step
);
2832 double beg
= NUM2DBL(from
);
2833 double end
= (allow_endless
&& NIL_P(to
)) ? (unit
< 0 ? -1 : 1)*HUGE_VAL
: NUM2DBL(to
);
2834 double n
= ruby_float_step_size(beg
, end
, unit
, excl
);
2838 /* if unit is infinity, i*unit+beg is NaN */
2839 if (n
) rb_yield(DBL2NUM(beg
));
2841 else if (unit
== 0) {
2842 VALUE val
= DBL2NUM(beg
);
2847 for (i
=0; i
<n
; i
++) {
2848 double d
= i
*unit
+beg
;
2849 if (unit
>= 0 ? end
< d
: d
< end
) d
= end
;
2850 rb_yield(DBL2NUM(d
));
2859 ruby_num_interval_step_size(VALUE from
, VALUE to
, VALUE step
, int excl
)
2861 if (FIXNUM_P(from
) && FIXNUM_P(to
) && FIXNUM_P(step
)) {
2864 diff
= FIX2LONG(step
);
2866 return DBL2NUM(HUGE_VAL
);
2868 delta
= FIX2LONG(to
) - FIX2LONG(from
);
2879 return ULONG2NUM(delta
/ diff
+ 1UL);
2881 else if (RB_FLOAT_TYPE_P(from
) || RB_FLOAT_TYPE_P(to
) || RB_FLOAT_TYPE_P(step
)) {
2882 double n
= ruby_float_step_size(NUM2DBL(from
), NUM2DBL(to
), NUM2DBL(step
), excl
);
2884 if (isinf(n
)) return DBL2NUM(n
);
2885 if (POSFIXABLE(n
)) return LONG2FIX((long)n
);
2886 return rb_dbl2big(n
);
2891 switch (rb_cmpint(rb_num_coerce_cmp(step
, INT2FIX(0), id_cmp
), step
, INT2FIX(0))) {
2892 case 0: return DBL2NUM(HUGE_VAL
);
2893 case -1: cmp
= '<'; break;
2895 if (RTEST(rb_funcall(from
, cmp
, 1, to
))) return INT2FIX(0);
2896 result
= rb_funcall(rb_funcall(to
, '-', 1, from
), id_div
, 1, step
);
2897 if (!excl
|| RTEST(rb_funcall(to
, cmp
, 1, rb_funcall(from
, '+', 1, rb_funcall(result
, '*', 1, step
))))) {
2898 result
= rb_funcall(result
, '+', 1, INT2FIX(1));
2905 num_step_negative_p(VALUE num
)
2908 VALUE zero
= INT2FIX(0);
2911 if (FIXNUM_P(num
)) {
2912 if (method_basic_p(rb_cInteger
))
2913 return (SIGNED_VALUE
)num
< 0;
2915 else if (RB_BIGNUM_TYPE_P(num
)) {
2916 if (method_basic_p(rb_cInteger
))
2917 return BIGNUM_NEGATIVE_P(num
);
2920 r
= rb_check_funcall(num
, '>', 1, &zero
);
2922 coerce_failed(num
, INT2FIX(0));
2928 num_step_extract_args(int argc
, const VALUE
*argv
, VALUE
*to
, VALUE
*step
, VALUE
*by
)
2932 argc
= rb_scan_args(argc
, argv
, "02:", to
, step
, &hash
);
2938 rb_get_kwargs(hash
, keys
, 0, 2, values
);
2939 if (!UNDEF_P(values
[0])) {
2940 if (argc
> 0) rb_raise(rb_eArgError
, "to is given twice");
2943 if (!UNDEF_P(values
[1])) {
2944 if (argc
> 1) rb_raise(rb_eArgError
, "step is given twice");
2953 num_step_check_fix_args(int argc
, VALUE
*to
, VALUE
*step
, VALUE by
, int fix_nil
, int allow_zero_step
)
2961 if (argc
> 1 && NIL_P(*step
)) {
2962 rb_raise(rb_eTypeError
, "step must be numeric");
2965 if (!allow_zero_step
&& rb_equal(*step
, INT2FIX(0))) {
2966 rb_raise(rb_eArgError
, "step can't be 0");
2971 desc
= num_step_negative_p(*step
);
2972 if (fix_nil
&& NIL_P(*to
)) {
2973 *to
= desc
? DBL2NUM(-HUGE_VAL
) : DBL2NUM(HUGE_VAL
);
2979 num_step_scan_args(int argc
, const VALUE
*argv
, VALUE
*to
, VALUE
*step
, int fix_nil
, int allow_zero_step
)
2982 argc
= num_step_extract_args(argc
, argv
, to
, step
, &by
);
2983 return num_step_check_fix_args(argc
, to
, step
, by
, fix_nil
, allow_zero_step
);
2987 num_step_size(VALUE from
, VALUE args
, VALUE eobj
)
2990 int argc
= args
? RARRAY_LENINT(args
) : 0;
2991 const VALUE
*argv
= args
? RARRAY_CONST_PTR(args
) : 0;
2993 num_step_scan_args(argc
, argv
, &to
, &step
, TRUE
, FALSE
);
2995 return ruby_num_interval_step_size(from
, to
, step
, FALSE
);
3000 * step(to = nil, by = 1) {|n| ... } -> self
3001 * step(to = nil, by = 1) -> enumerator
3002 * step(to = nil, by: 1) {|n| ... } -> self
3003 * step(to = nil, by: 1) -> enumerator
3004 * step(by: 1, to: ) {|n| ... } -> self
3005 * step(by: 1, to: ) -> enumerator
3006 * step(by: , to: nil) {|n| ... } -> self
3007 * step(by: , to: nil) -> enumerator
3009 * Generates a sequence of numbers; with a block given, traverses the sequence.
3011 * Of the Core and Standard Library classes,
3012 * Integer, Float, and Rational use this implementation.
3017 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
3018 * squares # => [1, 9, 25, 49, 81]
3020 * The generated sequence:
3022 * - Begins with +self+.
3023 * - Continues at intervals of +by+ (which may not be zero).
3024 * - Ends with the last number that is within or equal to +to+;
3025 * that is, less than or equal to +to+ if +by+ is positive,
3026 * greater than or equal to +to+ if +by+ is negative.
3027 * If +to+ is +nil+, the sequence is of infinite length.
3029 * If a block is given, calls the block with each number in the sequence;
3030 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
3032 * <b>Keyword Arguments</b>
3034 * With keyword arguments +by+ and +to+,
3035 * their values (or defaults) determine the step and limit:
3037 * # Both keywords given.
3039 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
3040 * squares # => [16, 36, 64, 100]
3042 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
3043 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
3045 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
3046 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3049 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
3050 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3052 * # Only keyword to given.
3054 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
3055 * squares # => [16, 25, 36, 49, 64, 81, 100]
3058 * # Only keyword by given
3060 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3061 * squares # => [16, 36, 64, 100, 144]
3064 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3065 * e.class # => Enumerator::ArithmeticSequence
3067 * <b>Positional Arguments</b>
3069 * With optional positional arguments +to+ and +by+,
3070 * their values (or defaults) determine the step and limit:
3073 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3074 * squares # => [16, 36, 64, 100]
3076 * 4.step(10) {|i| squares.push(i*i) }
3077 * squares # => [16, 25, 36, 49, 64, 81, 100]
3079 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3080 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3082 * <b>Implementation Notes</b>
3084 * If all the arguments are integers, the loop operates using an integer
3087 * If any of the arguments are floating point numbers, all are converted
3088 * to floats, and the loop is executed
3089 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3090 * where <i>n = (limit - self)/step</i>.
3095 num_step(int argc
, VALUE
*argv
, VALUE from
)
3100 if (!rb_block_given_p()) {
3103 num_step_extract_args(argc
, argv
, &to
, &step
, &by
);
3110 else if (rb_equal(step
, INT2FIX(0))) {
3111 rb_raise(rb_eArgError
, "step can't be 0");
3113 if ((NIL_P(to
) || rb_obj_is_kind_of(to
, rb_cNumeric
)) &&
3114 rb_obj_is_kind_of(step
, rb_cNumeric
)) {
3115 return rb_arith_seq_new(from
, ID2SYM(rb_frame_this_func()), argc
, argv
,
3116 num_step_size
, from
, to
, step
, FALSE
);
3119 return SIZED_ENUMERATOR_KW(from
, 2, ((VALUE
[2]){to
, step
}), num_step_size
, FALSE
);
3122 desc
= num_step_scan_args(argc
, argv
, &to
, &step
, TRUE
, FALSE
);
3123 if (rb_equal(step
, INT2FIX(0))) {
3126 else if (RB_FLOAT_TYPE_P(to
)) {
3127 double f
= RFLOAT_VALUE(to
);
3128 inf
= isinf(f
) && (signbit(f
) ? desc
: !desc
);
3132 if (FIXNUM_P(from
) && (inf
|| FIXNUM_P(to
)) && FIXNUM_P(step
)) {
3133 long i
= FIX2LONG(from
);
3134 long diff
= FIX2LONG(step
);
3138 rb_yield(LONG2FIX(i
));
3141 long end
= FIX2LONG(to
);
3144 for (; i
>= end
; i
+= diff
)
3145 rb_yield(LONG2FIX(i
));
3148 for (; i
<= end
; i
+= diff
)
3149 rb_yield(LONG2FIX(i
));
3153 else if (!ruby_float_step(from
, to
, step
, FALSE
, FALSE
)) {
3157 for (;; i
= rb_funcall(i
, '+', 1, step
))
3161 ID cmp
= desc
? '<' : '>';
3163 for (; !RTEST(rb_funcall(i
, cmp
, 1, to
)); i
= rb_funcall(i
, '+', 1, step
))
3171 out_of_range_float(char (*pbuf
)[24], VALUE val
)
3173 char *const buf
= *pbuf
;
3176 snprintf(buf
, sizeof(*pbuf
), "%-.10g", RFLOAT_VALUE(val
));
3177 if ((s
= strchr(buf
, ' ')) != 0) *s
= '\0';
3181 #define FLOAT_OUT_OF_RANGE(val, type) do { \
3183 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3184 out_of_range_float(&buf, (val))); \
3187 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3188 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3189 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3190 #define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3191 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3193 LONG_MIN_MINUS_ONE < (n))
3196 rb_num2long(VALUE val
)
3200 rb_raise(rb_eTypeError
, "no implicit conversion from nil to integer");
3203 if (FIXNUM_P(val
)) return FIX2LONG(val
);
3205 else if (RB_FLOAT_TYPE_P(val
)) {
3206 if (RFLOAT_VALUE(val
) < LONG_MAX_PLUS_ONE
3207 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val
))) {
3208 return (long)RFLOAT_VALUE(val
);
3211 FLOAT_OUT_OF_RANGE(val
, "integer");
3214 else if (RB_BIGNUM_TYPE_P(val
)) {
3215 return rb_big2long(val
);
3218 val
= rb_to_int(val
);
3223 static unsigned long
3224 rb_num2ulong_internal(VALUE val
, int *wrap_p
)
3228 rb_raise(rb_eTypeError
, "no implicit conversion of nil into Integer");
3231 if (FIXNUM_P(val
)) {
3232 long l
= FIX2LONG(val
); /* this is FIX2LONG, intended */
3235 return (unsigned long)l
;
3237 else if (RB_FLOAT_TYPE_P(val
)) {
3238 double d
= RFLOAT_VALUE(val
);
3239 if (d
< ULONG_MAX_PLUS_ONE
&& LONG_MIN_MINUS_ONE_IS_LESS_THAN(d
)) {
3241 *wrap_p
= d
<= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3243 return (unsigned long)d
;
3244 return (unsigned long)(long)d
;
3247 FLOAT_OUT_OF_RANGE(val
, "integer");
3250 else if (RB_BIGNUM_TYPE_P(val
)) {
3252 unsigned long ul
= rb_big2ulong(val
);
3254 *wrap_p
= BIGNUM_NEGATIVE_P(val
);
3259 val
= rb_to_int(val
);
3265 rb_num2ulong(VALUE val
)
3267 return rb_num2ulong_internal(val
, NULL
);
3271 rb_out_of_int(SIGNED_VALUE num
)
3273 rb_raise(rb_eRangeError
, "integer %"PRIdVALUE
" too %s to convert to 'int'",
3274 num
, num
< 0 ? "small" : "big");
3277 #if SIZEOF_INT < SIZEOF_LONG
3281 if ((long)(int)num
!= num
) {
3287 check_uint(unsigned long num
, int sign
)
3291 if (num
< (unsigned long)INT_MIN
)
3292 rb_raise(rb_eRangeError
, "integer %ld too small to convert to 'unsigned int'", (long)num
);
3297 rb_raise(rb_eRangeError
, "integer %lu too big to convert to 'unsigned int'", num
);
3302 rb_num2int(VALUE val
)
3304 long num
= rb_num2long(val
);
3311 rb_fix2int(VALUE val
)
3313 long num
= FIXNUM_P(val
)?FIX2LONG(val
):rb_num2long(val
);
3320 rb_num2uint(VALUE val
)
3323 unsigned long num
= rb_num2ulong_internal(val
, &wrap
);
3325 check_uint(num
, wrap
);
3330 rb_fix2uint(VALUE val
)
3334 if (!FIXNUM_P(val
)) {
3335 return rb_num2uint(val
);
3337 num
= FIX2ULONG(val
);
3339 check_uint(num
, FIXNUM_NEGATIVE_P(val
));
3344 rb_num2int(VALUE val
)
3346 return rb_num2long(val
);
3350 rb_fix2int(VALUE val
)
3352 return FIX2INT(val
);
3356 rb_num2uint(VALUE val
)
3358 return rb_num2ulong(val
);
3362 rb_fix2uint(VALUE val
)
3364 return RB_FIX2ULONG(val
);
3368 NORETURN(static void rb_out_of_short(SIGNED_VALUE num
));
3370 rb_out_of_short(SIGNED_VALUE num
)
3372 rb_raise(rb_eRangeError
, "integer %"PRIdVALUE
" too %s to convert to 'short'",
3373 num
, num
< 0 ? "small" : "big");
3377 check_short(long num
)
3379 if ((long)(short)num
!= num
) {
3380 rb_out_of_short(num
);
3385 check_ushort(unsigned long num
, int sign
)
3389 if (num
< (unsigned long)SHRT_MIN
)
3390 rb_raise(rb_eRangeError
, "integer %ld too small to convert to 'unsigned short'", (long)num
);
3394 if (USHRT_MAX
< num
)
3395 rb_raise(rb_eRangeError
, "integer %lu too big to convert to 'unsigned short'", num
);
3400 rb_num2short(VALUE val
)
3402 long num
= rb_num2long(val
);
3409 rb_fix2short(VALUE val
)
3411 long num
= FIXNUM_P(val
)?FIX2LONG(val
):rb_num2long(val
);
3418 rb_num2ushort(VALUE val
)
3421 unsigned long num
= rb_num2ulong_internal(val
, &wrap
);
3423 check_ushort(num
, wrap
);
3428 rb_fix2ushort(VALUE val
)
3432 if (!FIXNUM_P(val
)) {
3433 return rb_num2ushort(val
);
3435 num
= FIX2ULONG(val
);
3437 check_ushort(num
, FIXNUM_NEGATIVE_P(val
));
3442 rb_num2fix(VALUE val
)
3446 if (FIXNUM_P(val
)) return val
;
3448 v
= rb_num2long(val
);
3450 rb_raise(rb_eRangeError
, "integer %ld out of range of fixnum", v
);
3456 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3457 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3458 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3460 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3462 #define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3463 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3465 LLONG_MIN_MINUS_ONE < (n))
3468 rb_num2ll(VALUE val
)
3471 rb_raise(rb_eTypeError
, "no implicit conversion from nil");
3474 if (FIXNUM_P(val
)) return (LONG_LONG
)FIX2LONG(val
);
3476 else if (RB_FLOAT_TYPE_P(val
)) {
3477 double d
= RFLOAT_VALUE(val
);
3478 if (d
< LLONG_MAX_PLUS_ONE
&& (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d
))) {
3479 return (LONG_LONG
)d
;
3482 FLOAT_OUT_OF_RANGE(val
, "long long");
3485 else if (RB_BIGNUM_TYPE_P(val
)) {
3486 return rb_big2ll(val
);
3488 else if (RB_TYPE_P(val
, T_STRING
)) {
3489 rb_raise(rb_eTypeError
, "no implicit conversion from string");
3491 else if (RB_TYPE_P(val
, T_TRUE
) || RB_TYPE_P(val
, T_FALSE
)) {
3492 rb_raise(rb_eTypeError
, "no implicit conversion from boolean");
3495 val
= rb_to_int(val
);
3500 rb_num2ull(VALUE val
)
3503 rb_raise(rb_eTypeError
, "no implicit conversion of nil into Integer");
3505 else if (FIXNUM_P(val
)) {
3506 return (LONG_LONG
)FIX2LONG(val
); /* this is FIX2LONG, intended */
3508 else if (RB_FLOAT_TYPE_P(val
)) {
3509 double d
= RFLOAT_VALUE(val
);
3510 if (d
< ULLONG_MAX_PLUS_ONE
&& LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d
)) {
3512 return (unsigned LONG_LONG
)d
;
3513 return (unsigned LONG_LONG
)(LONG_LONG
)d
;
3516 FLOAT_OUT_OF_RANGE(val
, "unsigned long long");
3519 else if (RB_BIGNUM_TYPE_P(val
)) {
3520 return rb_big2ull(val
);
3523 val
= rb_to_int(val
);
3524 return NUM2ULL(val
);
3528 #endif /* HAVE_LONG_LONG */
3530 /********************************************************************
3532 * Document-class: Integer
3534 * An \Integer object represents an integer value.
3536 * You can create an \Integer object explicitly with:
3538 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3540 * You can convert certain objects to Integers with:
3542 * - \Method #Integer.
3544 * An attempt to add a singleton method to an instance of this class
3545 * causes an exception to be raised.
3549 * First, what's elsewhere. \Class \Integer:
3552 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3553 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3554 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3556 * Here, class \Integer provides methods for:
3558 * - {Querying}[rdoc-ref:Integer@Querying]
3559 * - {Comparing}[rdoc-ref:Integer@Comparing]
3560 * - {Converting}[rdoc-ref:Integer@Converting]
3561 * - {Other}[rdoc-ref:Integer@Other]
3565 * - #allbits?: Returns whether all bits in +self+ are set.
3566 * - #anybits?: Returns whether any bits in +self+ are set.
3567 * - #nobits?: Returns whether no bits in +self+ are set.
3571 * - #<: Returns whether +self+ is less than the given value.
3572 * - #<=: Returns whether +self+ is less than or equal to the given value.
3573 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3574 * to, or greater than the given value.
3575 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3577 * - #>: Returns whether +self+ is greater than the given value.
3578 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3582 * - ::sqrt: Returns the integer square root of the given value.
3583 * - ::try_convert: Returns the given value converted to an \Integer.
3584 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3585 * - #&: Returns the bitwise AND of +self+ and the given value.
3586 * - #*: Returns the product of +self+ and the given value.
3587 * - #**: Returns the value of +self+ raised to the power of the given value.
3588 * - #+: Returns the sum of +self+ and the given value.
3589 * - #-: Returns the difference of +self+ and the given value.
3590 * - #/: Returns the quotient of +self+ and the given value.
3591 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3592 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3593 * - #[]: Returns a slice of bits from +self+.
3594 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3595 * - #|: Returns the bitwise OR of +self+ and the given value.
3596 * - #ceil: Returns the smallest number greater than or equal to +self+.
3597 * - #chr: Returns a 1-character string containing the character
3598 * represented by the value of +self+.
3599 * - #digits: Returns an array of integers representing the base-radix digits
3601 * - #div: Returns the integer result of dividing +self+ by the given value.
3602 * - #divmod: Returns a 2-element array containing the quotient and remainder
3603 * results of dividing +self+ by the given value.
3604 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3605 * - #floor: Returns the greatest number smaller than or equal to +self+.
3606 * - #pow: Returns the modular exponentiation of +self+.
3607 * - #pred: Returns the integer predecessor of +self+.
3608 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3609 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3610 * - #succ (aliased as #next): Returns the integer successor of +self+.
3611 * - #to_f: Returns +self+ converted to a Float.
3612 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3613 * representation of +self+ in the given radix.
3614 * - #truncate: Returns +self+ truncated to the given precision.
3618 * - #downto: Calls the given block with each integer value from +self+
3619 * down to the given value.
3620 * - #times: Calls the given block +self+ times with each integer
3621 * in <tt>(0..self-1)</tt>.
3622 * - #upto: Calls the given block with each integer value from +self+
3623 * up to the given value.
3628 rb_int_odd_p(VALUE num
)
3630 if (FIXNUM_P(num
)) {
3631 return RBOOL(num
& 2);
3634 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3635 return rb_big_odd_p(num
);
3640 int_even_p(VALUE num
)
3642 if (FIXNUM_P(num
)) {
3643 return RBOOL((num
& 2) == 0);
3646 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3647 return rb_big_even_p(num
);
3652 rb_int_even_p(VALUE num
)
3654 return int_even_p(num
);
3659 * allbits?(mask) -> true or false
3661 * Returns +true+ if all bits that are set (=1) in +mask+
3662 * are also set in +self+; returns +false+ otherwise.
3668 * 0b1010100 self & mask
3669 * true self.allbits?(mask)
3673 * 0b1010100 self & mask
3674 * false self.allbits?(mask)
3676 * Related: Integer#anybits?, Integer#nobits?.
3681 int_allbits_p(VALUE num
, VALUE mask
)
3683 mask
= rb_to_int(mask
);
3684 return rb_int_equal(rb_int_and(num
, mask
), mask
);
3689 * anybits?(mask) -> true or false
3691 * Returns +true+ if any bit that is set (=1) in +mask+
3692 * is also set in +self+; returns +false+ otherwise.
3698 * 0b10000010 self & mask
3699 * true self.anybits?(mask)
3703 * 0b00000000 self & mask
3704 * false self.anybits?(mask)
3706 * Related: Integer#allbits?, Integer#nobits?.
3711 int_anybits_p(VALUE num
, VALUE mask
)
3713 mask
= rb_to_int(mask
);
3714 return RBOOL(!int_zero_p(rb_int_and(num
, mask
)));
3719 * nobits?(mask) -> true or false
3721 * Returns +true+ if no bit that is set (=1) in +mask+
3722 * is also set in +self+; returns +false+ otherwise.
3728 * 0b00000000 self & mask
3729 * true self.nobits?(mask)
3733 * 0b00000001 self & mask
3734 * false self.nobits?(mask)
3736 * Related: Integer#allbits?, Integer#anybits?.
3741 int_nobits_p(VALUE num
, VALUE mask
)
3743 mask
= rb_to_int(mask
);
3744 return RBOOL(int_zero_p(rb_int_and(num
, mask
)));
3749 * succ -> next_integer
3751 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3756 * Related: Integer#pred (predecessor value).
3760 rb_int_succ(VALUE num
)
3762 if (FIXNUM_P(num
)) {
3763 long i
= FIX2LONG(num
) + 1;
3766 if (RB_BIGNUM_TYPE_P(num
)) {
3767 return rb_big_plus(num
, INT2FIX(1));
3769 return num_funcall1(num
, '+', INT2FIX(1));
3772 #define int_succ rb_int_succ
3776 * pred -> next_integer
3778 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3783 * Related: Integer#succ (successor value).
3788 rb_int_pred(VALUE num
)
3790 if (FIXNUM_P(num
)) {
3791 long i
= FIX2LONG(num
) - 1;
3794 if (RB_BIGNUM_TYPE_P(num
)) {
3795 return rb_big_minus(num
, INT2FIX(1));
3797 return num_funcall1(num
, '-', INT2FIX(1));
3800 #define int_pred rb_int_pred
3803 rb_enc_uint_chr(unsigned int code
, rb_encoding
*enc
)
3807 switch (n
= rb_enc_codelen(code
, enc
)) {
3808 case ONIGERR_INVALID_CODE_POINT_VALUE
:
3809 rb_raise(rb_eRangeError
, "invalid codepoint 0x%X in %s", code
, rb_enc_name(enc
));
3811 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE
:
3813 rb_raise(rb_eRangeError
, "%u out of char range", code
);
3816 str
= rb_enc_str_new(0, n
, enc
);
3817 rb_enc_mbcput(code
, RSTRING_PTR(str
), enc
);
3818 if (rb_enc_precise_mbclen(RSTRING_PTR(str
), RSTRING_END(str
), enc
) != n
) {
3819 rb_raise(rb_eRangeError
, "invalid codepoint 0x%X in %s", code
, rb_enc_name(enc
));
3826 * chr(encoding) -> string
3828 * Returns a 1-character string containing the character
3829 * represented by the value of +self+, according to the given +encoding+.
3833 * 255.chr # => "\xFF"
3834 * string = 255.chr(Encoding::UTF_8)
3835 * string.encoding # => Encoding::UTF_8
3837 * Raises an exception if +self+ is negative.
3839 * Related: Integer#ord.
3844 int_chr(int argc
, VALUE
*argv
, VALUE num
)
3850 if (rb_num_to_uint(num
, &i
) == 0) {
3852 else if (FIXNUM_P(num
)) {
3853 rb_raise(rb_eRangeError
, "%ld out of char range", FIX2LONG(num
));
3856 rb_raise(rb_eRangeError
, "bignum out of char range");
3862 enc
= rb_default_internal_encoding();
3864 rb_raise(rb_eRangeError
, "%u out of char range", i
);
3870 return rb_usascii_str_new(&c
, 1);
3873 return rb_str_new(&c
, 1);
3878 rb_error_arity(argc
, 0, 1);
3880 enc
= rb_to_encoding(argv
[0]);
3881 if (!enc
) enc
= rb_ascii8bit_encoding();
3883 return rb_enc_uint_chr(i
, enc
);
3891 fix_uminus(VALUE num
)
3893 return LONG2NUM(-FIX2LONG(num
));
3897 rb_int_uminus(VALUE num
)
3899 if (FIXNUM_P(num
)) {
3900 return fix_uminus(num
);
3903 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num
));
3904 return rb_big_uminus(num
);
3909 rb_fix2str(VALUE x
, int base
)
3911 char buf
[SIZEOF_VALUE
*CHAR_BIT
+ 1], *const e
= buf
+ sizeof buf
, *b
= e
;
3912 long val
= FIX2LONG(x
);
3916 if (base
< 2 || 36 < base
) {
3917 rb_raise(rb_eArgError
, "invalid radix %d", base
);
3919 #if SIZEOF_LONG < SIZEOF_VOIDP
3920 # if SIZEOF_VOIDP == SIZEOF_LONG_LONG
3921 if ((val
>= 0 && (x
& 0xFFFFFFFF00000000ull
)) ||
3922 (val
< 0 && (x
& 0xFFFFFFFF00000000ull
) != 0xFFFFFFFF00000000ull
)) {
3923 rb_bug("Unnormalized Fixnum value %p", (void *)x
);
3926 /* should do something like above code, but currently ruby does not know */
3927 /* such platforms */
3931 return rb_usascii_str_new2("0");
3934 u
= 1 + (unsigned long)(-(val
+ 1)); /* u = -val avoiding overflow */
3941 *--b
= ruby_digitmap
[(int)(u
% base
)];
3942 } while (u
/= base
);
3947 return rb_usascii_str_new(b
, e
- b
);
3950 static VALUE rb_fix_to_s_static
[10];
3953 rb_fix_to_s(VALUE x
)
3955 long i
= FIX2LONG(x
);
3956 if (i
>= 0 && i
< 10) {
3957 return rb_fix_to_s_static
[i
];
3959 return rb_fix2str(x
, 10);
3964 * to_s(base = 10) -> string
3966 * Returns a string containing the place-value representation of +self+
3967 * in radix +base+ (in 2..36).
3969 * 12345.to_s # => "12345"
3970 * 12345.to_s(2) # => "11000000111001"
3971 * 12345.to_s(8) # => "30071"
3972 * 12345.to_s(10) # => "12345"
3973 * 12345.to_s(16) # => "3039"
3974 * 12345.to_s(36) # => "9ix"
3975 * 78546939656932.to_s(36) # => "rubyrules"
3977 * Raises an exception if +base+ is out of range.
3981 rb_int_to_s(int argc
, VALUE
*argv
, VALUE x
)
3985 if (rb_check_arity(argc
, 0, 1))
3986 base
= NUM2INT(argv
[0]);
3989 return rb_int2str(x
, base
);
3993 rb_int2str(VALUE x
, int base
)
3996 return rb_fix2str(x
, base
);
3998 else if (RB_BIGNUM_TYPE_P(x
)) {
3999 return rb_big2str(x
, base
);
4002 return rb_any_to_s(x
);
4006 fix_plus(VALUE x
, VALUE y
)
4009 return rb_fix_plus_fix(x
, y
);
4011 else if (RB_BIGNUM_TYPE_P(y
)) {
4012 return rb_big_plus(y
, x
);
4014 else if (RB_FLOAT_TYPE_P(y
)) {
4015 return DBL2NUM((double)FIX2LONG(x
) + RFLOAT_VALUE(y
));
4017 else if (RB_TYPE_P(y
, T_COMPLEX
)) {
4018 return rb_complex_plus(y
, x
);
4021 return rb_num_coerce_bin(x
, y
, '+');
4026 rb_fix_plus(VALUE x
, VALUE y
)
4028 return fix_plus(x
, y
);
4033 * self + numeric -> numeric_result
4035 * Performs addition:
4041 * 2 + Rational(2, 1) # => (4/1)
4042 * 2 + Complex(2, 0) # => (4+0i)
4047 rb_int_plus(VALUE x
, VALUE y
)
4050 return fix_plus(x
, y
);
4052 else if (RB_BIGNUM_TYPE_P(x
)) {
4053 return rb_big_plus(x
, y
);
4055 return rb_num_coerce_bin(x
, y
, '+');
4059 fix_minus(VALUE x
, VALUE y
)
4062 return rb_fix_minus_fix(x
, y
);
4064 else if (RB_BIGNUM_TYPE_P(y
)) {
4065 x
= rb_int2big(FIX2LONG(x
));
4066 return rb_big_minus(x
, y
);
4068 else if (RB_FLOAT_TYPE_P(y
)) {
4069 return DBL2NUM((double)FIX2LONG(x
) - RFLOAT_VALUE(y
));
4072 return rb_num_coerce_bin(x
, y
, '-');
4078 * self - numeric -> numeric_result
4080 * Performs subtraction:
4086 * 4 - Rational(2, 1) # => (2/1)
4087 * 4 - Complex(2, 0) # => (2+0i)
4092 rb_int_minus(VALUE x
, VALUE y
)
4095 return fix_minus(x
, y
);
4097 else if (RB_BIGNUM_TYPE_P(x
)) {
4098 return rb_big_minus(x
, y
);
4100 return rb_num_coerce_bin(x
, y
, '-');
4104 #define SQRT_LONG_MAX HALF_LONG_MSB
4105 /*tests if N*N would overflow*/
4106 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4109 fix_mul(VALUE x
, VALUE y
)
4112 return rb_fix_mul_fix(x
, y
);
4114 else if (RB_BIGNUM_TYPE_P(y
)) {
4116 case INT2FIX(0): return x
;
4117 case INT2FIX(1): return y
;
4119 return rb_big_mul(y
, x
);
4121 else if (RB_FLOAT_TYPE_P(y
)) {
4122 return DBL2NUM((double)FIX2LONG(x
) * RFLOAT_VALUE(y
));
4124 else if (RB_TYPE_P(y
, T_COMPLEX
)) {
4125 return rb_complex_mul(y
, x
);
4128 return rb_num_coerce_bin(x
, y
, '*');
4134 * self * numeric -> numeric_result
4136 * Performs multiplication:
4142 * 4 * Rational(1, 3) # => (4/3)
4143 * 4 * Complex(2, 0) # => (8+0i)
4147 rb_int_mul(VALUE x
, VALUE y
)
4150 return fix_mul(x
, y
);
4152 else if (RB_BIGNUM_TYPE_P(x
)) {
4153 return rb_big_mul(x
, y
);
4155 return rb_num_coerce_bin(x
, y
, '*');
4159 fix_fdiv_double(VALUE x
, VALUE y
)
4162 long iy
= FIX2LONG(y
);
4163 #if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4164 if ((iy
< 0 ? -iy
: iy
) >= (1L << DBL_MANT_DIG
)) {
4165 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x
)), rb_int2big(iy
));
4168 return double_div_double(FIX2LONG(x
), iy
);
4170 else if (RB_BIGNUM_TYPE_P(y
)) {
4171 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x
)), y
);
4173 else if (RB_FLOAT_TYPE_P(y
)) {
4174 return double_div_double(FIX2LONG(x
), RFLOAT_VALUE(y
));
4177 return NUM2DBL(rb_num_coerce_bin(x
, y
, idFdiv
));
4182 rb_int_fdiv_double(VALUE x
, VALUE y
)
4184 if (RB_INTEGER_TYPE_P(y
) && !FIXNUM_ZERO_P(y
)) {
4185 VALUE gcd
= rb_gcd(x
, y
);
4186 if (!FIXNUM_ZERO_P(gcd
) && gcd
!= INT2FIX(1)) {
4187 x
= rb_int_idiv(x
, gcd
);
4188 y
= rb_int_idiv(y
, gcd
);
4192 return fix_fdiv_double(x
, y
);
4194 else if (RB_BIGNUM_TYPE_P(x
)) {
4195 return rb_big_fdiv_double(x
, y
);
4204 * fdiv(numeric) -> float
4206 * Returns the Float result of dividing +self+ by +numeric+:
4208 * 4.fdiv(2) # => 2.0
4209 * 4.fdiv(-2) # => -2.0
4210 * -4.fdiv(2) # => -2.0
4211 * 4.fdiv(2.0) # => 2.0
4212 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4214 * Raises an exception if +numeric+ cannot be converted to a Float.
4219 rb_int_fdiv(VALUE x
, VALUE y
)
4221 if (RB_INTEGER_TYPE_P(x
)) {
4222 return DBL2NUM(rb_int_fdiv_double(x
, y
));
4228 fix_divide(VALUE x
, VALUE y
, ID op
)
4231 if (FIXNUM_ZERO_P(y
)) rb_num_zerodiv();
4232 return rb_fix_div_fix(x
, y
);
4234 else if (RB_BIGNUM_TYPE_P(y
)) {
4235 x
= rb_int2big(FIX2LONG(x
));
4236 return rb_big_div(x
, y
);
4238 else if (RB_FLOAT_TYPE_P(y
)) {
4240 double d
= FIX2LONG(x
);
4241 return rb_flo_div_flo(DBL2NUM(d
), y
);
4245 if (RFLOAT_VALUE(y
) == 0) rb_num_zerodiv();
4246 v
= fix_divide(x
, y
, '/');
4247 return flo_floor(0, 0, v
);
4251 if (RB_TYPE_P(y
, T_RATIONAL
) &&
4252 op
== '/' && FIX2LONG(x
) == 1)
4253 return rb_rational_reciprocal(y
);
4254 return rb_num_coerce_bin(x
, y
, op
);
4259 fix_div(VALUE x
, VALUE y
)
4261 return fix_divide(x
, y
, '/');
4266 * self / numeric -> numeric_result
4268 * Performs division; for integer +numeric+, truncates the result to an integer:
4275 * For other +numeric+, returns non-integer result:
4277 * 4 / 3.0 # => 1.3333333333333333
4278 * 4 / Rational(3, 1) # => (4/3)
4279 * 4 / Complex(3, 0) # => ((4/3)+0i)
4284 rb_int_div(VALUE x
, VALUE y
)
4287 return fix_div(x
, y
);
4289 else if (RB_BIGNUM_TYPE_P(x
)) {
4290 return rb_big_div(x
, y
);
4296 fix_idiv(VALUE x
, VALUE y
)
4298 return fix_divide(x
, y
, id_div
);
4303 * div(numeric) -> integer
4305 * Performs integer division; returns the integer result of dividing +self+
4313 * 4.div(Rational(3, 1)) # => 1
4315 * Raises an exception if +numeric+ does not have method +div+.
4320 rb_int_idiv(VALUE x
, VALUE y
)
4323 return fix_idiv(x
, y
);
4325 else if (RB_BIGNUM_TYPE_P(x
)) {
4326 return rb_big_idiv(x
, y
);
4328 return num_div(x
, y
);
4332 fix_mod(VALUE x
, VALUE y
)
4335 if (FIXNUM_ZERO_P(y
)) rb_num_zerodiv();
4336 return rb_fix_mod_fix(x
, y
);
4338 else if (RB_BIGNUM_TYPE_P(y
)) {
4339 x
= rb_int2big(FIX2LONG(x
));
4340 return rb_big_modulo(x
, y
);
4342 else if (RB_FLOAT_TYPE_P(y
)) {
4343 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x
), RFLOAT_VALUE(y
)));
4346 return rb_num_coerce_bin(x
, y
, '%');
4352 * self % other -> real_number
4354 * Returns +self+ modulo +other+ as a real number.
4356 * For integer +n+ and real number +r+, these expressions are equivalent:
4362 * See Numeric#divmod.
4375 * 10 % Rational(3, 1) # => (1/1)
4379 rb_int_modulo(VALUE x
, VALUE y
)
4382 return fix_mod(x
, y
);
4384 else if (RB_BIGNUM_TYPE_P(x
)) {
4385 return rb_big_modulo(x
, y
);
4387 return num_modulo(x
, y
);
4392 * remainder(other) -> real_number
4394 * Returns the remainder after dividing +self+ by +other+.
4398 * 11.remainder(4) # => 3
4399 * 11.remainder(-4) # => 3
4400 * -11.remainder(4) # => -3
4401 * -11.remainder(-4) # => -3
4403 * 12.remainder(4) # => 0
4404 * 12.remainder(-4) # => 0
4405 * -12.remainder(4) # => 0
4406 * -12.remainder(-4) # => 0
4408 * 13.remainder(4.0) # => 1.0
4409 * 13.remainder(Rational(4, 1)) # => (1/1)
4414 int_remainder(VALUE x
, VALUE y
)
4418 VALUE z
= fix_mod(x
, y
);
4419 RUBY_ASSERT(FIXNUM_P(z
));
4420 if (z
!= INT2FIX(0) && (SIGNED_VALUE
)(x
^ y
) < 0)
4421 z
= fix_minus(z
, y
);
4424 else if (!RB_BIGNUM_TYPE_P(y
)) {
4425 return num_remainder(x
, y
);
4427 x
= rb_int2big(FIX2LONG(x
));
4429 else if (!RB_BIGNUM_TYPE_P(x
)) {
4432 return rb_big_remainder(x
, y
);
4436 fix_divmod(VALUE x
, VALUE y
)
4440 if (FIXNUM_ZERO_P(y
)) rb_num_zerodiv();
4441 rb_fix_divmod_fix(x
, y
, &div
, &mod
);
4442 return rb_assoc_new(div
, mod
);
4444 else if (RB_BIGNUM_TYPE_P(y
)) {
4445 x
= rb_int2big(FIX2LONG(x
));
4446 return rb_big_divmod(x
, y
);
4448 else if (RB_FLOAT_TYPE_P(y
)) {
4451 volatile VALUE a
, b
;
4453 flodivmod((double)FIX2LONG(x
), RFLOAT_VALUE(y
), &div
, &mod
);
4456 return rb_assoc_new(a
, b
);
4460 return rb_num_coerce_bin(x
, y
, id_divmod
);
4466 * divmod(other) -> array
4468 * Returns a 2-element array <tt>[q, r]</tt>, where
4470 * q = (self/other).floor # Quotient
4471 * r = self % other # Remainder
4475 * 11.divmod(4) # => [2, 3]
4476 * 11.divmod(-4) # => [-3, -1]
4477 * -11.divmod(4) # => [-3, 1]
4478 * -11.divmod(-4) # => [2, -3]
4480 * 12.divmod(4) # => [3, 0]
4481 * 12.divmod(-4) # => [-3, 0]
4482 * -12.divmod(4) # => [-3, 0]
4483 * -12.divmod(-4) # => [3, 0]
4485 * 13.divmod(4.0) # => [3, 1.0]
4486 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4490 rb_int_divmod(VALUE x
, VALUE y
)
4493 return fix_divmod(x
, y
);
4495 else if (RB_BIGNUM_TYPE_P(x
)) {
4496 return rb_big_divmod(x
, y
);
4503 * self ** numeric -> numeric_result
4505 * Raises +self+ to the power of +numeric+:
4508 * 2 ** -3 # => (1/8)
4510 * -2 ** -3 # => (-1/8)
4511 * 2 ** 3.3 # => 9.849155306759329
4512 * 2 ** Rational(3, 1) # => (8/1)
4513 * 2 ** Complex(3, 0) # => (8+0i)
4518 int_pow(long x
, unsigned long y
)
4523 if (y
== 0) return INT2FIX(1);
4524 if (y
== 1) return LONG2NUM(x
);
4532 while (y
% 2 == 0) {
4533 if (!FIT_SQRT_LONG(x
)) {
4540 if (MUL_OVERFLOW_FIXNUM_P(x
, z
)) {
4551 v
= rb_big_pow(rb_int2big(x
), LONG2NUM(y
));
4552 if (RB_FLOAT_TYPE_P(v
)) /* infinity due to overflow */
4554 if (z
!= 1) v
= rb_big_mul(rb_int2big(neg
? -z
: z
), v
);
4559 rb_int_positive_pow(long x
, unsigned long y
)
4561 return int_pow(x
, y
);
4565 fix_pow_inverted(VALUE x
, VALUE minusb
)
4567 if (x
== INT2FIX(0)) {
4569 UNREACHABLE_RETURN(Qundef
);
4572 VALUE y
= rb_int_pow(x
, minusb
);
4574 if (RB_FLOAT_TYPE_P(y
)) {
4575 double d
= pow((double)FIX2LONG(x
), RFLOAT_VALUE(y
));
4576 return DBL2NUM(1.0 / d
);
4579 return rb_rational_raw(INT2FIX(1), y
);
4585 fix_pow(VALUE x
, VALUE y
)
4587 long a
= FIX2LONG(x
);
4590 long b
= FIX2LONG(y
);
4592 if (a
== 1) return INT2FIX(1);
4593 if (a
== -1) return INT2FIX(b
% 2 ? -1 : 1);
4594 if (b
< 0) return fix_pow_inverted(x
, fix_uminus(y
));
4595 if (b
== 0) return INT2FIX(1);
4596 if (b
== 1) return x
;
4597 if (a
== 0) return INT2FIX(0);
4598 return int_pow(a
, b
);
4600 else if (RB_BIGNUM_TYPE_P(y
)) {
4601 if (a
== 1) return INT2FIX(1);
4602 if (a
== -1) return INT2FIX(int_even_p(y
) ? 1 : -1);
4603 if (BIGNUM_NEGATIVE_P(y
)) return fix_pow_inverted(x
, rb_big_uminus(y
));
4604 if (a
== 0) return INT2FIX(0);
4605 x
= rb_int2big(FIX2LONG(x
));
4606 return rb_big_pow(x
, y
);
4608 else if (RB_FLOAT_TYPE_P(y
)) {
4609 double dy
= RFLOAT_VALUE(y
);
4610 if (dy
== 0.0) return DBL2NUM(1.0);
4612 return DBL2NUM(dy
< 0 ? HUGE_VAL
: 0.0);
4614 if (a
== 1) return DBL2NUM(1.0);
4615 if (a
< 0 && dy
!= round(dy
))
4616 return rb_dbl_complex_new_polar_pi(pow(-(double)a
, dy
), dy
);
4617 return DBL2NUM(pow((double)a
, dy
));
4620 return rb_num_coerce_bin(x
, y
, idPow
);
4626 * self ** numeric -> numeric_result
4628 * Raises +self+ to the power of +numeric+:
4631 * 2 ** -3 # => (1/8)
4633 * -2 ** -3 # => (-1/8)
4634 * 2 ** 3.3 # => 9.849155306759329
4635 * 2 ** Rational(3, 1) # => (8/1)
4636 * 2 ** Complex(3, 0) # => (8+0i)
4640 rb_int_pow(VALUE x
, VALUE y
)
4643 return fix_pow(x
, y
);
4645 else if (RB_BIGNUM_TYPE_P(x
)) {
4646 return rb_big_pow(x
, y
);
4652 rb_num_pow(VALUE x
, VALUE y
)
4654 VALUE z
= rb_int_pow(x
, y
);
4655 if (!NIL_P(z
)) return z
;
4656 if (RB_FLOAT_TYPE_P(x
)) return rb_float_pow(x
, y
);
4657 if (SPECIAL_CONST_P(x
)) return Qnil
;
4658 switch (BUILTIN_TYPE(x
)) {
4660 return rb_complex_pow(x
, y
);
4662 return rb_rational_pow(x
, y
);
4670 fix_equal(VALUE x
, VALUE y
)
4672 if (x
== y
) return Qtrue
;
4673 if (FIXNUM_P(y
)) return Qfalse
;
4674 else if (RB_BIGNUM_TYPE_P(y
)) {
4675 return rb_big_eq(y
, x
);
4677 else if (RB_FLOAT_TYPE_P(y
)) {
4678 return rb_integer_float_eq(x
, y
);
4681 return num_equal(x
, y
);
4687 * self == other -> true or false
4689 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4694 * Related: Integer#eql? (requires +other+ to be an \Integer).
4698 rb_int_equal(VALUE x
, VALUE y
)
4701 return fix_equal(x
, y
);
4703 else if (RB_BIGNUM_TYPE_P(x
)) {
4704 return rb_big_eq(x
, y
);
4710 fix_cmp(VALUE x
, VALUE y
)
4712 if (x
== y
) return INT2FIX(0);
4714 if (FIX2LONG(x
) > FIX2LONG(y
)) return INT2FIX(1);
4717 else if (RB_BIGNUM_TYPE_P(y
)) {
4718 VALUE cmp
= rb_big_cmp(y
, x
);
4720 case INT2FIX(+1): return INT2FIX(-1);
4721 case INT2FIX(-1): return INT2FIX(+1);
4725 else if (RB_FLOAT_TYPE_P(y
)) {
4726 return rb_integer_float_cmp(x
, y
);
4729 return rb_num_coerce_cmp(x
, y
, id_cmp
);
4735 * self <=> other -> -1, 0, +1, or nil
4739 * - -1, if +self+ is less than +other+.
4740 * - 0, if +self+ is equal to +other+.
4741 * - 1, if +self+ is greater then +other+.
4742 * - +nil+, if +self+ and +other+ are incomparable.
4749 * 1 <=> 'foo' # => nil
4752 * 1 <=> Rational(1, 1) # => 0
4753 * 1 <=> Complex(1, 0) # => 0
4755 * This method is the basis for comparisons in module Comparable.
4760 rb_int_cmp(VALUE x
, VALUE y
)
4763 return fix_cmp(x
, y
);
4765 else if (RB_BIGNUM_TYPE_P(x
)) {
4766 return rb_big_cmp(x
, y
);
4769 rb_raise(rb_eNotImpError
, "need to define '<=>' in %s", rb_obj_classname(x
));
4774 fix_gt(VALUE x
, VALUE y
)
4777 return RBOOL(FIX2LONG(x
) > FIX2LONG(y
));
4779 else if (RB_BIGNUM_TYPE_P(y
)) {
4780 return RBOOL(rb_big_cmp(y
, x
) == INT2FIX(-1));
4782 else if (RB_FLOAT_TYPE_P(y
)) {
4783 return RBOOL(rb_integer_float_cmp(x
, y
) == INT2FIX(1));
4786 return rb_num_coerce_relop(x
, y
, '>');
4792 * self > other -> true or false
4794 * Returns +true+ if the value of +self+ is greater than that of +other+:
4800 * 1 > Rational(1, 2) # => true
4802 * Raises an exception if the comparison cannot be made.
4807 rb_int_gt(VALUE x
, VALUE y
)
4810 return fix_gt(x
, y
);
4812 else if (RB_BIGNUM_TYPE_P(x
)) {
4813 return rb_big_gt(x
, y
);
4819 fix_ge(VALUE x
, VALUE y
)
4822 return RBOOL(FIX2LONG(x
) >= FIX2LONG(y
));
4824 else if (RB_BIGNUM_TYPE_P(y
)) {
4825 return RBOOL(rb_big_cmp(y
, x
) != INT2FIX(+1));
4827 else if (RB_FLOAT_TYPE_P(y
)) {
4828 VALUE rel
= rb_integer_float_cmp(x
, y
);
4829 return RBOOL(rel
== INT2FIX(1) || rel
== INT2FIX(0));
4832 return rb_num_coerce_relop(x
, y
, idGE
);
4838 * self >= real -> true or false
4840 * Returns +true+ if the value of +self+ is greater than or equal to
4846 * 1 >= 0.5 # => true
4847 * 1 >= Rational(1, 2) # => true
4849 * Raises an exception if the comparison cannot be made.
4854 rb_int_ge(VALUE x
, VALUE y
)
4857 return fix_ge(x
, y
);
4859 else if (RB_BIGNUM_TYPE_P(x
)) {
4860 return rb_big_ge(x
, y
);
4866 fix_lt(VALUE x
, VALUE y
)
4869 return RBOOL(FIX2LONG(x
) < FIX2LONG(y
));
4871 else if (RB_BIGNUM_TYPE_P(y
)) {
4872 return RBOOL(rb_big_cmp(y
, x
) == INT2FIX(+1));
4874 else if (RB_FLOAT_TYPE_P(y
)) {
4875 return RBOOL(rb_integer_float_cmp(x
, y
) == INT2FIX(-1));
4878 return rb_num_coerce_relop(x
, y
, '<');
4884 * self < other -> true or false
4886 * Returns +true+ if the value of +self+ is less than that of +other+:
4891 * 1 < 0.5 # => false
4892 * 1 < Rational(1, 2) # => false
4894 * Raises an exception if the comparison cannot be made.
4899 int_lt(VALUE x
, VALUE y
)
4902 return fix_lt(x
, y
);
4904 else if (RB_BIGNUM_TYPE_P(x
)) {
4905 return rb_big_lt(x
, y
);
4911 fix_le(VALUE x
, VALUE y
)
4914 return RBOOL(FIX2LONG(x
) <= FIX2LONG(y
));
4916 else if (RB_BIGNUM_TYPE_P(y
)) {
4917 return RBOOL(rb_big_cmp(y
, x
) != INT2FIX(-1));
4919 else if (RB_FLOAT_TYPE_P(y
)) {
4920 VALUE rel
= rb_integer_float_cmp(x
, y
);
4921 return RBOOL(rel
== INT2FIX(-1) || rel
== INT2FIX(0));
4924 return rb_num_coerce_relop(x
, y
, idLE
);
4930 * self <= real -> true or false
4932 * Returns +true+ if the value of +self+ is less than or equal to
4938 * 1 <= 0.5 # => false
4939 * 1 <= Rational(1, 2) # => false
4941 * Raises an exception if the comparison cannot be made.
4946 int_le(VALUE x
, VALUE y
)
4949 return fix_le(x
, y
);
4951 else if (RB_BIGNUM_TYPE_P(x
)) {
4952 return rb_big_le(x
, y
);
4960 return ~num
| FIXNUM_FLAG
;
4964 rb_int_comp(VALUE num
)
4966 if (FIXNUM_P(num
)) {
4967 return fix_comp(num
);
4969 else if (RB_BIGNUM_TYPE_P(num
)) {
4970 return rb_big_comp(num
);
4976 num_funcall_bit_1(VALUE y
, VALUE arg
, int recursive
)
4978 ID func
= (ID
)((VALUE
*)arg
)[0];
4979 VALUE x
= ((VALUE
*)arg
)[1];
4981 num_funcall_op_1_recursion(x
, func
, y
);
4983 return rb_check_funcall(x
, func
, 1, &y
);
4987 rb_num_coerce_bit(VALUE x
, VALUE y
, ID func
)
4991 args
[0] = (VALUE
)func
;
4994 do_coerce(&args
[1], &args
[2], TRUE
);
4995 ret
= rb_exec_recursive_paired(num_funcall_bit_1
,
4996 args
[2], args
[1], (VALUE
)args
);
4998 /* show the original object, not coerced object */
4999 coerce_failed(x
, y
);
5005 fix_and(VALUE x
, VALUE y
)
5008 long val
= FIX2LONG(x
) & FIX2LONG(y
);
5009 return LONG2NUM(val
);
5012 if (RB_BIGNUM_TYPE_P(y
)) {
5013 return rb_big_and(y
, x
);
5016 return rb_num_coerce_bit(x
, y
, '&');
5021 * self & other -> integer
5023 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5024 * in +self+ and +other+ are 1, 0 otherwise:
5026 * "%04b" % (0b0101 & 0b0110) # => "0100"
5028 * Raises an exception if +other+ is not an \Integer.
5030 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5035 rb_int_and(VALUE x
, VALUE y
)
5038 return fix_and(x
, y
);
5040 else if (RB_BIGNUM_TYPE_P(x
)) {
5041 return rb_big_and(x
, y
);
5047 fix_or(VALUE x
, VALUE y
)
5050 long val
= FIX2LONG(x
) | FIX2LONG(y
);
5051 return LONG2NUM(val
);
5054 if (RB_BIGNUM_TYPE_P(y
)) {
5055 return rb_big_or(y
, x
);
5058 return rb_num_coerce_bit(x
, y
, '|');
5063 * self | other -> integer
5065 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5066 * in +self+ or +other+ is 1, 0 otherwise:
5068 * "%04b" % (0b0101 | 0b0110) # => "0111"
5070 * Raises an exception if +other+ is not an \Integer.
5072 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5077 int_or(VALUE x
, VALUE y
)
5080 return fix_or(x
, y
);
5082 else if (RB_BIGNUM_TYPE_P(x
)) {
5083 return rb_big_or(x
, y
);
5089 fix_xor(VALUE x
, VALUE y
)
5092 long val
= FIX2LONG(x
) ^ FIX2LONG(y
);
5093 return LONG2NUM(val
);
5096 if (RB_BIGNUM_TYPE_P(y
)) {
5097 return rb_big_xor(y
, x
);
5100 return rb_num_coerce_bit(x
, y
, '^');
5105 * self ^ other -> integer
5107 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5108 * in +self+ and +other+ are different, 0 otherwise:
5110 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5112 * Raises an exception if +other+ is not an \Integer.
5114 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5119 int_xor(VALUE x
, VALUE y
)
5122 return fix_xor(x
, y
);
5124 else if (RB_BIGNUM_TYPE_P(x
)) {
5125 return rb_big_xor(x
, y
);
5131 rb_fix_lshift(VALUE x
, VALUE y
)
5136 if (!val
) return (rb_to_int(y
), INT2FIX(0));
5138 return rb_big_lshift(rb_int2big(val
), y
);
5139 width
= FIX2LONG(y
);
5141 return fix_rshift(val
, (unsigned long)-width
);
5142 return fix_lshift(val
, width
);
5146 fix_lshift(long val
, unsigned long width
)
5148 if (width
> (SIZEOF_LONG
*CHAR_BIT
-1)
5149 || ((unsigned long)val
)>>(SIZEOF_LONG
*CHAR_BIT
-1-width
) > 0) {
5150 return rb_big_lshift(rb_int2big(val
), ULONG2NUM(width
));
5153 return LONG2NUM(val
);
5158 * self << count -> integer
5160 * Returns +self+ with bits shifted +count+ positions to the left,
5161 * or to the right if +count+ is negative:
5164 * "%08b" % (n << 1) # => "111100000"
5165 * "%08b" % (n << 3) # => "11110000000"
5166 * "%08b" % (n << -1) # => "01111000"
5167 * "%08b" % (n << -3) # => "00011110"
5169 * Related: Integer#>>.
5174 rb_int_lshift(VALUE x
, VALUE y
)
5177 return rb_fix_lshift(x
, y
);
5179 else if (RB_BIGNUM_TYPE_P(x
)) {
5180 return rb_big_lshift(x
, y
);
5186 rb_fix_rshift(VALUE x
, VALUE y
)
5191 if (!val
) return (rb_to_int(y
), INT2FIX(0));
5193 return rb_big_rshift(rb_int2big(val
), y
);
5195 if (i
== 0) return x
;
5197 return fix_lshift(val
, (unsigned long)-i
);
5198 return fix_rshift(val
, i
);
5202 fix_rshift(long val
, unsigned long i
)
5204 if (i
>= sizeof(long)*CHAR_BIT
-1) {
5205 if (val
< 0) return INT2FIX(-1);
5208 val
= RSHIFT(val
, i
);
5209 return LONG2FIX(val
);
5214 * self >> count -> integer
5216 * Returns +self+ with bits shifted +count+ positions to the right,
5217 * or to the left if +count+ is negative:
5220 * "%08b" % (n >> 1) # => "01111000"
5221 * "%08b" % (n >> 3) # => "00011110"
5222 * "%08b" % (n >> -1) # => "111100000"
5223 * "%08b" % (n >> -3) # => "11110000000"
5225 * Related: Integer#<<.
5230 rb_int_rshift(VALUE x
, VALUE y
)
5233 return rb_fix_rshift(x
, y
);
5235 else if (RB_BIGNUM_TYPE_P(x
)) {
5236 return rb_big_rshift(x
, y
);
5242 rb_fix_aref(VALUE fix
, VALUE idx
)
5244 long val
= FIX2LONG(fix
);
5247 idx
= rb_to_int(idx
);
5248 if (!FIXNUM_P(idx
)) {
5249 idx
= rb_big_norm(idx
);
5250 if (!FIXNUM_P(idx
)) {
5251 if (!BIGNUM_SIGN(idx
) || val
>= 0)
5258 if (i
< 0) return INT2FIX(0);
5259 if (SIZEOF_LONG
*CHAR_BIT
-1 <= i
) {
5260 if (val
< 0) return INT2FIX(1);
5269 /* copied from "r_less" in range.c */
5270 /* compares _a_ and _b_ and returns:
5273 * > 0: a > b or non-comparable
5276 compare_indexes(VALUE a
, VALUE b
)
5278 VALUE r
= rb_funcall(a
, id_cmp
, 1, b
);
5282 return rb_cmpint(r
, a
, b
);
5286 generate_mask(VALUE len
)
5288 return rb_int_minus(rb_int_lshift(INT2FIX(1), len
), INT2FIX(1));
5292 int_aref1(VALUE num
, VALUE arg
)
5294 VALUE orig_num
= num
, beg
, end
;
5297 if (rb_range_values(arg
, &beg
, &end
, &excl
)) {
5299 /* beginless range */
5300 if (!RTEST(num_negative_p(end
))) {
5301 if (!excl
) end
= rb_int_plus(end
, INT2FIX(1));
5302 VALUE mask
= generate_mask(end
);
5303 if (int_zero_p(rb_int_and(num
, mask
))) {
5307 rb_raise(rb_eArgError
, "The beginless range for Integer#[] results in infinity");
5314 num
= rb_int_rshift(num
, beg
);
5316 int cmp
= compare_indexes(beg
, end
);
5317 if (!NIL_P(end
) && cmp
< 0) {
5318 VALUE len
= rb_int_minus(end
, beg
);
5319 if (!excl
) len
= rb_int_plus(len
, INT2FIX(1));
5320 VALUE mask
= generate_mask(len
);
5321 num
= rb_int_and(num
, mask
);
5323 else if (cmp
== 0) {
5324 if (excl
) return INT2FIX(0);
5333 if (FIXNUM_P(num
)) {
5334 return rb_fix_aref(num
, arg
);
5336 else if (RB_BIGNUM_TYPE_P(num
)) {
5337 return rb_big_aref(num
, arg
);
5343 int_aref2(VALUE num
, VALUE beg
, VALUE len
)
5345 num
= rb_int_rshift(num
, beg
);
5346 VALUE mask
= generate_mask(len
);
5347 num
= rb_int_and(num
, mask
);
5353 * self[offset] -> 0 or 1
5354 * self[offset, size] -> integer
5355 * self[range] -> integer
5357 * Returns a slice of bits from +self+.
5359 * With argument +offset+, returns the bit at the given offset,
5360 * where offset 0 refers to the least significant bit:
5368 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5369 * Thus, negative index always returns zero:
5373 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5374 * beginning at +offset+ and including bits of greater significance:
5376 * n = 0b111000 # => 56
5377 * "%010b" % n[0, 10] # => "0000111000"
5378 * "%010b" % n[4, 10] # => "0000000011"
5380 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5381 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5383 * n = 0b111000 # => 56
5384 * "%010b" % n[0..9] # => "0000111000"
5385 * "%010b" % n[4..9] # => "0000000011"
5387 * Raises an exception if the slice cannot be constructed.
5391 int_aref(int const argc
, VALUE
* const argv
, VALUE
const num
)
5393 rb_check_arity(argc
, 1, 2);
5395 return int_aref2(num
, argv
[0], argv
[1]);
5397 return int_aref1(num
, argv
[0]);
5406 * Converts +self+ to a Float:
5411 * If the value of +self+ does not fit in a Float,
5412 * the result is infinity:
5414 * (10**400).to_f # => Infinity
5415 * (-10**400).to_f # => -Infinity
5424 if (FIXNUM_P(num
)) {
5425 val
= (double)FIX2LONG(num
);
5427 else if (RB_BIGNUM_TYPE_P(num
)) {
5428 val
= rb_big2dbl(num
);
5431 rb_raise(rb_eNotImpError
, "Unknown subclass for to_f: %s", rb_obj_classname(num
));
5434 return DBL2NUM(val
);
5440 long i
= FIX2LONG(fix
);
5448 rb_int_abs(VALUE num
)
5450 if (FIXNUM_P(num
)) {
5451 return fix_abs(num
);
5453 else if (RB_BIGNUM_TYPE_P(num
)) {
5454 return rb_big_abs(num
);
5462 return INT2FIX(sizeof(long));
5466 rb_int_size(VALUE num
)
5468 if (FIXNUM_P(num
)) {
5469 return fix_size(num
);
5471 else if (RB_BIGNUM_TYPE_P(num
)) {
5472 return rb_big_size_m(num
);
5478 rb_fix_bit_length(VALUE fix
)
5480 long v
= FIX2LONG(fix
);
5483 return LONG2FIX(bit_length(v
));
5487 rb_int_bit_length(VALUE num
)
5489 if (FIXNUM_P(num
)) {
5490 return rb_fix_bit_length(num
);
5492 else if (RB_BIGNUM_TYPE_P(num
)) {
5493 return rb_big_bit_length(num
);
5499 rb_fix_digits(VALUE fix
, long base
)
5502 long x
= FIX2LONG(fix
);
5504 RUBY_ASSERT(x
>= 0);
5507 rb_raise(rb_eArgError
, "invalid radix %ld", base
);
5510 return rb_ary_new_from_args(1, INT2FIX(0));
5512 digits
= rb_ary_new();
5515 rb_ary_push(digits
, LONG2NUM(q
));
5518 rb_ary_push(digits
, LONG2NUM(x
));
5524 rb_int_digits_bigbase(VALUE num
, VALUE base
)
5526 VALUE digits
, bases
;
5528 RUBY_ASSERT(!rb_num_negative_p(num
));
5530 if (RB_BIGNUM_TYPE_P(base
))
5531 base
= rb_big_norm(base
);
5533 if (FIXNUM_P(base
) && FIX2LONG(base
) < 2)
5534 rb_raise(rb_eArgError
, "invalid radix %ld", FIX2LONG(base
));
5535 else if (RB_BIGNUM_TYPE_P(base
) && BIGNUM_NEGATIVE_P(base
))
5536 rb_raise(rb_eArgError
, "negative radix");
5538 if (FIXNUM_P(base
) && FIXNUM_P(num
))
5539 return rb_fix_digits(num
, FIX2LONG(base
));
5542 return rb_ary_new_from_args(1, num
);
5544 if (int_lt(rb_int_div(rb_int_bit_length(num
), rb_int_bit_length(base
)), INT2FIX(50))) {
5545 digits
= rb_ary_new();
5546 while (!FIXNUM_P(num
) || FIX2LONG(num
) > 0) {
5547 VALUE qr
= rb_int_divmod(num
, base
);
5548 rb_ary_push(digits
, RARRAY_AREF(qr
, 1));
5549 num
= RARRAY_AREF(qr
, 0);
5554 bases
= rb_ary_new();
5555 for (VALUE b
= base
; int_lt(b
, num
) == Qtrue
; b
= rb_int_mul(b
, b
)) {
5556 rb_ary_push(bases
, b
);
5558 digits
= rb_ary_new_from_args(1, num
);
5559 while (RARRAY_LEN(bases
)) {
5560 VALUE b
= rb_ary_pop(bases
);
5561 long i
, last_idx
= RARRAY_LEN(digits
) - 1;
5562 for(i
= last_idx
; i
>= 0; i
--) {
5563 VALUE n
= RARRAY_AREF(digits
, i
);
5564 VALUE divmod
= rb_int_divmod(n
, b
);
5565 VALUE div
= RARRAY_AREF(divmod
, 0);
5566 VALUE mod
= RARRAY_AREF(divmod
, 1);
5567 if (i
!= last_idx
|| div
!= INT2FIX(0)) rb_ary_store(digits
, 2 * i
+ 1, div
);
5568 rb_ary_store(digits
, 2 * i
, mod
);
5577 * digits(base = 10) -> array_of_integers
5579 * Returns an array of integers representing the +base+-radix
5581 * the first element of the array represents the least significant digit:
5583 * 12345.digits # => [5, 4, 3, 2, 1]
5584 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5585 * 12345.digits(100) # => [45, 23, 1]
5587 * Raises an exception if +self+ is negative or +base+ is less than 2.
5592 rb_int_digits(int argc
, VALUE
*argv
, VALUE num
)
5597 if (rb_num_negative_p(num
))
5598 rb_raise(rb_eMathDomainError
, "out of domain");
5600 if (rb_check_arity(argc
, 0, 1)) {
5601 base_value
= rb_to_int(argv
[0]);
5602 if (!RB_INTEGER_TYPE_P(base_value
))
5603 rb_raise(rb_eTypeError
, "wrong argument type %s (expected Integer)",
5604 rb_obj_classname(argv
[0]));
5605 if (RB_BIGNUM_TYPE_P(base_value
))
5606 return rb_int_digits_bigbase(num
, base_value
);
5608 base
= FIX2LONG(base_value
);
5610 rb_raise(rb_eArgError
, "negative radix");
5612 rb_raise(rb_eArgError
, "invalid radix %ld", base
);
5618 return rb_fix_digits(num
, base
);
5619 else if (RB_BIGNUM_TYPE_P(num
))
5620 return rb_int_digits_bigbase(num
, LONG2FIX(base
));
5626 int_upto_size(VALUE from
, VALUE args
, VALUE eobj
)
5628 return ruby_num_interval_step_size(from
, RARRAY_AREF(args
, 0), INT2FIX(1), FALSE
);
5633 * upto(limit) {|i| ... } -> self
5634 * upto(limit) -> enumerator
5636 * Calls the given block with each integer value from +self+ up to +limit+;
5640 * 5.upto(10) {|i| a << i } # => 5
5641 * a # => [5, 6, 7, 8, 9, 10]
5643 * -5.upto(0) {|i| a << i } # => -5
5644 * a # => [-5, -4, -3, -2, -1, 0]
5645 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5647 * With no block given, returns an Enumerator.
5652 int_upto(VALUE from
, VALUE to
)
5654 RETURN_SIZED_ENUMERATOR(from
, 1, &to
, int_upto_size
);
5655 if (FIXNUM_P(from
) && FIXNUM_P(to
)) {
5659 for (i
= FIX2LONG(from
); i
<= end
; i
++) {
5660 rb_yield(LONG2FIX(i
));
5666 while (!(c
= rb_funcall(i
, '>', 1, to
))) {
5668 i
= rb_funcall(i
, '+', 1, INT2FIX(1));
5670 ensure_cmp(c
, i
, to
);
5676 int_downto_size(VALUE from
, VALUE args
, VALUE eobj
)
5678 return ruby_num_interval_step_size(from
, RARRAY_AREF(args
, 0), INT2FIX(-1), FALSE
);
5683 * downto(limit) {|i| ... } -> self
5684 * downto(limit) -> enumerator
5686 * Calls the given block with each integer value from +self+ down to +limit+;
5690 * 10.downto(5) {|i| a << i } # => 10
5691 * a # => [10, 9, 8, 7, 6, 5]
5693 * 0.downto(-5) {|i| a << i } # => 0
5694 * a # => [0, -1, -2, -3, -4, -5]
5695 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5697 * With no block given, returns an Enumerator.
5702 int_downto(VALUE from
, VALUE to
)
5704 RETURN_SIZED_ENUMERATOR(from
, 1, &to
, int_downto_size
);
5705 if (FIXNUM_P(from
) && FIXNUM_P(to
)) {
5709 for (i
=FIX2LONG(from
); i
>= end
; i
--) {
5710 rb_yield(LONG2FIX(i
));
5716 while (!(c
= rb_funcall(i
, '<', 1, to
))) {
5718 i
= rb_funcall(i
, '-', 1, INT2FIX(1));
5720 if (NIL_P(c
)) rb_cmperr(i
, to
);
5726 int_dotimes_size(VALUE num
, VALUE args
, VALUE eobj
)
5728 return int_neg_p(num
) ? INT2FIX(0) : num
;
5733 * round(ndigits= 0, half: :up) -> integer
5735 * Returns +self+ rounded to the nearest value with
5736 * a precision of +ndigits+ decimal digits.
5738 * When +ndigits+ is negative, the returned value
5739 * has at least <tt>ndigits.abs</tt> trailing zeros:
5741 * 555.round(-1) # => 560
5742 * 555.round(-2) # => 600
5743 * 555.round(-3) # => 1000
5744 * -555.round(-2) # => -600
5745 * 555.round(-4) # => 0
5747 * Returns +self+ when +ndigits+ is zero or positive.
5749 * 555.round # => 555
5750 * 555.round(1) # => 555
5751 * 555.round(50) # => 555
5753 * If keyword argument +half+ is given,
5754 * and +self+ is equidistant from the two candidate values,
5755 * the rounding is according to the given +half+ value:
5757 * - +:up+ or +nil+: round away from zero:
5759 * 25.round(-1, half: :up) # => 30
5760 * (-25).round(-1, half: :up) # => -30
5762 * - +:down+: round toward zero:
5764 * 25.round(-1, half: :down) # => 20
5765 * (-25).round(-1, half: :down) # => -20
5768 * - +:even+: round toward the candidate whose last nonzero digit is even:
5770 * 25.round(-1, half: :even) # => 20
5771 * 15.round(-1, half: :even) # => 20
5772 * (-25).round(-1, half: :even) # => -20
5774 * Raises and exception if the value for +half+ is invalid.
5776 * Related: Integer#truncate.
5781 int_round(int argc
, VALUE
* argv
, VALUE num
)
5787 if (!rb_scan_args(argc
, argv
, "01:", &nd
, &opt
)) return num
;
5788 ndigits
= NUM2INT(nd
);
5789 mode
= rb_num_get_rounding_option(opt
);
5793 return rb_int_round(num
, ndigits
, mode
);
5800 * floor(ndigits = 0) -> integer
5802 * Returns an integer that is a "floor" value for `self`,
5803 * as specified by the given `ndigits`,
5805 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5807 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5811 * 0.floor(-2) # => 0
5814 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5817 * 555.floor # => 555
5818 * 555.floor(50) # => 555
5821 * - When `self` is non-zero and `ndigits` is negative,
5822 * returns a value based on a computed granularity:
5824 * - The granularity is `10 ** ndigits.abs`.
5825 * - The returned value is the largest multiple of the granularity
5826 * that is less than or equal to `self`.
5828 * Examples with positive `self`:
5830 * | ndigits | Granularity | 1234.floor(ndigits) |
5831 * |--------:|------------:|--------------------:|
5832 * | -1 | 10 | 1230 |
5833 * | -2 | 100 | 1200 |
5834 * | -3 | 1000 | 1000 |
5835 * | -4 | 10000 | 0 |
5836 * | -5 | 100000 | 0 |
5838 * Examples with negative `self`:
5840 * | ndigits | Granularity | -1234.floor(ndigits) |
5841 * |--------:|------------:|---------------------:|
5842 * | -1 | 10 | -1240 |
5843 * | -2 | 100 | -1300 |
5844 * | -3 | 1000 | -2000 |
5845 * | -4 | 10000 | -10000 |
5846 * | -5 | 100000 | -100000 |
5848 * Related: Integer#ceil.
5853 int_floor(int argc
, VALUE
* argv
, VALUE num
)
5857 if (!rb_check_arity(argc
, 0, 1)) return num
;
5858 ndigits
= NUM2INT(argv
[0]);
5862 return rb_int_floor(num
, ndigits
);
5869 * ceil(ndigits = 0) -> integer
5871 * Returns an integer that is a "ceiling" value for `self`,
5872 * as specified by the given `ndigits`,
5874 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5876 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5883 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5887 * 555.ceil(50) # => 555
5890 * - When `self` is non-zero and `ndigits` is negative,
5891 * returns a value based on a computed granularity:
5893 * - The granularity is `10 ** ndigits.abs`.
5894 * - The returned value is the smallest multiple of the granularity
5895 * that is greater than or equal to `self`.
5897 * Examples with positive `self`:
5899 * | ndigits | Granularity | 1234.ceil(ndigits) |
5900 * |--------:|------------:|-------------------:|
5901 * | -1 | 10 | 1240 |
5902 * | -2 | 100 | 1300 |
5903 * | -3 | 1000 | 2000 |
5904 * | -4 | 10000 | 10000 |
5905 * | -5 | 100000 | 100000 |
5907 * Examples with negative `self`:
5909 * | ndigits | Granularity | -1234.ceil(ndigits) |
5910 * |--------:|------------:|--------------------:|
5911 * | -1 | 10 | -1230 |
5912 * | -2 | 100 | -1200 |
5913 * | -3 | 1000 | -1000 |
5914 * | -4 | 10000 | 0 |
5915 * | -5 | 100000 | 0 |
5917 * Related: Integer#floor.
5921 int_ceil(int argc
, VALUE
* argv
, VALUE num
)
5925 if (!rb_check_arity(argc
, 0, 1)) return num
;
5926 ndigits
= NUM2INT(argv
[0]);
5930 return rb_int_ceil(num
, ndigits
);
5935 * truncate(ndigits = 0) -> integer
5937 * Returns +self+ truncated (toward zero) to
5938 * a precision of +ndigits+ decimal digits.
5940 * When +ndigits+ is negative, the returned value
5941 * has at least <tt>ndigits.abs</tt> trailing zeros:
5943 * 555.truncate(-1) # => 550
5944 * 555.truncate(-2) # => 500
5945 * -555.truncate(-2) # => -500
5947 * Returns +self+ when +ndigits+ is zero or positive.
5949 * 555.truncate # => 555
5950 * 555.truncate(50) # => 555
5952 * Related: Integer#round.
5957 int_truncate(int argc
, VALUE
* argv
, VALUE num
)
5961 if (!rb_check_arity(argc
, 0, 1)) return num
;
5962 ndigits
= NUM2INT(argv
[0]);
5966 return rb_int_truncate(num
, ndigits
);
5969 #define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5971 prefix##_isqrt(argtype n) \
5973 if (!argtype##_IN_DOUBLE_P(n)) { \
5974 unsigned int b = bit_length(n); \
5976 rettype x = (rettype)(n >> (b/2+1)); \
5977 x |= ((rettype)1LU << (b-1)/2); \
5978 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5981 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5984 #if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5985 # define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5987 # define RB_ULONG_IN_DOUBLE_P(n) 1
5989 #define RB_ULONG_TO_DOUBLE(n) (double)(n)
5990 #define RB_ULONG unsigned long
5991 DEFINE_INT_SQRT(unsigned long, rb_ulong
, RB_ULONG
)
5993 #if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5994 # if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5995 # define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5997 # define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5999 # ifdef ULL_TO_DOUBLE
6000 # define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6002 # define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6004 DEFINE_INT_SQRT(BDIGIT
, rb_bdigit_dbl
, BDIGIT_DBL
)
6007 #define domain_error(msg) \
6008 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6012 * Integer.sqrt(numeric) -> integer
6014 * Returns the integer square root of the non-negative integer +n+,
6015 * which is the largest non-negative integer less than or equal to the
6016 * square root of +numeric+.
6018 * Integer.sqrt(0) # => 0
6019 * Integer.sqrt(1) # => 1
6020 * Integer.sqrt(24) # => 4
6021 * Integer.sqrt(25) # => 5
6022 * Integer.sqrt(10**400) # => 10**200
6024 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6026 * Integer.sqrt(Complex(4, 0)) # => 2
6027 * Integer.sqrt(Rational(4, 1)) # => 2
6028 * Integer.sqrt(4.0) # => 2
6029 * Integer.sqrt(3.14159) # => 1
6031 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6032 * except that the result of the latter code may differ from the true value
6033 * due to the limited precision of floating point arithmetic.
6035 * Integer.sqrt(10**46) # => 100000000000000000000000
6036 * Math.sqrt(10**46).floor # => 99999999999999991611392
6038 * Raises an exception if +numeric+ is negative.
6043 rb_int_s_isqrt(VALUE self
, VALUE num
)
6045 unsigned long n
, sq
;
6046 num
= rb_to_int(num
);
6047 if (FIXNUM_P(num
)) {
6048 if (FIXNUM_NEGATIVE_P(num
)) {
6049 domain_error("isqrt");
6052 sq
= rb_ulong_isqrt(n
);
6053 return LONG2FIX(sq
);
6057 if (RBIGNUM_NEGATIVE_P(num
)) {
6058 domain_error("isqrt");
6060 biglen
= BIGNUM_LEN(num
);
6061 if (biglen
== 0) return INT2FIX(0);
6062 #if SIZEOF_BDIGIT <= SIZEOF_LONG
6065 n
= BIGNUM_DIGITS(num
)[0];
6066 sq
= rb_ulong_isqrt(n
);
6067 return ULONG2NUM(sq
);
6070 return rb_big_isqrt(num
);
6076 * Integer.try_convert(object) -> object, integer, or nil
6078 * If +object+ is an \Integer object, returns +object+.
6079 * Integer.try_convert(1) # => 1
6081 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6082 * calls <tt>object.to_int</tt> and returns the result.
6083 * Integer.try_convert(1.25) # => 1
6085 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6086 * Integer.try_convert([]) # => nil
6088 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6091 int_s_try_convert(VALUE self
, VALUE num
)
6093 return rb_check_integer_type(num
);
6097 * Document-class: ZeroDivisionError
6099 * Raised when attempting to divide an integer by 0.
6101 * 42 / 0 #=> ZeroDivisionError: divided by 0
6103 * Note that only division by an exact 0 will raise the exception:
6105 * 42 / 0.0 #=> Float::INFINITY
6106 * 42 / -0.0 #=> -Float::INFINITY
6111 * Document-class: FloatDomainError
6113 * Raised when attempting to convert special float values (in particular
6114 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6116 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6120 * Document-class: Numeric
6122 * \Numeric is the class from which all higher-level numeric classes should inherit.
6124 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6125 * Integer are implemented as immediates, which means that each Integer is a single immutable
6126 * object which is always passed by value.
6129 * 1.object_id == a.object_id #=> true
6131 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6132 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6134 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6136 * 1.object_id == 1.dup.object_id #=> true
6138 * For this reason, \Numeric should be used when defining other numeric classes.
6140 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6141 * Array containing an object that has been coerced into an instance of the new class
6142 * and +self+ (see #coerce).
6144 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6145 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6146 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6147 * instances of other numeric classes.
6149 * class Tally < Numeric
6150 * def initialize(string)
6163 * [self.class.new('|' * other.to_i), self]
6167 * to_i <=> other.to_i
6171 * self.class.new('|' * (to_i + other.to_i))
6175 * self.class.new('|' * (to_i - other.to_i))
6179 * self.class.new('|' * (to_i * other.to_i))
6183 * self.class.new('|' * (to_i / other.to_i))
6187 * tally = Tally.new('||')
6188 * puts tally * 2 #=> "||||"
6189 * puts tally > 1 #=> true
6193 * First, what's elsewhere. \Class \Numeric:
6195 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6196 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6198 * Here, class \Numeric provides methods for:
6200 * - {Querying}[rdoc-ref:Numeric@Querying]
6201 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6202 * - {Converting}[rdoc-ref:Numeric@Converting]
6203 * - {Other}[rdoc-ref:Numeric@Other]
6207 * - #finite?: Returns true unless +self+ is infinite or not a number.
6208 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6209 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6210 * - #integer?: Returns whether +self+ is an integer.
6211 * - #negative?: Returns whether +self+ is negative.
6212 * - #nonzero?: Returns whether +self+ is not zero.
6213 * - #positive?: Returns whether +self+ is positive.
6214 * - #real?: Returns whether +self+ is a real value.
6215 * - #zero?: Returns whether +self+ is zero.
6221 * - -1 if +self+ is less than the given value.
6222 * - 0 if +self+ is equal to the given value.
6223 * - 1 if +self+ is greater than the given value.
6224 * - +nil+ if +self+ and the given value are not comparable.
6226 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6230 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6231 * - #-@: Returns the value of +self+, negated.
6232 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6233 * - #abs2: Returns the square of +self+.
6234 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6235 * Math::PI otherwise.
6236 * - #ceil: Returns the smallest number greater than or equal to +self+,
6237 * to a given precision.
6238 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6239 * for the given other value.
6240 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6241 * - #denominator: Returns the denominator (always positive)
6242 * of the Rational representation of +self+.
6243 * - #div: Returns the value of +self+ divided by the given value
6244 * and converted to an integer.
6245 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6246 * from dividing +self+ the given divisor.
6247 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6248 * - #floor: Returns the largest number less than or equal to +self+,
6249 * to a given precision.
6250 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6252 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6253 * - #numerator: Returns the numerator of the Rational representation of +self+;
6254 * has the same sign as +self+.
6255 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6256 * - #quo: Returns the value of +self+ divided by the given value.
6257 * - #real: Returns the real part of +self+.
6258 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6259 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6260 * - #round: Returns the value of +self+ rounded to the nearest value
6261 * for the given a precision.
6262 * - #to_c: Returns the Complex representation of +self+.
6263 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6264 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6268 * - #clone: Returns +self+; does not allow freezing.
6269 * - #dup (aliased as #+@): Returns +self+.
6270 * - #step: Invokes the given block with the sequence of specified numbers.
6277 /* Turn off floating point exceptions for divide by zero, etc. */
6280 id_coerce
= rb_intern_const("coerce");
6281 id_to
= rb_intern_const("to");
6282 id_by
= rb_intern_const("by");
6284 rb_eZeroDivError
= rb_define_class("ZeroDivisionError", rb_eStandardError
);
6285 rb_eFloatDomainError
= rb_define_class("FloatDomainError", rb_eRangeError
);
6286 rb_cNumeric
= rb_define_class("Numeric", rb_cObject
);
6288 rb_define_method(rb_cNumeric
, "singleton_method_added", num_sadded
, 1);
6289 rb_include_module(rb_cNumeric
, rb_mComparable
);
6290 rb_define_method(rb_cNumeric
, "coerce", num_coerce
, 1);
6291 rb_define_method(rb_cNumeric
, "clone", num_clone
, -1);
6293 rb_define_method(rb_cNumeric
, "i", num_imaginary
, 0);
6294 rb_define_method(rb_cNumeric
, "-@", num_uminus
, 0);
6295 rb_define_method(rb_cNumeric
, "<=>", num_cmp
, 1);
6296 rb_define_method(rb_cNumeric
, "eql?", num_eql
, 1);
6297 rb_define_method(rb_cNumeric
, "fdiv", num_fdiv
, 1);
6298 rb_define_method(rb_cNumeric
, "div", num_div
, 1);
6299 rb_define_method(rb_cNumeric
, "divmod", num_divmod
, 1);
6300 rb_define_method(rb_cNumeric
, "%", num_modulo
, 1);
6301 rb_define_method(rb_cNumeric
, "modulo", num_modulo
, 1);
6302 rb_define_method(rb_cNumeric
, "remainder", num_remainder
, 1);
6303 rb_define_method(rb_cNumeric
, "abs", num_abs
, 0);
6304 rb_define_method(rb_cNumeric
, "magnitude", num_abs
, 0);
6305 rb_define_method(rb_cNumeric
, "to_int", num_to_int
, 0);
6307 rb_define_method(rb_cNumeric
, "zero?", num_zero_p
, 0);
6308 rb_define_method(rb_cNumeric
, "nonzero?", num_nonzero_p
, 0);
6310 rb_define_method(rb_cNumeric
, "floor", num_floor
, -1);
6311 rb_define_method(rb_cNumeric
, "ceil", num_ceil
, -1);
6312 rb_define_method(rb_cNumeric
, "round", num_round
, -1);
6313 rb_define_method(rb_cNumeric
, "truncate", num_truncate
, -1);
6314 rb_define_method(rb_cNumeric
, "step", num_step
, -1);
6315 rb_define_method(rb_cNumeric
, "positive?", num_positive_p
, 0);
6316 rb_define_method(rb_cNumeric
, "negative?", num_negative_p
, 0);
6318 rb_cInteger
= rb_define_class("Integer", rb_cNumeric
);
6319 rb_undef_alloc_func(rb_cInteger
);
6320 rb_undef_method(CLASS_OF(rb_cInteger
), "new");
6321 rb_define_singleton_method(rb_cInteger
, "sqrt", rb_int_s_isqrt
, 1);
6322 rb_define_singleton_method(rb_cInteger
, "try_convert", int_s_try_convert
, 1);
6324 rb_define_method(rb_cInteger
, "to_s", rb_int_to_s
, -1);
6325 rb_define_alias(rb_cInteger
, "inspect", "to_s");
6326 rb_define_method(rb_cInteger
, "allbits?", int_allbits_p
, 1);
6327 rb_define_method(rb_cInteger
, "anybits?", int_anybits_p
, 1);
6328 rb_define_method(rb_cInteger
, "nobits?", int_nobits_p
, 1);
6329 rb_define_method(rb_cInteger
, "upto", int_upto
, 1);
6330 rb_define_method(rb_cInteger
, "downto", int_downto
, 1);
6331 rb_define_method(rb_cInteger
, "succ", int_succ
, 0);
6332 rb_define_method(rb_cInteger
, "next", int_succ
, 0);
6333 rb_define_method(rb_cInteger
, "pred", int_pred
, 0);
6334 rb_define_method(rb_cInteger
, "chr", int_chr
, -1);
6335 rb_define_method(rb_cInteger
, "to_f", int_to_f
, 0);
6336 rb_define_method(rb_cInteger
, "floor", int_floor
, -1);
6337 rb_define_method(rb_cInteger
, "ceil", int_ceil
, -1);
6338 rb_define_method(rb_cInteger
, "truncate", int_truncate
, -1);
6339 rb_define_method(rb_cInteger
, "round", int_round
, -1);
6340 rb_define_method(rb_cInteger
, "<=>", rb_int_cmp
, 1);
6342 rb_define_method(rb_cInteger
, "+", rb_int_plus
, 1);
6343 rb_define_method(rb_cInteger
, "-", rb_int_minus
, 1);
6344 rb_define_method(rb_cInteger
, "*", rb_int_mul
, 1);
6345 rb_define_method(rb_cInteger
, "/", rb_int_div
, 1);
6346 rb_define_method(rb_cInteger
, "div", rb_int_idiv
, 1);
6347 rb_define_method(rb_cInteger
, "%", rb_int_modulo
, 1);
6348 rb_define_method(rb_cInteger
, "modulo", rb_int_modulo
, 1);
6349 rb_define_method(rb_cInteger
, "remainder", int_remainder
, 1);
6350 rb_define_method(rb_cInteger
, "divmod", rb_int_divmod
, 1);
6351 rb_define_method(rb_cInteger
, "fdiv", rb_int_fdiv
, 1);
6352 rb_define_method(rb_cInteger
, "**", rb_int_pow
, 1);
6354 rb_define_method(rb_cInteger
, "pow", rb_int_powm
, -1); /* in bignum.c */
6356 rb_define_method(rb_cInteger
, "===", rb_int_equal
, 1);
6357 rb_define_method(rb_cInteger
, "==", rb_int_equal
, 1);
6358 rb_define_method(rb_cInteger
, ">", rb_int_gt
, 1);
6359 rb_define_method(rb_cInteger
, ">=", rb_int_ge
, 1);
6360 rb_define_method(rb_cInteger
, "<", int_lt
, 1);
6361 rb_define_method(rb_cInteger
, "<=", int_le
, 1);
6363 rb_define_method(rb_cInteger
, "&", rb_int_and
, 1);
6364 rb_define_method(rb_cInteger
, "|", int_or
, 1);
6365 rb_define_method(rb_cInteger
, "^", int_xor
, 1);
6366 rb_define_method(rb_cInteger
, "[]", int_aref
, -1);
6368 rb_define_method(rb_cInteger
, "<<", rb_int_lshift
, 1);
6369 rb_define_method(rb_cInteger
, ">>", rb_int_rshift
, 1);
6371 rb_define_method(rb_cInteger
, "digits", rb_int_digits
, -1);
6373 #define fix_to_s_static(n) do { \
6374 VALUE lit = rb_fstring_literal(#n); \
6375 rb_fix_to_s_static[n] = lit; \
6376 rb_vm_register_global_object(lit); \
6391 #undef fix_to_s_static
6393 rb_cFloat
= rb_define_class("Float", rb_cNumeric
);
6395 rb_undef_alloc_func(rb_cFloat
);
6396 rb_undef_method(CLASS_OF(rb_cFloat
), "new");
6399 * The base of the floating point, or number of unique digits used to
6400 * represent the number.
6402 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6404 rb_define_const(rb_cFloat
, "RADIX", INT2FIX(FLT_RADIX
));
6406 * The number of base digits for the +double+ data type.
6408 * Usually defaults to 53.
6410 rb_define_const(rb_cFloat
, "MANT_DIG", INT2FIX(DBL_MANT_DIG
));
6412 * The minimum number of significant decimal digits in a double-precision
6415 * Usually defaults to 15.
6417 rb_define_const(rb_cFloat
, "DIG", INT2FIX(DBL_DIG
));
6419 * The smallest possible exponent value in a double-precision floating
6422 * Usually defaults to -1021.
6424 rb_define_const(rb_cFloat
, "MIN_EXP", INT2FIX(DBL_MIN_EXP
));
6426 * The largest possible exponent value in a double-precision floating
6429 * Usually defaults to 1024.
6431 rb_define_const(rb_cFloat
, "MAX_EXP", INT2FIX(DBL_MAX_EXP
));
6433 * The smallest negative exponent in a double-precision floating point
6434 * where 10 raised to this power minus 1.
6436 * Usually defaults to -307.
6438 rb_define_const(rb_cFloat
, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP
));
6440 * The largest positive exponent in a double-precision floating point where
6441 * 10 raised to this power minus 1.
6443 * Usually defaults to 308.
6445 rb_define_const(rb_cFloat
, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP
));
6447 * The smallest positive normalized number in a double-precision floating point.
6449 * Usually defaults to 2.2250738585072014e-308.
6451 * If the platform supports denormalized numbers,
6452 * there are numbers between zero and Float::MIN.
6453 * 0.0.next_float returns the smallest positive floating point number
6454 * including denormalized numbers.
6456 rb_define_const(rb_cFloat
, "MIN", DBL2NUM(DBL_MIN
));
6458 * The largest possible integer in a double-precision floating point number.
6460 * Usually defaults to 1.7976931348623157e+308.
6462 rb_define_const(rb_cFloat
, "MAX", DBL2NUM(DBL_MAX
));
6464 * The difference between 1 and the smallest double-precision floating
6465 * point number greater than 1.
6467 * Usually defaults to 2.2204460492503131e-16.
6469 rb_define_const(rb_cFloat
, "EPSILON", DBL2NUM(DBL_EPSILON
));
6471 * An expression representing positive infinity.
6473 rb_define_const(rb_cFloat
, "INFINITY", DBL2NUM(HUGE_VAL
));
6475 * An expression representing a value which is "not a number".
6477 rb_define_const(rb_cFloat
, "NAN", DBL2NUM(nan("")));
6479 rb_define_method(rb_cFloat
, "to_s", flo_to_s
, 0);
6480 rb_define_alias(rb_cFloat
, "inspect", "to_s");
6481 rb_define_method(rb_cFloat
, "coerce", flo_coerce
, 1);
6482 rb_define_method(rb_cFloat
, "+", rb_float_plus
, 1);
6483 rb_define_method(rb_cFloat
, "-", rb_float_minus
, 1);
6484 rb_define_method(rb_cFloat
, "*", rb_float_mul
, 1);
6485 rb_define_method(rb_cFloat
, "/", rb_float_div
, 1);
6486 rb_define_method(rb_cFloat
, "quo", flo_quo
, 1);
6487 rb_define_method(rb_cFloat
, "fdiv", flo_quo
, 1);
6488 rb_define_method(rb_cFloat
, "%", flo_mod
, 1);
6489 rb_define_method(rb_cFloat
, "modulo", flo_mod
, 1);
6490 rb_define_method(rb_cFloat
, "divmod", flo_divmod
, 1);
6491 rb_define_method(rb_cFloat
, "**", rb_float_pow
, 1);
6492 rb_define_method(rb_cFloat
, "==", flo_eq
, 1);
6493 rb_define_method(rb_cFloat
, "===", flo_eq
, 1);
6494 rb_define_method(rb_cFloat
, "<=>", flo_cmp
, 1);
6495 rb_define_method(rb_cFloat
, ">", rb_float_gt
, 1);
6496 rb_define_method(rb_cFloat
, ">=", flo_ge
, 1);
6497 rb_define_method(rb_cFloat
, "<", flo_lt
, 1);
6498 rb_define_method(rb_cFloat
, "<=", flo_le
, 1);
6499 rb_define_method(rb_cFloat
, "eql?", flo_eql
, 1);
6500 rb_define_method(rb_cFloat
, "hash", flo_hash
, 0);
6502 rb_define_method(rb_cFloat
, "to_i", flo_to_i
, 0);
6503 rb_define_method(rb_cFloat
, "to_int", flo_to_i
, 0);
6504 rb_define_method(rb_cFloat
, "floor", flo_floor
, -1);
6505 rb_define_method(rb_cFloat
, "ceil", flo_ceil
, -1);
6506 rb_define_method(rb_cFloat
, "round", flo_round
, -1);
6507 rb_define_method(rb_cFloat
, "truncate", flo_truncate
, -1);
6509 rb_define_method(rb_cFloat
, "nan?", flo_is_nan_p
, 0);
6510 rb_define_method(rb_cFloat
, "infinite?", rb_flo_is_infinite_p
, 0);
6511 rb_define_method(rb_cFloat
, "finite?", rb_flo_is_finite_p
, 0);
6512 rb_define_method(rb_cFloat
, "next_float", flo_next_float
, 0);
6513 rb_define_method(rb_cFloat
, "prev_float", flo_prev_float
, 0);
6516 #undef rb_float_value
6518 rb_float_value(VALUE v
)
6520 return rb_float_value_inline(v
);
6525 rb_float_new(double d
)
6527 return rb_float_new_inline(d
);
6530 #include "numeric.rbinc"