Ruby 3.5.0dev (2025-02-19 revision 27ba268b75bbe461460b31426e377b42d4935f70)
numeric.c (27ba268b75bbe461460b31426e377b42d4935f70)
1/**********************************************************************
2
3 numeric.c -
4
5 $Author$
6 created at: Fri Aug 13 18:33:09 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <assert.h>
15#include <ctype.h>
16#include <math.h>
17#include <stdio.h>
18
19#ifdef HAVE_FLOAT_H
20#include <float.h>
21#endif
22
23#ifdef HAVE_IEEEFP_H
24#include <ieeefp.h>
25#endif
26
27#include "id.h"
28#include "internal.h"
29#include "internal/array.h"
30#include "internal/compilers.h"
31#include "internal/complex.h"
32#include "internal/enumerator.h"
33#include "internal/gc.h"
34#include "internal/hash.h"
35#include "internal/numeric.h"
36#include "internal/object.h"
37#include "internal/rational.h"
38#include "internal/string.h"
39#include "internal/util.h"
40#include "internal/variable.h"
41#include "ruby/encoding.h"
42#include "ruby/util.h"
43#include "builtin.h"
44
45/* use IEEE 64bit values if not defined */
46#ifndef FLT_RADIX
47#define FLT_RADIX 2
48#endif
49#ifndef DBL_MIN
50#define DBL_MIN 2.2250738585072014e-308
51#endif
52#ifndef DBL_MAX
53#define DBL_MAX 1.7976931348623157e+308
54#endif
55#ifndef DBL_MIN_EXP
56#define DBL_MIN_EXP (-1021)
57#endif
58#ifndef DBL_MAX_EXP
59#define DBL_MAX_EXP 1024
60#endif
61#ifndef DBL_MIN_10_EXP
62#define DBL_MIN_10_EXP (-307)
63#endif
64#ifndef DBL_MAX_10_EXP
65#define DBL_MAX_10_EXP 308
66#endif
67#ifndef DBL_DIG
68#define DBL_DIG 15
69#endif
70#ifndef DBL_MANT_DIG
71#define DBL_MANT_DIG 53
72#endif
73#ifndef DBL_EPSILON
74#define DBL_EPSILON 2.2204460492503131e-16
75#endif
76
77#ifndef USE_RB_INFINITY
78#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
79const union bytesequence4_or_float rb_infinity = {{0x00, 0x00, 0x80, 0x7f}};
80#else
81const union bytesequence4_or_float rb_infinity = {{0x7f, 0x80, 0x00, 0x00}};
82#endif
83
84#ifndef USE_RB_NAN
85#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
86const union bytesequence4_or_float rb_nan = {{0x00, 0x00, 0xc0, 0x7f}};
87#else
88const union bytesequence4_or_float rb_nan = {{0x7f, 0xc0, 0x00, 0x00}};
89#endif
90
91#ifndef HAVE_ROUND
92double
93round(double x)
94{
95 double f;
96
97 if (x > 0.0) {
98 f = floor(x);
99 x = f + (x - f >= 0.5);
100 }
101 else if (x < 0.0) {
102 f = ceil(x);
103 x = f - (f - x >= 0.5);
104 }
105 return x;
106}
107#endif
108
109static double
110round_half_up(double x, double s)
111{
112 double f, xs = x * s;
113
114 f = round(xs);
115 if (s == 1.0) return f;
116 if (x > 0) {
117 if ((double)((f + 0.5) / s) <= x) f += 1;
118 x = f;
119 }
120 else {
121 if ((double)((f - 0.5) / s) >= x) f -= 1;
122 x = f;
123 }
124 return x;
125}
126
127static double
128round_half_down(double x, double s)
129{
130 double f, xs = x * s;
131
132 f = round(xs);
133 if (x > 0) {
134 if ((double)((f - 0.5) / s) >= x) f -= 1;
135 x = f;
136 }
137 else {
138 if ((double)((f + 0.5) / s) <= x) f += 1;
139 x = f;
140 }
141 return x;
142}
143
144static double
145round_half_even(double x, double s)
146{
147 double u, v, us, vs, f, d, uf;
148
149 v = modf(x, &u);
150 us = u * s;
151 vs = v * s;
152
153 if (x > 0.0) {
154 f = floor(vs);
155 uf = us + f;
156 d = vs - f;
157 if (d > 0.5)
158 d = 1.0;
159 else if (d == 0.5 || ((double)((uf + 0.5) / s) <= x))
160 d = fmod(uf, 2.0);
161 else
162 d = 0.0;
163 x = f + d;
164 }
165 else if (x < 0.0) {
166 f = ceil(vs);
167 uf = us + f;
168 d = f - vs;
169 if (d > 0.5)
170 d = 1.0;
171 else if (d == 0.5 || ((double)((uf - 0.5) / s) >= x))
172 d = fmod(-uf, 2.0);
173 else
174 d = 0.0;
175 x = f - d;
176 }
177 return us + x;
178}
179
180static VALUE fix_lshift(long, unsigned long);
181static VALUE fix_rshift(long, unsigned long);
182static VALUE int_pow(long x, unsigned long y);
183static VALUE rb_int_floor(VALUE num, int ndigits);
184static VALUE rb_int_ceil(VALUE num, int ndigits);
185static VALUE flo_to_i(VALUE num);
186static int float_round_overflow(int ndigits, int binexp);
187static int float_round_underflow(int ndigits, int binexp);
188
189static ID id_coerce;
190#define id_div idDiv
191#define id_divmod idDivmod
192#define id_to_i idTo_i
193#define id_eq idEq
194#define id_cmp idCmp
195
199
202
203static ID id_to, id_by;
204
205void
207{
208 rb_raise(rb_eZeroDivError, "divided by 0");
209}
210
211enum ruby_num_rounding_mode
212rb_num_get_rounding_option(VALUE opts)
213{
214 static ID round_kwds[1];
215 VALUE rounding;
216 VALUE str;
217 const char *s;
218
219 if (!NIL_P(opts)) {
220 if (!round_kwds[0]) {
221 round_kwds[0] = rb_intern_const("half");
222 }
223 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
224 if (SYMBOL_P(rounding)) {
225 str = rb_sym2str(rounding);
226 }
227 else if (NIL_P(rounding)) {
228 goto noopt;
229 }
230 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
231 str = rb_check_string_type(rounding);
232 if (NIL_P(str)) goto invalid;
233 }
235 s = RSTRING_PTR(str);
236 switch (RSTRING_LEN(str)) {
237 case 2:
238 if (rb_memcicmp(s, "up", 2) == 0)
239 return RUBY_NUM_ROUND_HALF_UP;
240 break;
241 case 4:
242 if (rb_memcicmp(s, "even", 4) == 0)
243 return RUBY_NUM_ROUND_HALF_EVEN;
244 if (strncasecmp(s, "down", 4) == 0)
245 return RUBY_NUM_ROUND_HALF_DOWN;
246 break;
247 }
248 invalid:
249 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
250 }
251 noopt:
252 return RUBY_NUM_ROUND_DEFAULT;
253}
254
255/* experimental API */
256int
257rb_num_to_uint(VALUE val, unsigned int *ret)
258{
259#define NUMERR_TYPE 1
260#define NUMERR_NEGATIVE 2
261#define NUMERR_TOOLARGE 3
262 if (FIXNUM_P(val)) {
263 long v = FIX2LONG(val);
264#if SIZEOF_INT < SIZEOF_LONG
265 if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
266#endif
267 if (v < 0) return NUMERR_NEGATIVE;
268 *ret = (unsigned int)v;
269 return 0;
270 }
271
272 if (RB_BIGNUM_TYPE_P(val)) {
273 if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
274#if SIZEOF_INT < SIZEOF_LONG
275 /* long is 64bit */
276 return NUMERR_TOOLARGE;
277#else
278 /* long is 32bit */
279 if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
280 *ret = (unsigned int)rb_big2ulong((VALUE)val);
281 return 0;
282#endif
283 }
284 return NUMERR_TYPE;
285}
286
287#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
288
289static inline int
290int_pos_p(VALUE num)
291{
292 if (FIXNUM_P(num)) {
293 return FIXNUM_POSITIVE_P(num);
294 }
295 else if (RB_BIGNUM_TYPE_P(num)) {
296 return BIGNUM_POSITIVE_P(num);
297 }
298 rb_raise(rb_eTypeError, "not an Integer");
299}
300
301static inline int
302int_neg_p(VALUE num)
303{
304 if (FIXNUM_P(num)) {
305 return FIXNUM_NEGATIVE_P(num);
306 }
307 else if (RB_BIGNUM_TYPE_P(num)) {
308 return BIGNUM_NEGATIVE_P(num);
309 }
310 rb_raise(rb_eTypeError, "not an Integer");
311}
312
313int
314rb_int_positive_p(VALUE num)
315{
316 return int_pos_p(num);
317}
318
319int
320rb_int_negative_p(VALUE num)
321{
322 return int_neg_p(num);
323}
324
325int
326rb_num_negative_p(VALUE num)
327{
328 return rb_num_negative_int_p(num);
329}
330
331static VALUE
332num_funcall_op_0(VALUE x, VALUE arg, int recursive)
333{
334 ID func = (ID)arg;
335 if (recursive) {
336 const char *name = rb_id2name(func);
337 if (ISALNUM(name[0])) {
338 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
339 x, ID2SYM(func));
340 }
341 else if (name[0] && name[1] == '@' && !name[2]) {
342 rb_name_error(func, "%c%"PRIsVALUE,
343 name[0], x);
344 }
345 else {
346 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
347 ID2SYM(func), x);
348 }
349 }
350 return rb_funcallv(x, func, 0, 0);
351}
352
353static VALUE
354num_funcall0(VALUE x, ID func)
355{
356 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
357}
358
359NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
360
361static void
362num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
363{
364 const char *name = rb_id2name(func);
365 if (ISALNUM(name[0])) {
366 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
367 x, ID2SYM(func), y);
368 }
369 else {
370 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
371 x, ID2SYM(func), y);
372 }
373}
374
375static VALUE
376num_funcall_op_1(VALUE y, VALUE arg, int recursive)
377{
378 ID func = (ID)((VALUE *)arg)[0];
379 VALUE x = ((VALUE *)arg)[1];
380 if (recursive) {
381 num_funcall_op_1_recursion(x, func, y);
382 }
383 return rb_funcall(x, func, 1, y);
384}
385
386static VALUE
387num_funcall1(VALUE x, ID func, VALUE y)
388{
389 VALUE args[2];
390 args[0] = (VALUE)func;
391 args[1] = x;
392 return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
393}
394
395/*
396 * call-seq:
397 * coerce(other) -> array
398 *
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.
402 *
403 * Of the Core and Standard Library classes,
404 * Integer, Rational, and Complex use this implementation.
405 *
406 * Examples:
407 *
408 * i = 2 # => 2
409 * i.coerce(3) # => [3, 2]
410 * i.coerce(3.0) # => [3.0, 2.0]
411 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
412 * i.coerce(Complex(3, 4)) # Raises RangeError.
413 *
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)]
419 *
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)]
425 *
426 * Raises an exception if any type conversion fails.
427 *
428 */
429
430static VALUE
431num_coerce(VALUE x, VALUE y)
432{
433 if (CLASS_OF(x) == CLASS_OF(y))
434 return rb_assoc_new(y, x);
435 x = rb_Float(x);
436 y = rb_Float(y);
437 return rb_assoc_new(y, x);
438}
439
440NORETURN(static void coerce_failed(VALUE x, VALUE y));
441static void
442coerce_failed(VALUE x, VALUE y)
443{
444 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
445 y = rb_inspect(y);
446 }
447 else {
448 y = rb_obj_class(y);
449 }
450 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
451 y, rb_obj_class(x));
452}
453
454static int
455do_coerce(VALUE *x, VALUE *y, int err)
456{
457 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
458 if (UNDEF_P(ary)) {
459 if (err) {
460 coerce_failed(*x, *y);
461 }
462 return FALSE;
463 }
464 if (!err && NIL_P(ary)) {
465 return FALSE;
466 }
467 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
468 rb_raise(rb_eTypeError, "coerce must return [x, y]");
469 }
470
471 *x = RARRAY_AREF(ary, 0);
472 *y = RARRAY_AREF(ary, 1);
473 return TRUE;
474}
475
476VALUE
478{
479 do_coerce(&x, &y, TRUE);
480 return rb_funcall(x, func, 1, y);
481}
482
483VALUE
485{
486 if (do_coerce(&x, &y, FALSE))
487 return rb_funcall(x, func, 1, y);
488 return Qnil;
489}
490
491static VALUE
492ensure_cmp(VALUE c, VALUE x, VALUE y)
493{
494 if (NIL_P(c)) rb_cmperr(x, y);
495 return c;
496}
497
498VALUE
500{
501 VALUE x0 = x, y0 = y;
502
503 if (!do_coerce(&x, &y, FALSE)) {
504 rb_cmperr(x0, y0);
506 }
507 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
508}
509
510NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
511
512/*
513 * :nodoc:
514 *
515 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
516 *
517 * Numerics should be values; singleton_methods should not be added to them.
518 */
519
520static VALUE
521num_sadded(VALUE x, VALUE name)
522{
523 ID mid = rb_to_id(name);
524 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
526 rb_raise(rb_eTypeError,
527 "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
528 rb_id2str(mid),
529 rb_obj_class(x));
530
532}
533
534#if 0
535/*
536 * call-seq:
537 * clone(freeze: true) -> self
538 *
539 * Returns +self+.
540 *
541 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
542 *
543 * Related: Numeric#dup.
544 *
545 */
546static VALUE
547num_clone(int argc, VALUE *argv, VALUE x)
548{
549 return rb_immutable_obj_clone(argc, argv, x);
550}
551#else
552# define num_clone rb_immutable_obj_clone
553#endif
554
555/*
556 * call-seq:
557 * i -> complex
558 *
559 * Returns <tt>Complex(0, self)</tt>:
560 *
561 * 2.i # => (0+2i)
562 * -2.i # => (0-2i)
563 * 2.0.i # => (0+2.0i)
564 * Rational(1, 2).i # => (0+(1/2)*i)
565 * Complex(3, 4).i # Raises NoMethodError.
566 *
567 */
568
569static VALUE
570num_imaginary(VALUE num)
571{
572 return rb_complex_new(INT2FIX(0), num);
573}
574
575/*
576 * call-seq:
577 * -self -> numeric
578 *
579 * Unary Minus---Returns the receiver, negated.
580 */
581
582static VALUE
583num_uminus(VALUE num)
584{
585 VALUE zero;
586
587 zero = INT2FIX(0);
588 do_coerce(&zero, &num, TRUE);
589
590 return num_funcall1(zero, '-', num);
591}
592
593/*
594 * call-seq:
595 * fdiv(other) -> float
596 *
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 +/+.)
600 *
601 * Of the Core and Standard Library classes,
602 * only BigDecimal uses this implementation.
603 *
604 */
605
606static VALUE
607num_fdiv(VALUE x, VALUE y)
608{
609 return rb_funcall(rb_Float(x), '/', 1, y);
610}
611
612/*
613 * call-seq:
614 * div(other) -> integer
615 *
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 +/+.)
619 *
620 * Of the Core and Standard Library classes,
621 * Only Float and Rational use this implementation.
622 *
623 */
624
625static VALUE
626num_div(VALUE x, VALUE y)
627{
628 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
629 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
630}
631
632/*
633 * call-seq:
634 * self % other -> real_numeric
635 *
636 * Returns +self+ modulo +other+ as a real number.
637 *
638 * Of the Core and Standard Library classes,
639 * only Rational uses this implementation.
640 *
641 * For Rational +r+ and real number +n+, these expressions are equivalent:
642 *
643 * r % n
644 * r-n*(r/n).floor
645 * r.divmod(n)[1]
646 *
647 * See Numeric#divmod.
648 *
649 * Examples:
650 *
651 * r = Rational(1, 2) # => (1/2)
652 * r2 = Rational(2, 3) # => (2/3)
653 * r % r2 # => (1/2)
654 * r % 2 # => (1/2)
655 * r % 2.0 # => 0.5
656 *
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)
663 *
664 */
665
666static VALUE
667num_modulo(VALUE x, VALUE y)
668{
669 VALUE q = num_funcall1(x, id_div, y);
670 return rb_funcall(x, '-', 1,
671 rb_funcall(y, '*', 1, q));
672}
673
674/*
675 * call-seq:
676 * remainder(other) -> real_number
677 *
678 * Returns the remainder after dividing +self+ by +other+.
679 *
680 * Of the Core and Standard Library classes,
681 * only Float and Rational use this implementation.
682 *
683 * Examples:
684 *
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
689 *
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
694 *
695 * 13.0.remainder(4.0) # => 1.0
696 * 13.0.remainder(Rational(4, 1)) # => 1.0
697 *
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)
702 *
703 */
704
705static VALUE
706num_remainder(VALUE x, VALUE y)
707{
709 do_coerce(&x, &y, TRUE);
710 }
711 VALUE z = num_funcall1(x, '%', y);
712
713 if ((!rb_equal(z, INT2FIX(0))) &&
714 ((rb_num_negative_int_p(x) &&
715 rb_num_positive_int_p(y)) ||
716 (rb_num_positive_int_p(x) &&
717 rb_num_negative_int_p(y)))) {
718 if (RB_FLOAT_TYPE_P(y)) {
719 if (isinf(RFLOAT_VALUE(y))) {
720 return x;
721 }
722 }
723 return rb_funcall(z, '-', 1, y);
724 }
725 return z;
726}
727
728/*
729 * call-seq:
730 * divmod(other) -> array
731 *
732 * Returns a 2-element array <tt>[q, r]</tt>, where
733 *
734 * q = (self/other).floor # Quotient
735 * r = self % other # Remainder
736 *
737 * Of the Core and Standard Library classes,
738 * only Rational uses this implementation.
739 *
740 * Examples:
741 *
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)]
746 *
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)]
751 *
752 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
753 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
754 */
755
756static VALUE
757num_divmod(VALUE x, VALUE y)
758{
759 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
760}
761
762/*
763 * call-seq:
764 * abs -> numeric
765 *
766 * Returns the absolute value of +self+.
767 *
768 * 12.abs #=> 12
769 * (-34.56).abs #=> 34.56
770 * -34.56.abs #=> 34.56
771 *
772 */
773
774static VALUE
775num_abs(VALUE num)
776{
777 if (rb_num_negative_int_p(num)) {
778 return num_funcall0(num, idUMinus);
779 }
780 return num;
781}
782
783/*
784 * call-seq:
785 * zero? -> true or false
786 *
787 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
788 *
789 * Of the Core and Standard Library classes,
790 * only Rational and Complex use this implementation.
791 *
792 */
793
794static VALUE
795num_zero_p(VALUE num)
796{
797 return rb_equal(num, INT2FIX(0));
798}
799
800static bool
801int_zero_p(VALUE num)
802{
803 if (FIXNUM_P(num)) {
804 return FIXNUM_ZERO_P(num);
805 }
806 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
807 return rb_bigzero_p(num);
808}
809
810VALUE
811rb_int_zero_p(VALUE num)
812{
813 return RBOOL(int_zero_p(num));
814}
815
816/*
817 * call-seq:
818 * nonzero? -> self or nil
819 *
820 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
821 * uses method <tt>zero?</tt> for the evaluation.
822 *
823 * The returned +self+ allows the method to be chained:
824 *
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"]
828 *
829 * Of the Core and Standard Library classes,
830 * Integer, Float, Rational, and Complex use this implementation.
831 *
832 * Related: #zero?
833 *
834 */
835
836static VALUE
837num_nonzero_p(VALUE num)
838{
839 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
840 return Qnil;
841 }
842 return num;
843}
844
845/*
846 * call-seq:
847 * to_int -> integer
848 *
849 * Returns +self+ as an integer;
850 * converts using method +to_i+ in the derived class.
851 *
852 * Of the Core and Standard Library classes,
853 * only Rational and Complex use this implementation.
854 *
855 * Examples:
856 *
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).to_int # Raises RangeError (non-zero imaginary part)
861 *
862 */
863
864static VALUE
865num_to_int(VALUE num)
866{
867 return num_funcall0(num, id_to_i);
868}
869
870/*
871 * call-seq:
872 * positive? -> true or false
873 *
874 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
875 *
876 */
877
878static VALUE
879num_positive_p(VALUE num)
880{
881 const ID mid = '>';
882
883 if (FIXNUM_P(num)) {
884 if (method_basic_p(rb_cInteger))
885 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
886 }
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));
890 }
891 return rb_num_compare_with_zero(num, mid);
892}
893
894/*
895 * call-seq:
896 * negative? -> true or false
897 *
898 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
899 *
900 */
901
902static VALUE
903num_negative_p(VALUE num)
904{
905 return RBOOL(rb_num_negative_int_p(num));
906}
907
908
909/********************************************************************
910 *
911 * Document-class: Float
912 *
913 * A \Float object represents a sometimes-inexact real number using the native
914 * architecture's double-precision floating point representation.
915 *
916 * Floating point has a different arithmetic and is an inexact number.
917 * So you should know its esoteric system. See following:
918 *
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
922 *
923 * You can create a \Float object explicitly with:
924 *
925 * - A {floating-point literal}[rdoc-ref:syntax/literals.rdoc@Float+Literals].
926 *
927 * You can convert certain objects to Floats with:
928 *
929 * - Method #Float.
930 *
931 * == What's Here
932 *
933 * First, what's elsewhere. Class \Float:
934 *
935 * - Inherits from
936 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
937 * and {class Object}[rdoc-ref:Object@What-27s+Here].
938 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
939 *
940 * Here, class \Float provides methods for:
941 *
942 * - {Querying}[rdoc-ref:Float@Querying]
943 * - {Comparing}[rdoc-ref:Float@Comparing]
944 * - {Converting}[rdoc-ref:Float@Converting]
945 *
946 * === Querying
947 *
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).
952 *
953 * === Comparing
954 *
955 * - #<: Returns whether +self+ is less than the given value.
956 * - #<=: Returns whether +self+ is less than or equal to the given value.
957 * - #<=>: Returns a number indicating whether +self+ is less than, equal
958 * to, or greater than the given value.
959 * - #== (aliased as #=== and #eql?): Returns whether +self+ is equal to
960 * the given value.
961 * - #>: Returns whether +self+ is greater than the given value.
962 * - #>=: Returns whether +self+ is greater than or equal to the given value.
963 *
964 * === Converting
965 *
966 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
967 * - #*: Returns the product of +self+ and the given value.
968 * - #**: Returns the value of +self+ raised to the power of the given value.
969 * - #+: Returns the sum of +self+ and the given value.
970 * - #-: Returns the difference of +self+ and the given value.
971 * - #/: Returns the quotient of +self+ and the given value.
972 * - #ceil: Returns the smallest number greater than or equal to +self+.
973 * - #coerce: Returns a 2-element array containing the given value converted to a \Float
974 * and +self+
975 * - #divmod: Returns a 2-element array containing the quotient and remainder
976 * results of dividing +self+ by the given value.
977 * - #fdiv: Returns the \Float result of dividing +self+ by the given value.
978 * - #floor: Returns the greatest number smaller than or equal to +self+.
979 * - #next_float: Returns the next-larger representable \Float.
980 * - #prev_float: Returns the next-smaller representable \Float.
981 * - #quo: Returns the quotient from dividing +self+ by the given value.
982 * - #round: Returns +self+ rounded to the nearest value, to a given precision.
983 * - #to_i (aliased as #to_int): Returns +self+ truncated to an Integer.
984 * - #to_s (aliased as #inspect): Returns a string containing the place-value
985 * representation of +self+ in the given radix.
986 * - #truncate: Returns +self+ truncated to a given precision.
987 *
988 */
989
990VALUE
992{
993 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT | (RGENGC_WB_PROTECTED_FLOAT ? FL_WB_PROTECTED : 0), sizeof(struct RFloat), 0);
994
995#if SIZEOF_DOUBLE <= SIZEOF_VALUE
996 flt->float_value = d;
997#else
998 union {
999 double d;
1000 rb_float_value_type v;
1001 } u = {d};
1002 flt->float_value = u.v;
1003#endif
1004 OBJ_FREEZE((VALUE)flt);
1005 return (VALUE)flt;
1006}
1007
1008/*
1009 * call-seq:
1010 * to_s -> string
1011 *
1012 * Returns a string containing a representation of +self+;
1013 * depending of the value of +self+, the string representation
1014 * may contain:
1015 *
1016 * - A fixed-point number.
1017 * 3.14.to_s # => "3.14"
1018 * - A number in "scientific notation" (containing an exponent).
1019 * (10.1**50).to_s # => "1.644631821843879e+50"
1020 * - 'Infinity'.
1021 * (10.1**500).to_s # => "Infinity"
1022 * - '-Infinity'.
1023 * (-10.1**500).to_s # => "-Infinity"
1024 * - 'NaN' (indicating not-a-number).
1025 * (0.0/0.0).to_s # => "NaN"
1026 *
1027 */
1028
1029static VALUE
1030flo_to_s(VALUE flt)
1031{
1032 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
1033 enum {float_dig = DBL_DIG+1};
1034 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
1035 double value = RFLOAT_VALUE(flt);
1036 VALUE s;
1037 char *p, *e;
1038 int sign, decpt, digs;
1039
1040 if (isinf(value)) {
1041 static const char minf[] = "-Infinity";
1042 const int pos = (value > 0); /* skip "-" */
1043 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
1044 }
1045 else if (isnan(value))
1046 return rb_usascii_str_new2("NaN");
1047
1048 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
1049 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
1050 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
1051 memcpy(buf, p, digs);
1052 free(p);
1053 if (decpt > 0) {
1054 if (decpt < digs) {
1055 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
1056 buf[decpt] = '.';
1057 rb_str_cat(s, buf, digs + 1);
1058 }
1059 else if (decpt <= DBL_DIG) {
1060 long len;
1061 char *ptr;
1062 rb_str_cat(s, buf, digs);
1063 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
1064 ptr = RSTRING_PTR(s) + len;
1065 if (decpt > digs) {
1066 memset(ptr, '0', decpt - digs);
1067 ptr += decpt - digs;
1068 }
1069 memcpy(ptr, ".0", 2);
1070 }
1071 else {
1072 goto exp;
1073 }
1074 }
1075 else if (decpt > -4) {
1076 long len;
1077 char *ptr;
1078 rb_str_cat(s, "0.", 2);
1079 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1080 ptr = RSTRING_PTR(s);
1081 memset(ptr += len, '0', -decpt);
1082 memcpy(ptr -= decpt, buf, digs);
1083 }
1084 else {
1085 goto exp;
1086 }
1087 return s;
1088
1089 exp:
1090 if (digs > 1) {
1091 memmove(buf + 2, buf + 1, digs - 1);
1092 }
1093 else {
1094 buf[2] = '0';
1095 digs++;
1096 }
1097 buf[1] = '.';
1098 rb_str_cat(s, buf, digs + 1);
1099 rb_str_catf(s, "e%+03d", decpt - 1);
1100 return s;
1101}
1102
1103/*
1104 * call-seq:
1105 * coerce(other) -> array
1106 *
1107 * Returns a 2-element array containing +other+ converted to a \Float
1108 * and +self+:
1109 *
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]
1115 *
1116 * Raises an exception if a type conversion fails.
1117 *
1118 */
1119
1120static VALUE
1121flo_coerce(VALUE x, VALUE y)
1122{
1123 return rb_assoc_new(rb_Float(y), x);
1124}
1125
1126VALUE
1127rb_float_uminus(VALUE flt)
1128{
1129 return DBL2NUM(-RFLOAT_VALUE(flt));
1130}
1131
1132/*
1133 * call-seq:
1134 * self + other -> numeric
1135 *
1136 * Returns a new \Float which is the sum of +self+ and +other+:
1137 *
1138 * f = 3.14
1139 * f + 1 # => 4.140000000000001
1140 * f + 1.0 # => 4.140000000000001
1141 * f + Rational(1, 1) # => 4.140000000000001
1142 * f + Complex(1, 0) # => (4.140000000000001+0i)
1143 *
1144 */
1145
1146VALUE
1147rb_float_plus(VALUE x, VALUE y)
1148{
1149 if (FIXNUM_P(y)) {
1150 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1151 }
1152 else if (RB_BIGNUM_TYPE_P(y)) {
1153 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1154 }
1155 else if (RB_FLOAT_TYPE_P(y)) {
1156 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1157 }
1158 else {
1159 return rb_num_coerce_bin(x, y, '+');
1160 }
1161}
1162
1163/*
1164 * call-seq:
1165 * self - other -> numeric
1166 *
1167 * Returns a new \Float which is the difference of +self+ and +other+:
1168 *
1169 * f = 3.14
1170 * f - 1 # => 2.14
1171 * f - 1.0 # => 2.14
1172 * f - Rational(1, 1) # => 2.14
1173 * f - Complex(1, 0) # => (2.14+0i)
1174 *
1175 */
1176
1177VALUE
1178rb_float_minus(VALUE x, VALUE y)
1179{
1180 if (FIXNUM_P(y)) {
1181 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1182 }
1183 else if (RB_BIGNUM_TYPE_P(y)) {
1184 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1185 }
1186 else if (RB_FLOAT_TYPE_P(y)) {
1187 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1188 }
1189 else {
1190 return rb_num_coerce_bin(x, y, '-');
1191 }
1192}
1193
1194/*
1195 * call-seq:
1196 * self * other -> numeric
1197 *
1198 * Returns a new \Float which is the product of +self+ and +other+:
1199 *
1200 * f = 3.14
1201 * f * 2 # => 6.28
1202 * f * 2.0 # => 6.28
1203 * f * Rational(1, 2) # => 1.57
1204 * f * Complex(2, 0) # => (6.28+0.0i)
1205 */
1206
1207VALUE
1208rb_float_mul(VALUE x, VALUE y)
1209{
1210 if (FIXNUM_P(y)) {
1211 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1212 }
1213 else if (RB_BIGNUM_TYPE_P(y)) {
1214 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1215 }
1216 else if (RB_FLOAT_TYPE_P(y)) {
1217 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1218 }
1219 else {
1220 return rb_num_coerce_bin(x, y, '*');
1221 }
1222}
1223
1224static double
1225double_div_double(double x, double y)
1226{
1227 if (LIKELY(y != 0.0)) {
1228 return x / y;
1229 }
1230 else if (x == 0.0) {
1231 return nan("");
1232 }
1233 else {
1234 double z = signbit(y) ? -1.0 : 1.0;
1235 return x * z * HUGE_VAL;
1236 }
1237}
1238
1239VALUE
1240rb_flo_div_flo(VALUE x, VALUE y)
1241{
1242 double num = RFLOAT_VALUE(x);
1243 double den = RFLOAT_VALUE(y);
1244 double ret = double_div_double(num, den);
1245 return DBL2NUM(ret);
1246}
1247
1248/*
1249 * call-seq:
1250 * self / other -> numeric
1251 *
1252 * Returns a new \Float which is the result of dividing +self+ by +other+:
1253 *
1254 * f = 3.14
1255 * f / 2 # => 1.57
1256 * f / 2.0 # => 1.57
1257 * f / Rational(2, 1) # => 1.57
1258 * f / Complex(2, 0) # => (1.57+0.0i)
1259 *
1260 */
1261
1262VALUE
1263rb_float_div(VALUE x, VALUE y)
1264{
1265 double num = RFLOAT_VALUE(x);
1266 double den;
1267 double ret;
1268
1269 if (FIXNUM_P(y)) {
1270 den = FIX2LONG(y);
1271 }
1272 else if (RB_BIGNUM_TYPE_P(y)) {
1273 den = rb_big2dbl(y);
1274 }
1275 else if (RB_FLOAT_TYPE_P(y)) {
1276 den = RFLOAT_VALUE(y);
1277 }
1278 else {
1279 return rb_num_coerce_bin(x, y, '/');
1280 }
1281
1282 ret = double_div_double(num, den);
1283 return DBL2NUM(ret);
1284}
1285
1286/*
1287 * call-seq:
1288 * quo(other) -> numeric
1289 *
1290 * Returns the quotient from dividing +self+ by +other+:
1291 *
1292 * f = 3.14
1293 * f.quo(2) # => 1.57
1294 * f.quo(-2) # => -1.57
1295 * f.quo(Rational(2, 1)) # => 1.57
1296 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1297 *
1298 */
1299
1300static VALUE
1301flo_quo(VALUE x, VALUE y)
1302{
1303 return num_funcall1(x, '/', y);
1304}
1305
1306static void
1307flodivmod(double x, double y, double *divp, double *modp)
1308{
1309 double div, mod;
1310
1311 if (isnan(y)) {
1312 /* y is NaN so all results are NaN */
1313 if (modp) *modp = y;
1314 if (divp) *divp = y;
1315 return;
1316 }
1317 if (y == 0.0) rb_num_zerodiv();
1318 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1319 mod = x;
1320 else {
1321#ifdef HAVE_FMOD
1322 mod = fmod(x, y);
1323#else
1324 double z;
1325
1326 modf(x/y, &z);
1327 mod = x - z * y;
1328#endif
1329 }
1330 if (isinf(x) && !isinf(y))
1331 div = x;
1332 else {
1333 div = (x - mod) / y;
1334 if (modp && divp) div = round(div);
1335 }
1336 if (y*mod < 0) {
1337 mod += y;
1338 div -= 1.0;
1339 }
1340 if (modp) *modp = mod;
1341 if (divp) *divp = div;
1342}
1343
1344/*
1345 * Returns the modulo of division of x by y.
1346 * An error will be raised if y == 0.
1347 */
1348
1349double
1350ruby_float_mod(double x, double y)
1351{
1352 double mod;
1353 flodivmod(x, y, 0, &mod);
1354 return mod;
1355}
1356
1357/*
1358 * call-seq:
1359 * self % other -> float
1360 *
1361 * Returns +self+ modulo +other+ as a float.
1362 *
1363 * For float +f+ and real number +r+, these expressions are equivalent:
1364 *
1365 * f % r
1366 * f-r*(f/r).floor
1367 * f.divmod(r)[1]
1368 *
1369 * See Numeric#divmod.
1370 *
1371 * Examples:
1372 *
1373 * 10.0 % 2 # => 0.0
1374 * 10.0 % 3 # => 1.0
1375 * 10.0 % 4 # => 2.0
1376 *
1377 * 10.0 % -2 # => 0.0
1378 * 10.0 % -3 # => -2.0
1379 * 10.0 % -4 # => -2.0
1380 *
1381 * 10.0 % 4.0 # => 2.0
1382 * 10.0 % Rational(4, 1) # => 2.0
1383 *
1384 */
1385
1386static VALUE
1387flo_mod(VALUE x, VALUE y)
1388{
1389 double fy;
1390
1391 if (FIXNUM_P(y)) {
1392 fy = (double)FIX2LONG(y);
1393 }
1394 else if (RB_BIGNUM_TYPE_P(y)) {
1395 fy = rb_big2dbl(y);
1396 }
1397 else if (RB_FLOAT_TYPE_P(y)) {
1398 fy = RFLOAT_VALUE(y);
1399 }
1400 else {
1401 return rb_num_coerce_bin(x, y, '%');
1402 }
1403 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1404}
1405
1406static VALUE
1407dbl2ival(double d)
1408{
1409 if (FIXABLE(d)) {
1410 return LONG2FIX((long)d);
1411 }
1412 return rb_dbl2big(d);
1413}
1414
1415/*
1416 * call-seq:
1417 * divmod(other) -> array
1418 *
1419 * Returns a 2-element array <tt>[q, r]</tt>, where
1420 *
1421 * q = (self/other).floor # Quotient
1422 * r = self % other # Remainder
1423 *
1424 * Examples:
1425 *
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]
1430 *
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]
1435 *
1436 * 13.0.divmod(4.0) # => [3, 1.0]
1437 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1438 *
1439 */
1440
1441static VALUE
1442flo_divmod(VALUE x, VALUE y)
1443{
1444 double fy, div, mod;
1445 volatile VALUE a, b;
1446
1447 if (FIXNUM_P(y)) {
1448 fy = (double)FIX2LONG(y);
1449 }
1450 else if (RB_BIGNUM_TYPE_P(y)) {
1451 fy = rb_big2dbl(y);
1452 }
1453 else if (RB_FLOAT_TYPE_P(y)) {
1454 fy = RFLOAT_VALUE(y);
1455 }
1456 else {
1457 return rb_num_coerce_bin(x, y, id_divmod);
1458 }
1459 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1460 a = dbl2ival(div);
1461 b = DBL2NUM(mod);
1462 return rb_assoc_new(a, b);
1463}
1464
1465/*
1466 * call-seq:
1467 * self ** other -> numeric
1468 *
1469 * Raises +self+ to the power of +other+:
1470 *
1471 * f = 3.14
1472 * f ** 2 # => 9.8596
1473 * f ** -2 # => 0.1014239928597509
1474 * f ** 2.1 # => 11.054834900588839
1475 * f ** Rational(2, 1) # => 9.8596
1476 * f ** Complex(2, 0) # => (9.8596+0i)
1477 *
1478 */
1479
1480VALUE
1481rb_float_pow(VALUE x, VALUE y)
1482{
1483 double dx, dy;
1484 if (y == INT2FIX(2)) {
1485 dx = RFLOAT_VALUE(x);
1486 return DBL2NUM(dx * dx);
1487 }
1488 else if (FIXNUM_P(y)) {
1489 dx = RFLOAT_VALUE(x);
1490 dy = (double)FIX2LONG(y);
1491 }
1492 else if (RB_BIGNUM_TYPE_P(y)) {
1493 dx = RFLOAT_VALUE(x);
1494 dy = rb_big2dbl(y);
1495 }
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);
1501 }
1502 else {
1503 return rb_num_coerce_bin(x, y, idPow);
1504 }
1505 return DBL2NUM(pow(dx, dy));
1506}
1507
1508/*
1509 * call-seq:
1510 * eql?(other) -> true or false
1511 *
1512 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1513 *
1514 * Of the Core and Standard Library classes,
1515 * only Integer, Rational, and Complex use this implementation.
1516 *
1517 * Examples:
1518 *
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
1523 *
1524 * Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1525 * while <tt>==</tt> does not.
1526 *
1527 */
1528
1529static VALUE
1530num_eql(VALUE x, VALUE y)
1531{
1532 if (TYPE(x) != TYPE(y)) return Qfalse;
1533
1534 if (RB_BIGNUM_TYPE_P(x)) {
1535 return rb_big_eql(x, y);
1536 }
1537
1538 return rb_equal(x, y);
1539}
1540
1541/*
1542 * call-seq:
1543 * self <=> other -> zero or nil
1544 *
1545 * Returns zero if +self+ is the same as +other+, +nil+ otherwise.
1546 *
1547 * No subclass in the Ruby Core or Standard Library uses this implementation.
1548 *
1549 */
1550
1551static VALUE
1552num_cmp(VALUE x, VALUE y)
1553{
1554 if (x == y) return INT2FIX(0);
1555 return Qnil;
1556}
1557
1558static VALUE
1559num_equal(VALUE x, VALUE y)
1560{
1561 VALUE result;
1562 if (x == y) return Qtrue;
1563 result = num_funcall1(y, id_eq, x);
1564 return RBOOL(RTEST(result));
1565}
1566
1567/*
1568 * call-seq:
1569 * self == other -> true or false
1570 *
1571 * Returns +true+ if +other+ has the same value as +self+, +false+ otherwise:
1572 *
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
1577 *
1578 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1579 *
1580 * Related: Float#eql? (requires +other+ to be a \Float).
1581 *
1582 */
1583
1584VALUE
1585rb_float_equal(VALUE x, VALUE y)
1586{
1587 volatile double a, b;
1588
1589 if (RB_INTEGER_TYPE_P(y)) {
1590 return rb_integer_float_eq(y, x);
1591 }
1592 else if (RB_FLOAT_TYPE_P(y)) {
1593 b = RFLOAT_VALUE(y);
1594#if MSC_VERSION_BEFORE(1300)
1595 if (isnan(b)) return Qfalse;
1596#endif
1597 }
1598 else {
1599 return num_equal(x, y);
1600 }
1601 a = RFLOAT_VALUE(x);
1602#if MSC_VERSION_BEFORE(1300)
1603 if (isnan(a)) return Qfalse;
1604#endif
1605 return RBOOL(a == b);
1606}
1607
1608#define flo_eq rb_float_equal
1609static VALUE rb_dbl_hash(double d);
1610
1611/*
1612 * call-seq:
1613 * hash -> integer
1614 *
1615 * Returns the integer hash value for +self+.
1616 *
1617 * See also Object#hash.
1618 */
1619
1620static VALUE
1621flo_hash(VALUE num)
1622{
1623 return rb_dbl_hash(RFLOAT_VALUE(num));
1624}
1625
1626static VALUE
1627rb_dbl_hash(double d)
1628{
1629 return ST2FIX(rb_dbl_long_hash(d));
1630}
1631
1632VALUE
1633rb_dbl_cmp(double a, double b)
1634{
1635 if (isnan(a) || isnan(b)) return Qnil;
1636 if (a == b) return INT2FIX(0);
1637 if (a > b) return INT2FIX(1);
1638 if (a < b) return INT2FIX(-1);
1639 return Qnil;
1640}
1641
1642/*
1643 * call-seq:
1644 * self <=> other -> -1, 0, +1, or nil
1645 *
1646 * Returns a value that depends on the numeric relation
1647 * between +self+ and +other+:
1648 *
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.
1653 *
1654 * Examples:
1655 *
1656 * 2.0 <=> 2 # => 0
1657 * 2.0 <=> 2.0 # => 0
1658 * 2.0 <=> Rational(2, 1) # => 0
1659 * 2.0 <=> Complex(2, 0) # => 0
1660 * 2.0 <=> 1.9 # => 1
1661 * 2.0 <=> 2.1 # => -1
1662 * 2.0 <=> 'foo' # => nil
1663 *
1664 * This is the basis for the tests in the Comparable module.
1665 *
1666 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1667 *
1668 */
1669
1670static VALUE
1671flo_cmp(VALUE x, VALUE y)
1672{
1673 double a, b;
1674 VALUE i;
1675
1676 a = RFLOAT_VALUE(x);
1677 if (isnan(a)) return Qnil;
1678 if (RB_INTEGER_TYPE_P(y)) {
1679 VALUE rel = rb_integer_float_cmp(y, x);
1680 if (FIXNUM_P(rel))
1681 return LONG2FIX(-FIX2LONG(rel));
1682 return rel;
1683 }
1684 else if (RB_FLOAT_TYPE_P(y)) {
1685 b = RFLOAT_VALUE(y);
1686 }
1687 else {
1688 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1689 if (RTEST(i)) {
1690 int j = rb_cmpint(i, x, y);
1691 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1692 return INT2FIX(j);
1693 }
1694 if (a > 0.0) return INT2FIX(1);
1695 return INT2FIX(-1);
1696 }
1697 return rb_num_coerce_cmp(x, y, id_cmp);
1698 }
1699 return rb_dbl_cmp(a, b);
1700}
1701
1702int
1703rb_float_cmp(VALUE x, VALUE y)
1704{
1705 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1706}
1707
1708/*
1709 * call-seq:
1710 * self > other -> true or false
1711 *
1712 * Returns +true+ if +self+ is numerically greater than +other+:
1713 *
1714 * 2.0 > 1 # => true
1715 * 2.0 > 1.0 # => true
1716 * 2.0 > Rational(1, 2) # => true
1717 * 2.0 > 2.0 # => false
1718 *
1719 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1720 *
1721 */
1722
1723VALUE
1724rb_float_gt(VALUE x, VALUE y)
1725{
1726 double a, b;
1727
1728 a = RFLOAT_VALUE(x);
1729 if (RB_INTEGER_TYPE_P(y)) {
1730 VALUE rel = rb_integer_float_cmp(y, x);
1731 if (FIXNUM_P(rel))
1732 return RBOOL(-FIX2LONG(rel) > 0);
1733 return Qfalse;
1734 }
1735 else if (RB_FLOAT_TYPE_P(y)) {
1736 b = RFLOAT_VALUE(y);
1737#if MSC_VERSION_BEFORE(1300)
1738 if (isnan(b)) return Qfalse;
1739#endif
1740 }
1741 else {
1742 return rb_num_coerce_relop(x, y, '>');
1743 }
1744#if MSC_VERSION_BEFORE(1300)
1745 if (isnan(a)) return Qfalse;
1746#endif
1747 return RBOOL(a > b);
1748}
1749
1750/*
1751 * call-seq:
1752 * self >= other -> true or false
1753 *
1754 * Returns +true+ if +self+ is numerically greater than or equal to +other+:
1755 *
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
1761 *
1762 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1763 *
1764 */
1765
1766static VALUE
1767flo_ge(VALUE x, VALUE y)
1768{
1769 double a, b;
1770
1771 a = RFLOAT_VALUE(x);
1772 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1773 VALUE rel = rb_integer_float_cmp(y, x);
1774 if (FIXNUM_P(rel))
1775 return RBOOL(-FIX2LONG(rel) >= 0);
1776 return Qfalse;
1777 }
1778 else if (RB_FLOAT_TYPE_P(y)) {
1779 b = RFLOAT_VALUE(y);
1780#if MSC_VERSION_BEFORE(1300)
1781 if (isnan(b)) return Qfalse;
1782#endif
1783 }
1784 else {
1785 return rb_num_coerce_relop(x, y, idGE);
1786 }
1787#if MSC_VERSION_BEFORE(1300)
1788 if (isnan(a)) return Qfalse;
1789#endif
1790 return RBOOL(a >= b);
1791}
1792
1793/*
1794 * call-seq:
1795 * self < other -> true or false
1796 *
1797 * Returns +true+ if +self+ is numerically less than +other+:
1798 *
1799 * 2.0 < 3 # => true
1800 * 2.0 < 3.0 # => true
1801 * 2.0 < Rational(3, 1) # => true
1802 * 2.0 < 2.0 # => false
1803 *
1804 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1805 *
1806 */
1807
1808static VALUE
1809flo_lt(VALUE x, VALUE y)
1810{
1811 double a, b;
1812
1813 a = RFLOAT_VALUE(x);
1814 if (RB_INTEGER_TYPE_P(y)) {
1815 VALUE rel = rb_integer_float_cmp(y, x);
1816 if (FIXNUM_P(rel))
1817 return RBOOL(-FIX2LONG(rel) < 0);
1818 return Qfalse;
1819 }
1820 else if (RB_FLOAT_TYPE_P(y)) {
1821 b = RFLOAT_VALUE(y);
1822#if MSC_VERSION_BEFORE(1300)
1823 if (isnan(b)) return Qfalse;
1824#endif
1825 }
1826 else {
1827 return rb_num_coerce_relop(x, y, '<');
1828 }
1829#if MSC_VERSION_BEFORE(1300)
1830 if (isnan(a)) return Qfalse;
1831#endif
1832 return RBOOL(a < b);
1833}
1834
1835/*
1836 * call-seq:
1837 * self <= other -> true or false
1838 *
1839 * Returns +true+ if +self+ is numerically less than or equal to +other+:
1840 *
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
1846 *
1847 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1848 *
1849 */
1850
1851static VALUE
1852flo_le(VALUE x, VALUE y)
1853{
1854 double a, b;
1855
1856 a = RFLOAT_VALUE(x);
1857 if (RB_INTEGER_TYPE_P(y)) {
1858 VALUE rel = rb_integer_float_cmp(y, x);
1859 if (FIXNUM_P(rel))
1860 return RBOOL(-FIX2LONG(rel) <= 0);
1861 return Qfalse;
1862 }
1863 else if (RB_FLOAT_TYPE_P(y)) {
1864 b = RFLOAT_VALUE(y);
1865#if MSC_VERSION_BEFORE(1300)
1866 if (isnan(b)) return Qfalse;
1867#endif
1868 }
1869 else {
1870 return rb_num_coerce_relop(x, y, idLE);
1871 }
1872#if MSC_VERSION_BEFORE(1300)
1873 if (isnan(a)) return Qfalse;
1874#endif
1875 return RBOOL(a <= b);
1876}
1877
1878/*
1879 * call-seq:
1880 * eql?(other) -> true or false
1881 *
1882 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1883 * +false+ otherwise:
1884 *
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
1890 *
1891 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1892 *
1893 * Related: Float#== (performs type conversions).
1894 */
1895
1896VALUE
1897rb_float_eql(VALUE x, VALUE y)
1898{
1899 if (RB_FLOAT_TYPE_P(y)) {
1900 double a = RFLOAT_VALUE(x);
1901 double b = RFLOAT_VALUE(y);
1902#if MSC_VERSION_BEFORE(1300)
1903 if (isnan(a) || isnan(b)) return Qfalse;
1904#endif
1905 return RBOOL(a == b);
1906 }
1907 return Qfalse;
1908}
1909
1910#define flo_eql rb_float_eql
1911
1912VALUE
1913rb_float_abs(VALUE flt)
1914{
1915 double val = fabs(RFLOAT_VALUE(flt));
1916 return DBL2NUM(val);
1917}
1918
1919/*
1920 * call-seq:
1921 * nan? -> true or false
1922 *
1923 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1924 *
1925 * f = -1.0 #=> -1.0
1926 * f.nan? #=> false
1927 * f = 0.0/0.0 #=> NaN
1928 * f.nan? #=> true
1929 */
1930
1931static VALUE
1932flo_is_nan_p(VALUE num)
1933{
1934 double value = RFLOAT_VALUE(num);
1935
1936 return RBOOL(isnan(value));
1937}
1938
1939/*
1940 * call-seq:
1941 * infinite? -> -1, 1, or nil
1942 *
1943 * Returns:
1944 *
1945 * - 1, if +self+ is <tt>Infinity</tt>.
1946 * - -1 if +self+ is <tt>-Infinity</tt>.
1947 * - +nil+, otherwise.
1948 *
1949 * Examples:
1950 *
1951 * f = 1.0/0.0 # => Infinity
1952 * f.infinite? # => 1
1953 * f = -1.0/0.0 # => -Infinity
1954 * f.infinite? # => -1
1955 * f = 1.0 # => 1.0
1956 * f.infinite? # => nil
1957 * f = 0.0/0.0 # => NaN
1958 * f.infinite? # => nil
1959 *
1960 */
1961
1962VALUE
1963rb_flo_is_infinite_p(VALUE num)
1964{
1965 double value = RFLOAT_VALUE(num);
1966
1967 if (isinf(value)) {
1968 return INT2FIX( value < 0 ? -1 : 1 );
1969 }
1970
1971 return Qnil;
1972}
1973
1974/*
1975 * call-seq:
1976 * finite? -> true or false
1977 *
1978 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1979 * +false+ otherwise:
1980 *
1981 * f = 2.0 # => 2.0
1982 * f.finite? # => true
1983 * f = 1.0/0.0 # => Infinity
1984 * f.finite? # => false
1985 * f = -1.0/0.0 # => -Infinity
1986 * f.finite? # => false
1987 * f = 0.0/0.0 # => NaN
1988 * f.finite? # => false
1989 *
1990 */
1991
1992VALUE
1993rb_flo_is_finite_p(VALUE num)
1994{
1995 double value = RFLOAT_VALUE(num);
1996
1997 return RBOOL(isfinite(value));
1998}
1999
2000static VALUE
2001flo_nextafter(VALUE flo, double value)
2002{
2003 double x, y;
2004 x = NUM2DBL(flo);
2005 y = nextafter(x, value);
2006 return DBL2NUM(y);
2007}
2008
2009/*
2010 * call-seq:
2011 * next_float -> float
2012 *
2013 * Returns the next-larger representable \Float.
2014 *
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>:
2017 *
2018 * f = 0.0 # 0x0000000000000000
2019 * f.next_float # 0x0000000000000001
2020 *
2021 * f = 0.01 # 0x3f847ae147ae147b
2022 * f.next_float # 0x3f847ae147ae147c
2023 *
2024 * In the remaining examples here, the output is shown in the usual way
2025 * (result +to_s+):
2026 *
2027 * 0.01.next_float # => 0.010000000000000002
2028 * 1.0.next_float # => 1.0000000000000002
2029 * 100.0.next_float # => 100.00000000000001
2030 *
2031 * f = 0.01
2032 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
2033 *
2034 * Output:
2035 *
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
2040 *
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.
2049 *
2050 * Related: Float#prev_float
2051 *
2052 */
2053static VALUE
2054flo_next_float(VALUE vx)
2055{
2056 return flo_nextafter(vx, HUGE_VAL);
2057}
2058
2059/*
2060 * call-seq:
2061 * float.prev_float -> float
2062 *
2063 * Returns the next-smaller representable \Float.
2064 *
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>:
2067 *
2068 * f = 5e-324 # 0x0000000000000001
2069 * f.prev_float # 0x0000000000000000
2070 *
2071 * f = 0.01 # 0x3f847ae147ae147b
2072 * f.prev_float # 0x3f847ae147ae147a
2073 *
2074 * In the remaining examples here, the output is shown in the usual way
2075 * (result +to_s+):
2076 *
2077 * 0.01.prev_float # => 0.009999999999999998
2078 * 1.0.prev_float # => 0.9999999999999999
2079 * 100.0.prev_float # => 99.99999999999999
2080 *
2081 * f = 0.01
2082 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
2083 *
2084 * Output:
2085 *
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
2090 *
2091 * Related: Float#next_float.
2092 *
2093 */
2094static VALUE
2095flo_prev_float(VALUE vx)
2096{
2097 return flo_nextafter(vx, -HUGE_VAL);
2098}
2099
2100VALUE
2101rb_float_floor(VALUE num, int ndigits)
2102{
2103 double number;
2104 number = RFLOAT_VALUE(num);
2105 if (number == 0.0) {
2106 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2107 }
2108 if (ndigits > 0) {
2109 int binexp;
2110 double f, mul, res;
2111 frexp(number, &binexp);
2112 if (float_round_overflow(ndigits, binexp)) return num;
2113 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2114 return DBL2NUM(0.0);
2115 f = pow(10, ndigits);
2116 mul = floor(number * f);
2117 res = (mul + 1) / f;
2118 if (res > number)
2119 res = mul / f;
2120 return DBL2NUM(res);
2121 }
2122 else {
2123 num = dbl2ival(floor(number));
2124 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2125 return num;
2126 }
2127}
2128
2129static int
2130flo_ndigits(int argc, VALUE *argv)
2131{
2132 if (rb_check_arity(argc, 0, 1)) {
2133 return NUM2INT(argv[0]);
2134 }
2135 return 0;
2136}
2137
2138/*
2139 * :markup: markdown
2140 *
2141 * call-seq:
2142 * floor(ndigits = 0) -> float or integer
2143 *
2144 * Returns a float or integer that is a "floor" value for `self`,
2145 * as specified by `ndigits`,
2146 * which must be an
2147 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2148 *
2149 * When `self` is zero,
2150 * returns a zero value:
2151 * a float if `ndigits` is positive,
2152 * an integer otherwise:
2153 *
2154 * ```
2155 * f = 0.0 # => 0.0
2156 * f.floor(20) # => 0.0
2157 * f.floor(0) # => 0
2158 * f.floor(-20) # => 0
2159 * ```
2160 *
2161 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2162 * digits after the decimal point (as available):
2163 *
2164 * ```
2165 * f = 12345.6789
2166 * f.floor(1) # => 12345.6
2167 * f.floor(3) # => 12345.678
2168 * f.floor(30) # => 12345.6789
2169 * f = -12345.6789
2170 * f.floor(1) # => -12345.7
2171 * f.floor(3) # => -12345.679
2172 * f.floor(30) # => -12345.6789
2173 * ```
2174 *
2175 * When `self` is non-zero and `ndigits` is non-positive,
2176 * returns an integer value based on a computed granularity:
2177 *
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`.
2181 *
2182 * Examples with positive `self`:
2183 *
2184 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2185 * |--------:|------------:|--------------------------:|
2186 * | 0 | 1 | 12345 |
2187 * | -1 | 10 | 12340 |
2188 * | -2 | 100 | 12300 |
2189 * | -3 | 1000 | 12000 |
2190 * | -4 | 10000 | 10000 |
2191 * | -5 | 100000 | 0 |
2192 *
2193 * Examples with negative `self`:
2194 *
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 |
2204 *
2205 * Note that the limited precision of floating-point arithmetic
2206 * may lead to surprising results:
2207 *
2208 * ```
2209 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2210 * ```
2211 *
2212 * Related: Float#ceil.
2213 *
2214 */
2215
2216static VALUE
2217flo_floor(int argc, VALUE *argv, VALUE num)
2218{
2219 int ndigits = flo_ndigits(argc, argv);
2220 return rb_float_floor(num, ndigits);
2221}
2222
2223/*
2224 * :markup: markdown
2225 *
2226 * call-seq:
2227 * ceil(ndigits = 0) -> float or integer
2228 *
2229 * Returns a numeric that is a "ceiling" value for `self`,
2230 * as specified by the given `ndigits`,
2231 * which must be an
2232 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2233 *
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):
2237 *
2238 * ```
2239 * f = 12345.6789
2240 * f.ceil(1) # => 12345.7
2241 * f.ceil(3) # => 12345.679
2242 * f.ceil(30) # => 12345.6789
2243 * f = -12345.6789
2244 * f.ceil(1) # => -12345.6
2245 * f.ceil(3) # => -12345.678
2246 * f.ceil(30) # => -12345.6789
2247 * f = 0.0
2248 * f.ceil(1) # => 0.0
2249 * f.ceil(100) # => 0.0
2250 * ```
2251 *
2252 * When `ndigits` is non-positive,
2253 * returns an Integer based on a computed granularity:
2254 *
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`.
2258 *
2259 * Examples with positive `self`:
2260 *
2261 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2262 * |--------:|------------:|-------------------------:|
2263 * | 0 | 1 | 12346 |
2264 * | -1 | 10 | 12350 |
2265 * | -2 | 100 | 12400 |
2266 * | -3 | 1000 | 13000 |
2267 * | -4 | 10000 | 20000 |
2268 * | -5 | 100000 | 100000 |
2269 *
2270 * Examples with negative `self`:
2271 *
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 |
2280 *
2281 * When `self` is zero and `ndigits` is non-positive,
2282 * returns Integer zero:
2283 *
2284 * ```
2285 * 0.0.ceil(0) # => 0
2286 * 0.0.ceil(-1) # => 0
2287 * 0.0.ceil(-2) # => 0
2288 * ```
2289 *
2290 * Note that the limited precision of floating-point arithmetic
2291 * may lead to surprising results:
2292 *
2293 * ```
2294 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2295 * ```
2296 *
2297 * Related: Float#floor.
2298 *
2299 */
2300
2301static VALUE
2302flo_ceil(int argc, VALUE *argv, VALUE num)
2303{
2304 int ndigits = flo_ndigits(argc, argv);
2305 return rb_float_ceil(num, ndigits);
2306}
2307
2308VALUE
2309rb_float_ceil(VALUE num, int ndigits)
2310{
2311 double number, f;
2312
2313 number = RFLOAT_VALUE(num);
2314 if (number == 0.0) {
2315 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2316 }
2317 if (ndigits > 0) {
2318 int binexp;
2319 frexp(number, &binexp);
2320 if (float_round_overflow(ndigits, binexp)) return num;
2321 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2322 return DBL2NUM(0.0);
2323 f = pow(10, ndigits);
2324 f = ceil(number * f) / f;
2325 return DBL2NUM(f);
2326 }
2327 else {
2328 num = dbl2ival(ceil(number));
2329 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2330 return num;
2331 }
2332}
2333
2334static int
2335int_round_zero_p(VALUE num, int ndigits)
2336{
2337 long bytes;
2338 /* If 10**N / 2 > num, then return 0 */
2339 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2340 if (FIXNUM_P(num)) {
2341 bytes = sizeof(long);
2342 }
2343 else if (RB_BIGNUM_TYPE_P(num)) {
2344 bytes = rb_big_size(num);
2345 }
2346 else {
2347 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2348 }
2349 return (-0.415241 * ndigits - 0.125 > bytes);
2350}
2351
2352static SIGNED_VALUE
2353int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2354{
2355 SIGNED_VALUE z = +(x + y / 2) / y;
2356 if ((z * y - x) * 2 == y) {
2357 z &= ~1;
2358 }
2359 return z * y;
2360}
2361
2362static SIGNED_VALUE
2363int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2364{
2365 return (x + y / 2) / y * y;
2366}
2367
2368static SIGNED_VALUE
2369int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2370{
2371 return (x + y / 2 - 1) / y * y;
2372}
2373
2374static int
2375int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2376{
2377 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2378}
2379
2380static int
2381int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2382{
2383 return int_pos_p(num);
2384}
2385
2386static int
2387int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2388{
2389 return int_neg_p(num);
2390}
2391
2392/*
2393 * Assumes num is an \Integer, ndigits <= 0
2394 */
2395static VALUE
2396rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2397{
2398 VALUE n, f, h, r;
2399
2400 if (int_round_zero_p(num, ndigits)) {
2401 return INT2FIX(0);
2402 }
2403
2404 f = int_pow(10, -ndigits);
2405 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2406 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2407 int neg = x < 0;
2408 if (neg) x = -x;
2409 x = ROUND_CALL(mode, int_round, (x, y));
2410 if (neg) x = -x;
2411 return LONG2NUM(x);
2412 }
2413 if (RB_FLOAT_TYPE_P(f)) {
2414 /* then int_pow overflow */
2415 return INT2FIX(0);
2416 }
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);
2424 }
2425 return n;
2426}
2427
2428static VALUE
2429rb_int_floor(VALUE num, int ndigits)
2430{
2431 VALUE f = int_pow(10, -ndigits);
2432 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2433 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2434 int neg = x < 0;
2435 if (neg) x = -x + y - 1;
2436 x = x / y * y;
2437 if (neg) x = -x;
2438 return LONG2NUM(x);
2439 }
2440 else {
2441 bool neg = int_neg_p(num);
2442 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2443 num = rb_int_mul(rb_int_div(num, f), f);
2444 if (neg) num = rb_int_uminus(num);
2445 return num;
2446 }
2447}
2448
2449static VALUE
2450rb_int_ceil(VALUE num, int ndigits)
2451{
2452 VALUE f = int_pow(10, -ndigits);
2453 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2454 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2455 int neg = x < 0;
2456 if (neg) x = -x;
2457 else x += y - 1;
2458 x = (x / y) * y;
2459 if (neg) x = -x;
2460 return LONG2NUM(x);
2461 }
2462 else {
2463 bool neg = int_neg_p(num);
2464 if (neg)
2465 num = rb_int_uminus(num);
2466 else
2467 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2468 num = rb_int_mul(rb_int_div(num, f), f);
2469 if (neg) num = rb_int_uminus(num);
2470 return num;
2471 }
2472}
2473
2474VALUE
2475rb_int_truncate(VALUE num, int ndigits)
2476{
2477 VALUE f;
2478 VALUE m;
2479
2480 if (int_round_zero_p(num, ndigits))
2481 return INT2FIX(0);
2482 f = int_pow(10, -ndigits);
2483 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2484 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2485 int neg = x < 0;
2486 if (neg) x = -x;
2487 x = x / y * y;
2488 if (neg) x = -x;
2489 return LONG2NUM(x);
2490 }
2491 if (RB_FLOAT_TYPE_P(f)) {
2492 /* then int_pow overflow */
2493 return INT2FIX(0);
2494 }
2495 m = rb_int_modulo(num, f);
2496 if (int_neg_p(num)) {
2497 return rb_int_plus(num, rb_int_minus(f, m));
2498 }
2499 else {
2500 return rb_int_minus(num, m);
2501 }
2502}
2503
2504/*
2505 * call-seq:
2506 * round(ndigits = 0, half: :up) -> integer or float
2507 *
2508 * Returns +self+ rounded to the nearest value with
2509 * a precision of +ndigits+ decimal digits.
2510 *
2511 * When +ndigits+ is non-negative, returns a float with +ndigits+
2512 * after the decimal point (as available):
2513 *
2514 * f = 12345.6789
2515 * f.round(1) # => 12345.7
2516 * f.round(3) # => 12345.679
2517 * f = -12345.6789
2518 * f.round(1) # => -12345.7
2519 * f.round(3) # => -12345.679
2520 *
2521 * When +ndigits+ is negative, returns an integer
2522 * with at least <tt>ndigits.abs</tt> trailing zeros:
2523 *
2524 * f = 12345.6789
2525 * f.round(0) # => 12346
2526 * f.round(-3) # => 12000
2527 * f = -12345.6789
2528 * f.round(0) # => -12346
2529 * f.round(-3) # => -12000
2530 *
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:
2534 *
2535 * - +:up+ or +nil+: round away from zero:
2536 *
2537 * 2.5.round(half: :up) # => 3
2538 * 3.5.round(half: :up) # => 4
2539 * (-2.5).round(half: :up) # => -3
2540 *
2541 * - +:down+: round toward zero:
2542 *
2543 * 2.5.round(half: :down) # => 2
2544 * 3.5.round(half: :down) # => 3
2545 * (-2.5).round(half: :down) # => -2
2546 *
2547 * - +:even+: round toward the candidate whose last nonzero digit is even:
2548 *
2549 * 2.5.round(half: :even) # => 2
2550 * 3.5.round(half: :even) # => 4
2551 * (-2.5).round(half: :even) # => -2
2552 *
2553 * Raises and exception if the value for +half+ is invalid.
2554 *
2555 * Related: Float#truncate.
2556 *
2557 */
2558
2559static VALUE
2560flo_round(int argc, VALUE *argv, VALUE num)
2561{
2562 double number, f, x;
2563 VALUE nd, opt;
2564 int ndigits = 0;
2565 enum ruby_num_rounding_mode mode;
2566
2567 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2568 ndigits = NUM2INT(nd);
2569 }
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);
2574 }
2575 if (ndigits < 0) {
2576 return rb_int_round(flo_to_i(num), ndigits, mode);
2577 }
2578 if (ndigits == 0) {
2579 x = ROUND_CALL(mode, round, (number, 1.0));
2580 return dbl2ival(x);
2581 }
2582 if (isfinite(number)) {
2583 int binexp;
2584 frexp(number, &binexp);
2585 if (float_round_overflow(ndigits, binexp)) return num;
2586 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2587 if (ndigits > 14) {
2588 /* In this case, pow(10, ndigits) may not be accurate. */
2589 return rb_flo_round_by_rational(argc, argv, num);
2590 }
2591 f = pow(10, ndigits);
2592 x = ROUND_CALL(mode, round, (number, f));
2593 return DBL2NUM(x / f);
2594 }
2595 return num;
2596}
2597
2598static int
2599float_round_overflow(int ndigits, int binexp)
2600{
2601 enum {float_dig = DBL_DIG+2};
2602
2603/* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2604 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2605 Recall that up to float_dig digits can be needed to represent a double,
2606 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2607 will be an integer and thus the result is the original number.
2608 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2609 if ndigits + exp < 0, the result is 0.
2610 We have:
2611 2 ** (binexp-1) <= |number| < 2 ** binexp
2612 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2613 If binexp >= 0, and since log_2(10) = 3.322259:
2614 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2615 floor(binexp/4) <= exp <= ceil(binexp/3)
2616 If binexp <= 0, swap the /4 and the /3
2617 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2618 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2619*/
2620 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2621 return TRUE;
2622 }
2623 return FALSE;
2624}
2625
2626static int
2627float_round_underflow(int ndigits, int binexp)
2628{
2629 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2630 return TRUE;
2631 }
2632 return FALSE;
2633}
2634
2635/*
2636 * call-seq:
2637 * to_i -> integer
2638 *
2639 * Returns +self+ truncated to an Integer.
2640 *
2641 * 1.2.to_i # => 1
2642 * (-1.2).to_i # => -1
2643 *
2644 * Note that the limited precision of floating-point arithmetic
2645 * may lead to surprising results:
2646 *
2647 * (0.3 / 0.1).to_i # => 2 (!)
2648 *
2649 */
2650
2651static VALUE
2652flo_to_i(VALUE num)
2653{
2654 double f = RFLOAT_VALUE(num);
2655
2656 if (f > 0.0) f = floor(f);
2657 if (f < 0.0) f = ceil(f);
2658
2659 return dbl2ival(f);
2660}
2661
2662/*
2663 * call-seq:
2664 * truncate(ndigits = 0) -> float or integer
2665 *
2666 * Returns +self+ truncated (toward zero) to
2667 * a precision of +ndigits+ decimal digits.
2668 *
2669 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2670 * after the decimal point (as available):
2671 *
2672 * f = 12345.6789
2673 * f.truncate(1) # => 12345.6
2674 * f.truncate(3) # => 12345.678
2675 * f = -12345.6789
2676 * f.truncate(1) # => -12345.6
2677 * f.truncate(3) # => -12345.678
2678 *
2679 * When +ndigits+ is negative, returns an integer
2680 * with at least <tt>ndigits.abs</tt> trailing zeros:
2681 *
2682 * f = 12345.6789
2683 * f.truncate(0) # => 12345
2684 * f.truncate(-3) # => 12000
2685 * f = -12345.6789
2686 * f.truncate(0) # => -12345
2687 * f.truncate(-3) # => -12000
2688 *
2689 * Note that the limited precision of floating-point arithmetic
2690 * may lead to surprising results:
2691 *
2692 * (0.3 / 0.1).truncate #=> 2 (!)
2693 *
2694 * Related: Float#round.
2695 *
2696 */
2697static VALUE
2698flo_truncate(int argc, VALUE *argv, VALUE num)
2699{
2700 if (signbit(RFLOAT_VALUE(num)))
2701 return flo_ceil(argc, argv, num);
2702 else
2703 return flo_floor(argc, argv, num);
2704}
2705
2706/*
2707 * call-seq:
2708 * floor(ndigits = 0) -> float or integer
2709 *
2710 * Returns the largest float or integer that is less than or equal to +self+,
2711 * as specified by the given `ndigits`,
2712 * which must be an
2713 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2714 *
2715 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2716 *
2717 * Related: #ceil, Float#floor.
2718 */
2719
2720static VALUE
2721num_floor(int argc, VALUE *argv, VALUE num)
2722{
2723 return flo_floor(argc, argv, rb_Float(num));
2724}
2725
2726/*
2727 * call-seq:
2728 * ceil(ndigits = 0) -> float or integer
2729 *
2730 * Returns the smallest float or integer that is greater than or equal to +self+,
2731 * as specified by the given `ndigits`,
2732 * which must be an
2733 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2734 *
2735 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2736 *
2737 * Related: #floor, Float#ceil.
2738 */
2739
2740static VALUE
2741num_ceil(int argc, VALUE *argv, VALUE num)
2742{
2743 return flo_ceil(argc, argv, rb_Float(num));
2744}
2745
2746/*
2747 * call-seq:
2748 * round(digits = 0) -> integer or float
2749 *
2750 * Returns +self+ rounded to the nearest value with
2751 * a precision of +digits+ decimal digits.
2752 *
2753 * \Numeric implements this by converting +self+ to a Float and
2754 * invoking Float#round.
2755 */
2756
2757static VALUE
2758num_round(int argc, VALUE* argv, VALUE num)
2759{
2760 return flo_round(argc, argv, rb_Float(num));
2761}
2762
2763/*
2764 * call-seq:
2765 * truncate(digits = 0) -> integer or float
2766 *
2767 * Returns +self+ truncated (toward zero) to
2768 * a precision of +digits+ decimal digits.
2769 *
2770 * \Numeric implements this by converting +self+ to a Float and
2771 * invoking Float#truncate.
2772 */
2773
2774static VALUE
2775num_truncate(int argc, VALUE *argv, VALUE num)
2776{
2777 return flo_truncate(argc, argv, rb_Float(num));
2778}
2779
2780double
2781ruby_float_step_size(double beg, double end, double unit, int excl)
2782{
2783 const double epsilon = DBL_EPSILON;
2784 double d, n, err;
2785
2786 if (unit == 0) {
2787 return HUGE_VAL;
2788 }
2789 if (isinf(unit)) {
2790 return unit > 0 ? beg <= end : beg >= end;
2791 }
2792 n= (end - beg)/unit;
2793 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2794 if (err>0.5) err=0.5;
2795 if (excl) {
2796 if (n<=0) return 0;
2797 if (n<1)
2798 n = 0;
2799 else
2800 n = floor(n - err);
2801 d = +((n + 1) * unit) + beg;
2802 if (beg < end) {
2803 if (d < end)
2804 n++;
2805 }
2806 else if (beg > end) {
2807 if (d > end)
2808 n++;
2809 }
2810 }
2811 else {
2812 if (n<0) return 0;
2813 n = floor(n + err);
2814 d = +((n + 1) * unit) + beg;
2815 if (beg < end) {
2816 if (d <= end)
2817 n++;
2818 }
2819 else if (beg > end) {
2820 if (d >= end)
2821 n++;
2822 }
2823 }
2824 return n+1;
2825}
2826
2827int
2828ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2829{
2830 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2831 double unit = NUM2DBL(step);
2832 double beg = NUM2DBL(from);
2833 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2834 double n = ruby_float_step_size(beg, end, unit, excl);
2835 long i;
2836
2837 if (isinf(unit)) {
2838 /* if unit is infinity, i*unit+beg is NaN */
2839 if (n) rb_yield(DBL2NUM(beg));
2840 }
2841 else if (unit == 0) {
2842 VALUE val = DBL2NUM(beg);
2843 for (;;)
2844 rb_yield(val);
2845 }
2846 else {
2847 for (i=0; i<n; i++) {
2848 double d = i*unit+beg;
2849 if (unit >= 0 ? end < d : d < end) d = end;
2850 rb_yield(DBL2NUM(d));
2851 }
2852 }
2853 return TRUE;
2854 }
2855 return FALSE;
2856}
2857
2858VALUE
2859ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2860{
2861 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2862 long delta, diff;
2863
2864 diff = FIX2LONG(step);
2865 if (diff == 0) {
2866 return DBL2NUM(HUGE_VAL);
2867 }
2868 delta = FIX2LONG(to) - FIX2LONG(from);
2869 if (diff < 0) {
2870 diff = -diff;
2871 delta = -delta;
2872 }
2873 if (excl) {
2874 delta--;
2875 }
2876 if (delta < 0) {
2877 return INT2FIX(0);
2878 }
2879 return ULONG2NUM(delta / diff + 1UL);
2880 }
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);
2883
2884 if (isinf(n)) return DBL2NUM(n);
2885 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2886 return rb_dbl2big(n);
2887 }
2888 else {
2889 VALUE result;
2890 ID cmp = '>';
2891 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2892 case 0: return DBL2NUM(HUGE_VAL);
2893 case -1: cmp = '<'; break;
2894 }
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));
2899 }
2900 return result;
2901 }
2902}
2903
2904static int
2905num_step_negative_p(VALUE num)
2906{
2907 const ID mid = '<';
2908 VALUE zero = INT2FIX(0);
2909 VALUE r;
2910
2911 if (FIXNUM_P(num)) {
2912 if (method_basic_p(rb_cInteger))
2913 return (SIGNED_VALUE)num < 0;
2914 }
2915 else if (RB_BIGNUM_TYPE_P(num)) {
2916 if (method_basic_p(rb_cInteger))
2917 return BIGNUM_NEGATIVE_P(num);
2918 }
2919
2920 r = rb_check_funcall(num, '>', 1, &zero);
2921 if (UNDEF_P(r)) {
2922 coerce_failed(num, INT2FIX(0));
2923 }
2924 return !RTEST(r);
2925}
2926
2927static int
2928num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2929{
2930 VALUE hash;
2931
2932 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2933 if (!NIL_P(hash)) {
2934 ID keys[2];
2935 VALUE values[2];
2936 keys[0] = id_to;
2937 keys[1] = id_by;
2938 rb_get_kwargs(hash, keys, 0, 2, values);
2939 if (!UNDEF_P(values[0])) {
2940 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2941 *to = values[0];
2942 }
2943 if (!UNDEF_P(values[1])) {
2944 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2945 *by = values[1];
2946 }
2947 }
2948
2949 return argc;
2950}
2951
2952static int
2953num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2954{
2955 int desc;
2956 if (!UNDEF_P(by)) {
2957 *step = by;
2958 }
2959 else {
2960 /* compatibility */
2961 if (argc > 1 && NIL_P(*step)) {
2962 rb_raise(rb_eTypeError, "step must be numeric");
2963 }
2964 }
2965 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2966 rb_raise(rb_eArgError, "step can't be 0");
2967 }
2968 if (NIL_P(*step)) {
2969 *step = INT2FIX(1);
2970 }
2971 desc = num_step_negative_p(*step);
2972 if (fix_nil && NIL_P(*to)) {
2973 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2974 }
2975 return desc;
2976}
2977
2978static int
2979num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2980{
2981 VALUE by = Qundef;
2982 argc = num_step_extract_args(argc, argv, to, step, &by);
2983 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2984}
2985
2986static VALUE
2987num_step_size(VALUE from, VALUE args, VALUE eobj)
2988{
2989 VALUE to, step;
2990 int argc = args ? RARRAY_LENINT(args) : 0;
2991 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2992
2993 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2994
2995 return ruby_num_interval_step_size(from, to, step, FALSE);
2996}
2997
2998/*
2999 * call-seq:
3000 * step(to = nil, by = 1) {|n| ... } -> self
3001 * step(to = nil, by = 1) -> enumerator
3002 * step(to = nil, by: 1) {|n| ... } -> self
3003 * step(to = nil, by: 1) -> enumerator
3004 * step(by: 1, to: ) {|n| ... } -> self
3005 * step(by: 1, to: ) -> enumerator
3006 * step(by: , to: nil) {|n| ... } -> self
3007 * step(by: , to: nil) -> enumerator
3008 *
3009 * Generates a sequence of numbers; with a block given, traverses the sequence.
3010 *
3011 * Of the Core and Standard Library classes,
3012 * Integer, Float, and Rational use this implementation.
3013 *
3014 * A quick example:
3015 *
3016 * squares = []
3017 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
3018 * squares # => [1, 9, 25, 49, 81]
3019 *
3020 * The generated sequence:
3021 *
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.
3028 *
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.
3031 *
3032 * <b>Keyword Arguments</b>
3033 *
3034 * With keyword arguments +by+ and +to+,
3035 * their values (or defaults) determine the step and limit:
3036 *
3037 * # Both keywords given.
3038 * squares = []
3039 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
3040 * squares # => [16, 36, 64, 100]
3041 * cubes = []
3042 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
3043 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
3044 * squares = []
3045 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
3046 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3047 *
3048 * squares = []
3049 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
3050 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
3051 *
3052 * # Only keyword to given.
3053 * squares = []
3054 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
3055 * squares # => [16, 25, 36, 49, 64, 81, 100]
3056 * # Only by given.
3057 *
3058 * # Only keyword by given
3059 * squares = []
3060 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
3061 * squares # => [16, 36, 64, 100, 144]
3062 *
3063 * # No block given.
3064 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
3065 * e.class # => Enumerator::ArithmeticSequence
3066 *
3067 * <b>Positional Arguments</b>
3068 *
3069 * With optional positional arguments +to+ and +by+,
3070 * their values (or defaults) determine the step and limit:
3071 *
3072 * squares = []
3073 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
3074 * squares # => [16, 36, 64, 100]
3075 * squares = []
3076 * 4.step(10) {|i| squares.push(i*i) }
3077 * squares # => [16, 25, 36, 49, 64, 81, 100]
3078 * squares = []
3079 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3080 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3081 *
3082 * <b>Implementation Notes</b>
3083 *
3084 * If all the arguments are integers, the loop operates using an integer
3085 * counter.
3086 *
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>.
3091 *
3092 */
3093
3094static VALUE
3095num_step(int argc, VALUE *argv, VALUE from)
3096{
3097 VALUE to, step;
3098 int desc, inf;
3099
3100 if (!rb_block_given_p()) {
3101 VALUE by = Qundef;
3102
3103 num_step_extract_args(argc, argv, &to, &step, &by);
3104 if (!UNDEF_P(by)) {
3105 step = by;
3106 }
3107 if (NIL_P(step)) {
3108 step = INT2FIX(1);
3109 }
3110 else if (rb_equal(step, INT2FIX(0))) {
3111 rb_raise(rb_eArgError, "step can't be 0");
3112 }
3113 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3115 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3116 num_step_size, from, to, step, FALSE);
3117 }
3118
3119 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3120 }
3121
3122 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3123 if (rb_equal(step, INT2FIX(0))) {
3124 inf = 1;
3125 }
3126 else if (RB_FLOAT_TYPE_P(to)) {
3127 double f = RFLOAT_VALUE(to);
3128 inf = isinf(f) && (signbit(f) ? desc : !desc);
3129 }
3130 else inf = 0;
3131
3132 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3133 long i = FIX2LONG(from);
3134 long diff = FIX2LONG(step);
3135
3136 if (inf) {
3137 for (;; i += diff)
3138 rb_yield(LONG2FIX(i));
3139 }
3140 else {
3141 long end = FIX2LONG(to);
3142
3143 if (desc) {
3144 for (; i >= end; i += diff)
3145 rb_yield(LONG2FIX(i));
3146 }
3147 else {
3148 for (; i <= end; i += diff)
3149 rb_yield(LONG2FIX(i));
3150 }
3151 }
3152 }
3153 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3154 VALUE i = from;
3155
3156 if (inf) {
3157 for (;; i = rb_funcall(i, '+', 1, step))
3158 rb_yield(i);
3159 }
3160 else {
3161 ID cmp = desc ? '<' : '>';
3162
3163 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3164 rb_yield(i);
3165 }
3166 }
3167 return from;
3168}
3169
3170static char *
3171out_of_range_float(char (*pbuf)[24], VALUE val)
3172{
3173 char *const buf = *pbuf;
3174 char *s;
3175
3176 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3177 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3178 return buf;
3179}
3180
3181#define FLOAT_OUT_OF_RANGE(val, type) do { \
3182 char buf[24]; \
3183 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3184 out_of_range_float(&buf, (val))); \
3185} while (0)
3186
3187#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3188#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3189#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3190#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3191 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3192 LONG_MIN <= (n): \
3193 LONG_MIN_MINUS_ONE < (n))
3194
3195long
3197{
3198 again:
3199 if (NIL_P(val)) {
3200 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
3201 }
3202
3203 if (FIXNUM_P(val)) return FIX2LONG(val);
3204
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);
3209 }
3210 else {
3211 FLOAT_OUT_OF_RANGE(val, "integer");
3212 }
3213 }
3214 else if (RB_BIGNUM_TYPE_P(val)) {
3215 return rb_big2long(val);
3216 }
3217 else {
3218 val = rb_to_int(val);
3219 goto again;
3220 }
3221}
3222
3223static unsigned long
3224rb_num2ulong_internal(VALUE val, int *wrap_p)
3225{
3226 again:
3227 if (NIL_P(val)) {
3228 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3229 }
3230
3231 if (FIXNUM_P(val)) {
3232 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3233 if (wrap_p)
3234 *wrap_p = l < 0;
3235 return (unsigned long)l;
3236 }
3237 else if (RB_FLOAT_TYPE_P(val)) {
3238 double d = RFLOAT_VALUE(val);
3239 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3240 if (wrap_p)
3241 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3242 if (0 <= d)
3243 return (unsigned long)d;
3244 return (unsigned long)(long)d;
3245 }
3246 else {
3247 FLOAT_OUT_OF_RANGE(val, "integer");
3248 }
3249 }
3250 else if (RB_BIGNUM_TYPE_P(val)) {
3251 {
3252 unsigned long ul = rb_big2ulong(val);
3253 if (wrap_p)
3254 *wrap_p = BIGNUM_NEGATIVE_P(val);
3255 return ul;
3256 }
3257 }
3258 else {
3259 val = rb_to_int(val);
3260 goto again;
3261 }
3262}
3263
3264unsigned long
3266{
3267 return rb_num2ulong_internal(val, NULL);
3268}
3269
3270void
3272{
3273 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3274 num, num < 0 ? "small" : "big");
3275}
3276
3277#if SIZEOF_INT < SIZEOF_LONG
3278static void
3279check_int(long num)
3280{
3281 if ((long)(int)num != num) {
3282 rb_out_of_int(num);
3283 }
3284}
3285
3286static void
3287check_uint(unsigned long num, int sign)
3288{
3289 if (sign) {
3290 /* minus */
3291 if (num < (unsigned long)INT_MIN)
3292 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3293 }
3294 else {
3295 /* plus */
3296 if (UINT_MAX < num)
3297 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3298 }
3299}
3300
3301long
3302rb_num2int(VALUE val)
3303{
3304 long num = rb_num2long(val);
3305
3306 check_int(num);
3307 return num;
3308}
3309
3310long
3311rb_fix2int(VALUE val)
3312{
3313 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3314
3315 check_int(num);
3316 return num;
3317}
3318
3319unsigned long
3320rb_num2uint(VALUE val)
3321{
3322 int wrap;
3323 unsigned long num = rb_num2ulong_internal(val, &wrap);
3324
3325 check_uint(num, wrap);
3326 return num;
3327}
3328
3329unsigned long
3330rb_fix2uint(VALUE val)
3331{
3332 unsigned long num;
3333
3334 if (!FIXNUM_P(val)) {
3335 return rb_num2uint(val);
3336 }
3337 num = FIX2ULONG(val);
3338
3339 check_uint(num, FIXNUM_NEGATIVE_P(val));
3340 return num;
3341}
3342#else
3343long
3345{
3346 return rb_num2long(val);
3347}
3348
3349long
3351{
3352 return FIX2INT(val);
3353}
3354
3355unsigned long
3357{
3358 return rb_num2ulong(val);
3359}
3360
3361unsigned long
3363{
3364 return RB_FIX2ULONG(val);
3365}
3366#endif
3367
3368NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3369static void
3370rb_out_of_short(SIGNED_VALUE num)
3371{
3372 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3373 num, num < 0 ? "small" : "big");
3374}
3375
3376static void
3377check_short(long num)
3378{
3379 if ((long)(short)num != num) {
3380 rb_out_of_short(num);
3381 }
3382}
3383
3384static void
3385check_ushort(unsigned long num, int sign)
3386{
3387 if (sign) {
3388 /* minus */
3389 if (num < (unsigned long)SHRT_MIN)
3390 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3391 }
3392 else {
3393 /* plus */
3394 if (USHRT_MAX < num)
3395 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3396 }
3397}
3398
3399short
3401{
3402 long num = rb_num2long(val);
3403
3404 check_short(num);
3405 return num;
3406}
3407
3408short
3410{
3411 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3412
3413 check_short(num);
3414 return num;
3415}
3416
3417unsigned short
3419{
3420 int wrap;
3421 unsigned long num = rb_num2ulong_internal(val, &wrap);
3422
3423 check_ushort(num, wrap);
3424 return num;
3425}
3426
3427unsigned short
3429{
3430 unsigned long num;
3431
3432 if (!FIXNUM_P(val)) {
3433 return rb_num2ushort(val);
3434 }
3435 num = FIX2ULONG(val);
3436
3437 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3438 return num;
3439}
3440
3441VALUE
3443{
3444 long v;
3445
3446 if (FIXNUM_P(val)) return val;
3447
3448 v = rb_num2long(val);
3449 if (!FIXABLE(v))
3450 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3451 return LONG2FIX(v);
3452}
3453
3454#if HAVE_LONG_LONG
3455
3456#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3457#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3458#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3459#ifndef ULLONG_MAX
3460#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3461#endif
3462#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3463 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3464 LLONG_MIN <= (n): \
3465 LLONG_MIN_MINUS_ONE < (n))
3466
3468rb_num2ll(VALUE val)
3469{
3470 if (NIL_P(val)) {
3471 rb_raise(rb_eTypeError, "no implicit conversion from nil");
3472 }
3473
3474 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3475
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;
3480 }
3481 else {
3482 FLOAT_OUT_OF_RANGE(val, "long long");
3483 }
3484 }
3485 else if (RB_BIGNUM_TYPE_P(val)) {
3486 return rb_big2ll(val);
3487 }
3488 else if (RB_TYPE_P(val, T_STRING)) {
3489 rb_raise(rb_eTypeError, "no implicit conversion from string");
3490 }
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");
3493 }
3494
3495 val = rb_to_int(val);
3496 return NUM2LL(val);
3497}
3498
3499unsigned LONG_LONG
3500rb_num2ull(VALUE val)
3501{
3502 if (NIL_P(val)) {
3503 rb_raise(rb_eTypeError, "no implicit conversion of nil into Integer");
3504 }
3505 else if (FIXNUM_P(val)) {
3506 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3507 }
3508 else if (RB_FLOAT_TYPE_P(val)) {
3509 double d = RFLOAT_VALUE(val);
3510 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3511 if (0 <= d)
3512 return (unsigned LONG_LONG)d;
3513 return (unsigned LONG_LONG)(LONG_LONG)d;
3514 }
3515 else {
3516 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3517 }
3518 }
3519 else if (RB_BIGNUM_TYPE_P(val)) {
3520 return rb_big2ull(val);
3521 }
3522 else {
3523 val = rb_to_int(val);
3524 return NUM2ULL(val);
3525 }
3526}
3527
3528#endif /* HAVE_LONG_LONG */
3529
3530/********************************************************************
3531 *
3532 * Document-class: Integer
3533 *
3534 * An \Integer object represents an integer value.
3535 *
3536 * You can create an \Integer object explicitly with:
3537 *
3538 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3539 *
3540 * You can convert certain objects to Integers with:
3541 *
3542 * - Method #Integer.
3543 *
3544 * An attempt to add a singleton method to an instance of this class
3545 * causes an exception to be raised.
3546 *
3547 * == What's Here
3548 *
3549 * First, what's elsewhere. Class \Integer:
3550 *
3551 * - Inherits from
3552 * {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
3553 * and {class Object}[rdoc-ref:Object@What-27s+Here].
3554 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
3555 *
3556 * Here, class \Integer provides methods for:
3557 *
3558 * - {Querying}[rdoc-ref:Integer@Querying]
3559 * - {Comparing}[rdoc-ref:Integer@Comparing]
3560 * - {Converting}[rdoc-ref:Integer@Converting]
3561 * - {Other}[rdoc-ref:Integer@Other]
3562 *
3563 * === Querying
3564 *
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.
3568 *
3569 * === Comparing
3570 *
3571 * - #<: Returns whether +self+ is less than the given value.
3572 * - #<=: Returns whether +self+ is less than or equal to the given value.
3573 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3574 * to, or greater than the given value.
3575 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3576 * value.
3577 * - #>: Returns whether +self+ is greater than the given value.
3578 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3579 *
3580 * === Converting
3581 *
3582 * - ::sqrt: Returns the integer square root of the given value.
3583 * - ::try_convert: Returns the given value converted to an \Integer.
3584 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3585 * - #&: Returns the bitwise AND of +self+ and the given value.
3586 * - #*: Returns the product of +self+ and the given value.
3587 * - #**: Returns the value of +self+ raised to the power of the given value.
3588 * - #+: Returns the sum of +self+ and the given value.
3589 * - #-: Returns the difference of +self+ and the given value.
3590 * - #/: Returns the quotient of +self+ and the given value.
3591 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3592 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3593 * - #[]: Returns a slice of bits from +self+.
3594 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3595 * - #|: Returns the bitwise OR of +self+ and the given value.
3596 * - #ceil: Returns the smallest number greater than or equal to +self+.
3597 * - #chr: Returns a 1-character string containing the character
3598 * represented by the value of +self+.
3599 * - #digits: Returns an array of integers representing the base-radix digits
3600 * of +self+.
3601 * - #div: Returns the integer result of dividing +self+ by the given value.
3602 * - #divmod: Returns a 2-element array containing the quotient and remainder
3603 * results of dividing +self+ by the given value.
3604 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3605 * - #floor: Returns the greatest number smaller than or equal to +self+.
3606 * - #pow: Returns the modular exponentiation of +self+.
3607 * - #pred: Returns the integer predecessor of +self+.
3608 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3609 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3610 * - #succ (aliased as #next): Returns the integer successor of +self+.
3611 * - #to_f: Returns +self+ converted to a Float.
3612 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3613 * representation of +self+ in the given radix.
3614 * - #truncate: Returns +self+ truncated to the given precision.
3615 *
3616 * === Other
3617 *
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.
3624 *
3625 */
3626
3627VALUE
3628rb_int_odd_p(VALUE num)
3629{
3630 if (FIXNUM_P(num)) {
3631 return RBOOL(num & 2);
3632 }
3633 else {
3634 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3635 return rb_big_odd_p(num);
3636 }
3637}
3638
3639static VALUE
3640int_even_p(VALUE num)
3641{
3642 if (FIXNUM_P(num)) {
3643 return RBOOL((num & 2) == 0);
3644 }
3645 else {
3646 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3647 return rb_big_even_p(num);
3648 }
3649}
3650
3651VALUE
3652rb_int_even_p(VALUE num)
3653{
3654 return int_even_p(num);
3655}
3656
3657/*
3658 * call-seq:
3659 * allbits?(mask) -> true or false
3660 *
3661 * Returns +true+ if all bits that are set (=1) in +mask+
3662 * are also set in +self+; returns +false+ otherwise.
3663 *
3664 * Example values:
3665 *
3666 * 0b1010101 self
3667 * 0b1010100 mask
3668 * 0b1010100 self & mask
3669 * true self.allbits?(mask)
3670 *
3671 * 0b1010100 self
3672 * 0b1010101 mask
3673 * 0b1010100 self & mask
3674 * false self.allbits?(mask)
3675 *
3676 * Related: Integer#anybits?, Integer#nobits?.
3677 *
3678 */
3679
3680static VALUE
3681int_allbits_p(VALUE num, VALUE mask)
3682{
3683 mask = rb_to_int(mask);
3684 return rb_int_equal(rb_int_and(num, mask), mask);
3685}
3686
3687/*
3688 * call-seq:
3689 * anybits?(mask) -> true or false
3690 *
3691 * Returns +true+ if any bit that is set (=1) in +mask+
3692 * is also set in +self+; returns +false+ otherwise.
3693 *
3694 * Example values:
3695 *
3696 * 0b10000010 self
3697 * 0b11111111 mask
3698 * 0b10000010 self & mask
3699 * true self.anybits?(mask)
3700 *
3701 * 0b00000000 self
3702 * 0b11111111 mask
3703 * 0b00000000 self & mask
3704 * false self.anybits?(mask)
3705 *
3706 * Related: Integer#allbits?, Integer#nobits?.
3707 *
3708 */
3709
3710static VALUE
3711int_anybits_p(VALUE num, VALUE mask)
3712{
3713 mask = rb_to_int(mask);
3714 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3715}
3716
3717/*
3718 * call-seq:
3719 * nobits?(mask) -> true or false
3720 *
3721 * Returns +true+ if no bit that is set (=1) in +mask+
3722 * is also set in +self+; returns +false+ otherwise.
3723 *
3724 * Example values:
3725 *
3726 * 0b11110000 self
3727 * 0b00001111 mask
3728 * 0b00000000 self & mask
3729 * true self.nobits?(mask)
3730 *
3731 * 0b00000001 self
3732 * 0b11111111 mask
3733 * 0b00000001 self & mask
3734 * false self.nobits?(mask)
3735 *
3736 * Related: Integer#allbits?, Integer#anybits?.
3737 *
3738 */
3739
3740static VALUE
3741int_nobits_p(VALUE num, VALUE mask)
3742{
3743 mask = rb_to_int(mask);
3744 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3745}
3746
3747/*
3748 * call-seq:
3749 * succ -> next_integer
3750 *
3751 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3752 *
3753 * 1.succ #=> 2
3754 * -1.succ #=> 0
3755 *
3756 * Related: Integer#pred (predecessor value).
3757 */
3758
3759VALUE
3760rb_int_succ(VALUE num)
3761{
3762 if (FIXNUM_P(num)) {
3763 long i = FIX2LONG(num) + 1;
3764 return LONG2NUM(i);
3765 }
3766 if (RB_BIGNUM_TYPE_P(num)) {
3767 return rb_big_plus(num, INT2FIX(1));
3768 }
3769 return num_funcall1(num, '+', INT2FIX(1));
3770}
3771
3772#define int_succ rb_int_succ
3773
3774/*
3775 * call-seq:
3776 * pred -> next_integer
3777 *
3778 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3779 *
3780 * 1.pred #=> 0
3781 * -1.pred #=> -2
3782 *
3783 * Related: Integer#succ (successor value).
3784 *
3785 */
3786
3787static VALUE
3788rb_int_pred(VALUE num)
3789{
3790 if (FIXNUM_P(num)) {
3791 long i = FIX2LONG(num) - 1;
3792 return LONG2NUM(i);
3793 }
3794 if (RB_BIGNUM_TYPE_P(num)) {
3795 return rb_big_minus(num, INT2FIX(1));
3796 }
3797 return num_funcall1(num, '-', INT2FIX(1));
3798}
3799
3800#define int_pred rb_int_pred
3801
3802VALUE
3803rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3804{
3805 int n;
3806 VALUE str;
3807 switch (n = rb_enc_codelen(code, enc)) {
3808 case ONIGERR_INVALID_CODE_POINT_VALUE:
3809 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3810 break;
3811 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3812 case 0:
3813 rb_raise(rb_eRangeError, "%u out of char range", code);
3814 break;
3815 }
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));
3820 }
3821 return str;
3822}
3823
3824/* call-seq:
3825 * chr -> string
3826 * chr(encoding) -> string
3827 *
3828 * Returns a 1-character string containing the character
3829 * represented by the value of +self+, according to the given +encoding+.
3830 *
3831 * 65.chr # => "A"
3832 * 0.chr # => "\x00"
3833 * 255.chr # => "\xFF"
3834 * string = 255.chr(Encoding::UTF_8)
3835 * string.encoding # => Encoding::UTF_8
3836 *
3837 * Raises an exception if +self+ is negative.
3838 *
3839 * Related: Integer#ord.
3840 *
3841 */
3842
3843static VALUE
3844int_chr(int argc, VALUE *argv, VALUE num)
3845{
3846 char c;
3847 unsigned int i;
3848 rb_encoding *enc;
3849
3850 if (rb_num_to_uint(num, &i) == 0) {
3851 }
3852 else if (FIXNUM_P(num)) {
3853 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
3854 }
3855 else {
3856 rb_raise(rb_eRangeError, "bignum out of char range");
3857 }
3858
3859 switch (argc) {
3860 case 0:
3861 if (0xff < i) {
3862 enc = rb_default_internal_encoding();
3863 if (!enc) {
3864 rb_raise(rb_eRangeError, "%u out of char range", i);
3865 }
3866 goto decode;
3867 }
3868 c = (char)i;
3869 if (i < 0x80) {
3870 return rb_usascii_str_new(&c, 1);
3871 }
3872 else {
3873 return rb_str_new(&c, 1);
3874 }
3875 case 1:
3876 break;
3877 default:
3878 rb_error_arity(argc, 0, 1);
3879 }
3880 enc = rb_to_encoding(argv[0]);
3881 if (!enc) enc = rb_ascii8bit_encoding();
3882 decode:
3883 return rb_enc_uint_chr(i, enc);
3884}
3885
3886/*
3887 * Fixnum
3888 */
3889
3890static VALUE
3891fix_uminus(VALUE num)
3892{
3893 return LONG2NUM(-FIX2LONG(num));
3894}
3895
3896VALUE
3897rb_int_uminus(VALUE num)
3898{
3899 if (FIXNUM_P(num)) {
3900 return fix_uminus(num);
3901 }
3902 else {
3903 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3904 return rb_big_uminus(num);
3905 }
3906}
3907
3908VALUE
3909rb_fix2str(VALUE x, int base)
3910{
3911 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
3912 long val = FIX2LONG(x);
3913 unsigned long u;
3914 int neg = 0;
3915
3916 if (base < 2 || 36 < base) {
3917 rb_raise(rb_eArgError, "invalid radix %d", base);
3918 }
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);
3924 }
3925# else
3926 /* should do something like above code, but currently ruby does not know */
3927 /* such platforms */
3928# endif
3929#endif
3930 if (val == 0) {
3931 return rb_usascii_str_new2("0");
3932 }
3933 if (val < 0) {
3934 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
3935 neg = 1;
3936 }
3937 else {
3938 u = val;
3939 }
3940 do {
3941 *--b = ruby_digitmap[(int)(u % base)];
3942 } while (u /= base);
3943 if (neg) {
3944 *--b = '-';
3945 }
3946
3947 return rb_usascii_str_new(b, e - b);
3948}
3949
3950static VALUE rb_fix_to_s_static[10];
3951
3952VALUE
3953rb_fix_to_s(VALUE x)
3954{
3955 long i = FIX2LONG(x);
3956 if (i >= 0 && i < 10) {
3957 return rb_fix_to_s_static[i];
3958 }
3959 return rb_fix2str(x, 10);
3960}
3961
3962/*
3963 * call-seq:
3964 * to_s(base = 10) -> string
3965 *
3966 * Returns a string containing the place-value representation of +self+
3967 * in radix +base+ (in 2..36).
3968 *
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"
3976 *
3977 * Raises an exception if +base+ is out of range.
3978 */
3979
3980VALUE
3981rb_int_to_s(int argc, VALUE *argv, VALUE x)
3982{
3983 int base;
3984
3985 if (rb_check_arity(argc, 0, 1))
3986 base = NUM2INT(argv[0]);
3987 else
3988 base = 10;
3989 return rb_int2str(x, base);
3990}
3991
3992VALUE
3993rb_int2str(VALUE x, int base)
3994{
3995 if (FIXNUM_P(x)) {
3996 return rb_fix2str(x, base);
3997 }
3998 else if (RB_BIGNUM_TYPE_P(x)) {
3999 return rb_big2str(x, base);
4000 }
4001
4002 return rb_any_to_s(x);
4003}
4004
4005static VALUE
4006fix_plus(VALUE x, VALUE y)
4007{
4008 if (FIXNUM_P(y)) {
4009 return rb_fix_plus_fix(x, y);
4010 }
4011 else if (RB_BIGNUM_TYPE_P(y)) {
4012 return rb_big_plus(y, x);
4013 }
4014 else if (RB_FLOAT_TYPE_P(y)) {
4015 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4016 }
4017 else if (RB_TYPE_P(y, T_COMPLEX)) {
4018 return rb_complex_plus(y, x);
4019 }
4020 else {
4021 return rb_num_coerce_bin(x, y, '+');
4022 }
4023}
4024
4025VALUE
4026rb_fix_plus(VALUE x, VALUE y)
4027{
4028 return fix_plus(x, y);
4029}
4030
4031/*
4032 * call-seq:
4033 * self + numeric -> numeric_result
4034 *
4035 * Performs addition:
4036 *
4037 * 2 + 2 # => 4
4038 * -2 + 2 # => 0
4039 * -2 + -2 # => -4
4040 * 2 + 2.0 # => 4.0
4041 * 2 + Rational(2, 1) # => (4/1)
4042 * 2 + Complex(2, 0) # => (4+0i)
4043 *
4044 */
4045
4046VALUE
4047rb_int_plus(VALUE x, VALUE y)
4048{
4049 if (FIXNUM_P(x)) {
4050 return fix_plus(x, y);
4051 }
4052 else if (RB_BIGNUM_TYPE_P(x)) {
4053 return rb_big_plus(x, y);
4054 }
4055 return rb_num_coerce_bin(x, y, '+');
4056}
4057
4058static VALUE
4059fix_minus(VALUE x, VALUE y)
4060{
4061 if (FIXNUM_P(y)) {
4062 return rb_fix_minus_fix(x, y);
4063 }
4064 else if (RB_BIGNUM_TYPE_P(y)) {
4065 x = rb_int2big(FIX2LONG(x));
4066 return rb_big_minus(x, y);
4067 }
4068 else if (RB_FLOAT_TYPE_P(y)) {
4069 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4070 }
4071 else {
4072 return rb_num_coerce_bin(x, y, '-');
4073 }
4074}
4075
4076/*
4077 * call-seq:
4078 * self - numeric -> numeric_result
4079 *
4080 * Performs subtraction:
4081 *
4082 * 4 - 2 # => 2
4083 * -4 - 2 # => -6
4084 * -4 - -2 # => -2
4085 * 4 - 2.0 # => 2.0
4086 * 4 - Rational(2, 1) # => (2/1)
4087 * 4 - Complex(2, 0) # => (2+0i)
4088 *
4089 */
4090
4091VALUE
4092rb_int_minus(VALUE x, VALUE y)
4093{
4094 if (FIXNUM_P(x)) {
4095 return fix_minus(x, y);
4096 }
4097 else if (RB_BIGNUM_TYPE_P(x)) {
4098 return rb_big_minus(x, y);
4099 }
4100 return rb_num_coerce_bin(x, y, '-');
4101}
4102
4103
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))
4107
4108static VALUE
4109fix_mul(VALUE x, VALUE y)
4110{
4111 if (FIXNUM_P(y)) {
4112 return rb_fix_mul_fix(x, y);
4113 }
4114 else if (RB_BIGNUM_TYPE_P(y)) {
4115 switch (x) {
4116 case INT2FIX(0): return x;
4117 case INT2FIX(1): return y;
4118 }
4119 return rb_big_mul(y, x);
4120 }
4121 else if (RB_FLOAT_TYPE_P(y)) {
4122 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4123 }
4124 else if (RB_TYPE_P(y, T_COMPLEX)) {
4125 return rb_complex_mul(y, x);
4126 }
4127 else {
4128 return rb_num_coerce_bin(x, y, '*');
4129 }
4130}
4131
4132/*
4133 * call-seq:
4134 * self * numeric -> numeric_result
4135 *
4136 * Performs multiplication:
4137 *
4138 * 4 * 2 # => 8
4139 * 4 * -2 # => -8
4140 * -4 * 2 # => -8
4141 * 4 * 2.0 # => 8.0
4142 * 4 * Rational(1, 3) # => (4/3)
4143 * 4 * Complex(2, 0) # => (8+0i)
4144 */
4145
4146VALUE
4147rb_int_mul(VALUE x, VALUE y)
4148{
4149 if (FIXNUM_P(x)) {
4150 return fix_mul(x, y);
4151 }
4152 else if (RB_BIGNUM_TYPE_P(x)) {
4153 return rb_big_mul(x, y);
4154 }
4155 return rb_num_coerce_bin(x, y, '*');
4156}
4157
4158static double
4159fix_fdiv_double(VALUE x, VALUE y)
4160{
4161 if (FIXNUM_P(y)) {
4162 long iy = FIX2LONG(y);
4163#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4164 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4165 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4166 }
4167#endif
4168 return double_div_double(FIX2LONG(x), iy);
4169 }
4170 else if (RB_BIGNUM_TYPE_P(y)) {
4171 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4172 }
4173 else if (RB_FLOAT_TYPE_P(y)) {
4174 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4175 }
4176 else {
4177 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4178 }
4179}
4180
4181double
4182rb_int_fdiv_double(VALUE x, VALUE y)
4183{
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);
4189 }
4190 }
4191 if (FIXNUM_P(x)) {
4192 return fix_fdiv_double(x, y);
4193 }
4194 else if (RB_BIGNUM_TYPE_P(x)) {
4195 return rb_big_fdiv_double(x, y);
4196 }
4197 else {
4198 return nan("");
4199 }
4200}
4201
4202/*
4203 * call-seq:
4204 * fdiv(numeric) -> float
4205 *
4206 * Returns the Float result of dividing +self+ by +numeric+:
4207 *
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
4213 *
4214 * Raises an exception if +numeric+ cannot be converted to a Float.
4215 *
4216 */
4217
4218VALUE
4219rb_int_fdiv(VALUE x, VALUE y)
4220{
4221 if (RB_INTEGER_TYPE_P(x)) {
4222 return DBL2NUM(rb_int_fdiv_double(x, y));
4223 }
4224 return Qnil;
4225}
4226
4227static VALUE
4228fix_divide(VALUE x, VALUE y, ID op)
4229{
4230 if (FIXNUM_P(y)) {
4231 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4232 return rb_fix_div_fix(x, y);
4233 }
4234 else if (RB_BIGNUM_TYPE_P(y)) {
4235 x = rb_int2big(FIX2LONG(x));
4236 return rb_big_div(x, y);
4237 }
4238 else if (RB_FLOAT_TYPE_P(y)) {
4239 if (op == '/') {
4240 double d = FIX2LONG(x);
4241 return rb_flo_div_flo(DBL2NUM(d), y);
4242 }
4243 else {
4244 VALUE v;
4245 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4246 v = fix_divide(x, y, '/');
4247 return flo_floor(0, 0, v);
4248 }
4249 }
4250 else {
4251 if (RB_TYPE_P(y, T_RATIONAL) &&
4252 op == '/' && FIX2LONG(x) == 1)
4253 return rb_rational_reciprocal(y);
4254 return rb_num_coerce_bin(x, y, op);
4255 }
4256}
4257
4258static VALUE
4259fix_div(VALUE x, VALUE y)
4260{
4261 return fix_divide(x, y, '/');
4262}
4263
4264/*
4265 * call-seq:
4266 * self / numeric -> numeric_result
4267 *
4268 * Performs division; for integer +numeric+, truncates the result to an integer:
4269 *
4270 * 4 / 3 # => 1
4271 * 4 / -3 # => -2
4272 * -4 / 3 # => -2
4273 * -4 / -3 # => 1
4274 *
4275 * For other +numeric+, returns non-integer result:
4276 *
4277 * 4 / 3.0 # => 1.3333333333333333
4278 * 4 / Rational(3, 1) # => (4/3)
4279 * 4 / Complex(3, 0) # => ((4/3)+0i)
4280 *
4281 */
4282
4283VALUE
4284rb_int_div(VALUE x, VALUE y)
4285{
4286 if (FIXNUM_P(x)) {
4287 return fix_div(x, y);
4288 }
4289 else if (RB_BIGNUM_TYPE_P(x)) {
4290 return rb_big_div(x, y);
4291 }
4292 return Qnil;
4293}
4294
4295static VALUE
4296fix_idiv(VALUE x, VALUE y)
4297{
4298 return fix_divide(x, y, id_div);
4299}
4300
4301/*
4302 * call-seq:
4303 * div(numeric) -> integer
4304 *
4305 * Performs integer division; returns the integer result of dividing +self+
4306 * by +numeric+:
4307 *
4308 * 4.div(3) # => 1
4309 * 4.div(-3) # => -2
4310 * -4.div(3) # => -2
4311 * -4.div(-3) # => 1
4312 * 4.div(3.0) # => 1
4313 * 4.div(Rational(3, 1)) # => 1
4314 *
4315 * Raises an exception if +numeric+ does not have method +div+.
4316 *
4317 */
4318
4319VALUE
4320rb_int_idiv(VALUE x, VALUE y)
4321{
4322 if (FIXNUM_P(x)) {
4323 return fix_idiv(x, y);
4324 }
4325 else if (RB_BIGNUM_TYPE_P(x)) {
4326 return rb_big_idiv(x, y);
4327 }
4328 return num_div(x, y);
4329}
4330
4331static VALUE
4332fix_mod(VALUE x, VALUE y)
4333{
4334 if (FIXNUM_P(y)) {
4335 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4336 return rb_fix_mod_fix(x, y);
4337 }
4338 else if (RB_BIGNUM_TYPE_P(y)) {
4339 x = rb_int2big(FIX2LONG(x));
4340 return rb_big_modulo(x, y);
4341 }
4342 else if (RB_FLOAT_TYPE_P(y)) {
4343 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4344 }
4345 else {
4346 return rb_num_coerce_bin(x, y, '%');
4347 }
4348}
4349
4350/*
4351 * call-seq:
4352 * self % other -> real_number
4353 *
4354 * Returns +self+ modulo +other+ as a real number.
4355 *
4356 * For integer +n+ and real number +r+, these expressions are equivalent:
4357 *
4358 * n % r
4359 * n-r*(n/r).floor
4360 * n.divmod(r)[1]
4361 *
4362 * See Numeric#divmod.
4363 *
4364 * Examples:
4365 *
4366 * 10 % 2 # => 0
4367 * 10 % 3 # => 1
4368 * 10 % 4 # => 2
4369 *
4370 * 10 % -2 # => 0
4371 * 10 % -3 # => -2
4372 * 10 % -4 # => -2
4373 *
4374 * 10 % 3.0 # => 1.0
4375 * 10 % Rational(3, 1) # => (1/1)
4376 *
4377 */
4378VALUE
4379rb_int_modulo(VALUE x, VALUE y)
4380{
4381 if (FIXNUM_P(x)) {
4382 return fix_mod(x, y);
4383 }
4384 else if (RB_BIGNUM_TYPE_P(x)) {
4385 return rb_big_modulo(x, y);
4386 }
4387 return num_modulo(x, y);
4388}
4389
4390/*
4391 * call-seq:
4392 * remainder(other) -> real_number
4393 *
4394 * Returns the remainder after dividing +self+ by +other+.
4395 *
4396 * Examples:
4397 *
4398 * 11.remainder(4) # => 3
4399 * 11.remainder(-4) # => 3
4400 * -11.remainder(4) # => -3
4401 * -11.remainder(-4) # => -3
4402 *
4403 * 12.remainder(4) # => 0
4404 * 12.remainder(-4) # => 0
4405 * -12.remainder(4) # => 0
4406 * -12.remainder(-4) # => 0
4407 *
4408 * 13.remainder(4.0) # => 1.0
4409 * 13.remainder(Rational(4, 1)) # => (1/1)
4410 *
4411 */
4412
4413static VALUE
4414int_remainder(VALUE x, VALUE y)
4415{
4416 if (FIXNUM_P(x)) {
4417 if (FIXNUM_P(y)) {
4418 VALUE z = fix_mod(x, y);
4420 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4421 z = fix_minus(z, y);
4422 return z;
4423 }
4424 else if (!RB_BIGNUM_TYPE_P(y)) {
4425 return num_remainder(x, y);
4426 }
4427 x = rb_int2big(FIX2LONG(x));
4428 }
4429 else if (!RB_BIGNUM_TYPE_P(x)) {
4430 return Qnil;
4431 }
4432 return rb_big_remainder(x, y);
4433}
4434
4435static VALUE
4436fix_divmod(VALUE x, VALUE y)
4437{
4438 if (FIXNUM_P(y)) {
4439 VALUE div, mod;
4440 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4441 rb_fix_divmod_fix(x, y, &div, &mod);
4442 return rb_assoc_new(div, mod);
4443 }
4444 else if (RB_BIGNUM_TYPE_P(y)) {
4445 x = rb_int2big(FIX2LONG(x));
4446 return rb_big_divmod(x, y);
4447 }
4448 else if (RB_FLOAT_TYPE_P(y)) {
4449 {
4450 double div, mod;
4451 volatile VALUE a, b;
4452
4453 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4454 a = dbl2ival(div);
4455 b = DBL2NUM(mod);
4456 return rb_assoc_new(a, b);
4457 }
4458 }
4459 else {
4460 return rb_num_coerce_bin(x, y, id_divmod);
4461 }
4462}
4463
4464/*
4465 * call-seq:
4466 * divmod(other) -> array
4467 *
4468 * Returns a 2-element array <tt>[q, r]</tt>, where
4469 *
4470 * q = (self/other).floor # Quotient
4471 * r = self % other # Remainder
4472 *
4473 * Examples:
4474 *
4475 * 11.divmod(4) # => [2, 3]
4476 * 11.divmod(-4) # => [-3, -1]
4477 * -11.divmod(4) # => [-3, 1]
4478 * -11.divmod(-4) # => [2, -3]
4479 *
4480 * 12.divmod(4) # => [3, 0]
4481 * 12.divmod(-4) # => [-3, 0]
4482 * -12.divmod(4) # => [-3, 0]
4483 * -12.divmod(-4) # => [3, 0]
4484 *
4485 * 13.divmod(4.0) # => [3, 1.0]
4486 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4487 *
4488 */
4489VALUE
4490rb_int_divmod(VALUE x, VALUE y)
4491{
4492 if (FIXNUM_P(x)) {
4493 return fix_divmod(x, y);
4494 }
4495 else if (RB_BIGNUM_TYPE_P(x)) {
4496 return rb_big_divmod(x, y);
4497 }
4498 return Qnil;
4499}
4500
4501/*
4502 * call-seq:
4503 * self ** numeric -> numeric_result
4504 *
4505 * Raises +self+ to the power of +numeric+:
4506 *
4507 * 2 ** 3 # => 8
4508 * 2 ** -3 # => (1/8)
4509 * -2 ** 3 # => -8
4510 * -2 ** -3 # => (-1/8)
4511 * 2 ** 3.3 # => 9.849155306759329
4512 * 2 ** Rational(3, 1) # => (8/1)
4513 * 2 ** Complex(3, 0) # => (8+0i)
4514 *
4515 */
4516
4517static VALUE
4518int_pow(long x, unsigned long y)
4519{
4520 int neg = x < 0;
4521 long z = 1;
4522
4523 if (y == 0) return INT2FIX(1);
4524 if (y == 1) return LONG2NUM(x);
4525 if (neg) x = -x;
4526 if (y & 1)
4527 z = x;
4528 else
4529 neg = 0;
4530 y &= ~1;
4531 do {
4532 while (y % 2 == 0) {
4533 if (!FIT_SQRT_LONG(x)) {
4534 goto bignum;
4535 }
4536 x = x * x;
4537 y >>= 1;
4538 }
4539 {
4540 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4541 goto bignum;
4542 }
4543 z = x * z;
4544 }
4545 } while (--y);
4546 if (neg) z = -z;
4547 return LONG2NUM(z);
4548
4549 VALUE v;
4550 bignum:
4551 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4552 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4553 return v;
4554 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4555 return v;
4556}
4557
4558VALUE
4559rb_int_positive_pow(long x, unsigned long y)
4560{
4561 return int_pow(x, y);
4562}
4563
4564static VALUE
4565fix_pow_inverted(VALUE x, VALUE minusb)
4566{
4567 if (x == INT2FIX(0)) {
4570 }
4571 else {
4572 VALUE y = rb_int_pow(x, minusb);
4573
4574 if (RB_FLOAT_TYPE_P(y)) {
4575 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4576 return DBL2NUM(1.0 / d);
4577 }
4578 else {
4579 return rb_rational_raw(INT2FIX(1), y);
4580 }
4581 }
4582}
4583
4584static VALUE
4585fix_pow(VALUE x, VALUE y)
4586{
4587 long a = FIX2LONG(x);
4588
4589 if (FIXNUM_P(y)) {
4590 long b = FIX2LONG(y);
4591
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);
4599 }
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);
4607 }
4608 else if (RB_FLOAT_TYPE_P(y)) {
4609 double dy = RFLOAT_VALUE(y);
4610 if (dy == 0.0) return DBL2NUM(1.0);
4611 if (a == 0) {
4612 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4613 }
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));
4618 }
4619 else {
4620 return rb_num_coerce_bin(x, y, idPow);
4621 }
4622}
4623
4624/*
4625 * call-seq:
4626 * self ** numeric -> numeric_result
4627 *
4628 * Raises +self+ to the power of +numeric+:
4629 *
4630 * 2 ** 3 # => 8
4631 * 2 ** -3 # => (1/8)
4632 * -2 ** 3 # => -8
4633 * -2 ** -3 # => (-1/8)
4634 * 2 ** 3.3 # => 9.849155306759329
4635 * 2 ** Rational(3, 1) # => (8/1)
4636 * 2 ** Complex(3, 0) # => (8+0i)
4637 *
4638 */
4639VALUE
4640rb_int_pow(VALUE x, VALUE y)
4641{
4642 if (FIXNUM_P(x)) {
4643 return fix_pow(x, y);
4644 }
4645 else if (RB_BIGNUM_TYPE_P(x)) {
4646 return rb_big_pow(x, y);
4647 }
4648 return Qnil;
4649}
4650
4651VALUE
4652rb_num_pow(VALUE x, VALUE y)
4653{
4654 VALUE z = rb_int_pow(x, y);
4655 if (!NIL_P(z)) return z;
4656 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4657 if (SPECIAL_CONST_P(x)) return Qnil;
4658 switch (BUILTIN_TYPE(x)) {
4659 case T_COMPLEX:
4660 return rb_complex_pow(x, y);
4661 case T_RATIONAL:
4662 return rb_rational_pow(x, y);
4663 default:
4664 break;
4665 }
4666 return Qnil;
4667}
4668
4669static VALUE
4670fix_equal(VALUE x, VALUE y)
4671{
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);
4676 }
4677 else if (RB_FLOAT_TYPE_P(y)) {
4678 return rb_integer_float_eq(x, y);
4679 }
4680 else {
4681 return num_equal(x, y);
4682 }
4683}
4684
4685/*
4686 * call-seq:
4687 * self == other -> true or false
4688 *
4689 * Returns +true+ if +self+ is numerically equal to +other+; +false+ otherwise.
4690 *
4691 * 1 == 2 #=> false
4692 * 1 == 1.0 #=> true
4693 *
4694 * Related: Integer#eql? (requires +other+ to be an \Integer).
4695 */
4696
4697VALUE
4698rb_int_equal(VALUE x, VALUE y)
4699{
4700 if (FIXNUM_P(x)) {
4701 return fix_equal(x, y);
4702 }
4703 else if (RB_BIGNUM_TYPE_P(x)) {
4704 return rb_big_eq(x, y);
4705 }
4706 return Qnil;
4707}
4708
4709static VALUE
4710fix_cmp(VALUE x, VALUE y)
4711{
4712 if (x == y) return INT2FIX(0);
4713 if (FIXNUM_P(y)) {
4714 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4715 return INT2FIX(-1);
4716 }
4717 else if (RB_BIGNUM_TYPE_P(y)) {
4718 VALUE cmp = rb_big_cmp(y, x);
4719 switch (cmp) {
4720 case INT2FIX(+1): return INT2FIX(-1);
4721 case INT2FIX(-1): return INT2FIX(+1);
4722 }
4723 return cmp;
4724 }
4725 else if (RB_FLOAT_TYPE_P(y)) {
4726 return rb_integer_float_cmp(x, y);
4727 }
4728 else {
4729 return rb_num_coerce_cmp(x, y, id_cmp);
4730 }
4731}
4732
4733/*
4734 * call-seq:
4735 * self <=> other -> -1, 0, +1, or nil
4736 *
4737 * Returns:
4738 *
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.
4743 *
4744 * Examples:
4745 *
4746 * 1 <=> 2 # => -1
4747 * 1 <=> 1 # => 0
4748 * 1 <=> 0 # => 1
4749 * 1 <=> 'foo' # => nil
4750 *
4751 * 1 <=> 1.0 # => 0
4752 * 1 <=> Rational(1, 1) # => 0
4753 * 1 <=> Complex(1, 0) # => 0
4754 *
4755 * This method is the basis for comparisons in module Comparable.
4756 *
4757 */
4758
4759VALUE
4760rb_int_cmp(VALUE x, VALUE y)
4761{
4762 if (FIXNUM_P(x)) {
4763 return fix_cmp(x, y);
4764 }
4765 else if (RB_BIGNUM_TYPE_P(x)) {
4766 return rb_big_cmp(x, y);
4767 }
4768 else {
4769 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
4770 }
4771}
4772
4773static VALUE
4774fix_gt(VALUE x, VALUE y)
4775{
4776 if (FIXNUM_P(y)) {
4777 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4778 }
4779 else if (RB_BIGNUM_TYPE_P(y)) {
4780 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4781 }
4782 else if (RB_FLOAT_TYPE_P(y)) {
4783 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
4784 }
4785 else {
4786 return rb_num_coerce_relop(x, y, '>');
4787 }
4788}
4789
4790/*
4791 * call-seq:
4792 * self > other -> true or false
4793 *
4794 * Returns +true+ if the value of +self+ is greater than that of +other+:
4795 *
4796 * 1 > 0 # => true
4797 * 1 > 1 # => false
4798 * 1 > 2 # => false
4799 * 1 > 0.5 # => true
4800 * 1 > Rational(1, 2) # => true
4801 *
4802 * Raises an exception if the comparison cannot be made.
4803 *
4804 */
4805
4806VALUE
4807rb_int_gt(VALUE x, VALUE y)
4808{
4809 if (FIXNUM_P(x)) {
4810 return fix_gt(x, y);
4811 }
4812 else if (RB_BIGNUM_TYPE_P(x)) {
4813 return rb_big_gt(x, y);
4814 }
4815 return Qnil;
4816}
4817
4818static VALUE
4819fix_ge(VALUE x, VALUE y)
4820{
4821 if (FIXNUM_P(y)) {
4822 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
4823 }
4824 else if (RB_BIGNUM_TYPE_P(y)) {
4825 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
4826 }
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));
4830 }
4831 else {
4832 return rb_num_coerce_relop(x, y, idGE);
4833 }
4834}
4835
4836/*
4837 * call-seq:
4838 * self >= real -> true or false
4839 *
4840 * Returns +true+ if the value of +self+ is greater than or equal to
4841 * that of +other+:
4842 *
4843 * 1 >= 0 # => true
4844 * 1 >= 1 # => true
4845 * 1 >= 2 # => false
4846 * 1 >= 0.5 # => true
4847 * 1 >= Rational(1, 2) # => true
4848 *
4849 * Raises an exception if the comparison cannot be made.
4850 *
4851 */
4852
4853VALUE
4854rb_int_ge(VALUE x, VALUE y)
4855{
4856 if (FIXNUM_P(x)) {
4857 return fix_ge(x, y);
4858 }
4859 else if (RB_BIGNUM_TYPE_P(x)) {
4860 return rb_big_ge(x, y);
4861 }
4862 return Qnil;
4863}
4864
4865static VALUE
4866fix_lt(VALUE x, VALUE y)
4867{
4868 if (FIXNUM_P(y)) {
4869 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
4870 }
4871 else if (RB_BIGNUM_TYPE_P(y)) {
4872 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
4873 }
4874 else if (RB_FLOAT_TYPE_P(y)) {
4875 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
4876 }
4877 else {
4878 return rb_num_coerce_relop(x, y, '<');
4879 }
4880}
4881
4882/*
4883 * call-seq:
4884 * self < other -> true or false
4885 *
4886 * Returns +true+ if the value of +self+ is less than that of +other+:
4887 *
4888 * 1 < 0 # => false
4889 * 1 < 1 # => false
4890 * 1 < 2 # => true
4891 * 1 < 0.5 # => false
4892 * 1 < Rational(1, 2) # => false
4893 *
4894 * Raises an exception if the comparison cannot be made.
4895 *
4896 */
4897
4898static VALUE
4899int_lt(VALUE x, VALUE y)
4900{
4901 if (FIXNUM_P(x)) {
4902 return fix_lt(x, y);
4903 }
4904 else if (RB_BIGNUM_TYPE_P(x)) {
4905 return rb_big_lt(x, y);
4906 }
4907 return Qnil;
4908}
4909
4910static VALUE
4911fix_le(VALUE x, VALUE y)
4912{
4913 if (FIXNUM_P(y)) {
4914 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
4915 }
4916 else if (RB_BIGNUM_TYPE_P(y)) {
4917 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
4918 }
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));
4922 }
4923 else {
4924 return rb_num_coerce_relop(x, y, idLE);
4925 }
4926}
4927
4928/*
4929 * call-seq:
4930 * self <= real -> true or false
4931 *
4932 * Returns +true+ if the value of +self+ is less than or equal to
4933 * that of +other+:
4934 *
4935 * 1 <= 0 # => false
4936 * 1 <= 1 # => true
4937 * 1 <= 2 # => true
4938 * 1 <= 0.5 # => false
4939 * 1 <= Rational(1, 2) # => false
4940 *
4941 * Raises an exception if the comparison cannot be made.
4942 *
4943 */
4944
4945static VALUE
4946int_le(VALUE x, VALUE y)
4947{
4948 if (FIXNUM_P(x)) {
4949 return fix_le(x, y);
4950 }
4951 else if (RB_BIGNUM_TYPE_P(x)) {
4952 return rb_big_le(x, y);
4953 }
4954 return Qnil;
4955}
4956
4957static VALUE
4958fix_comp(VALUE num)
4959{
4960 return ~num | FIXNUM_FLAG;
4961}
4962
4963VALUE
4964rb_int_comp(VALUE num)
4965{
4966 if (FIXNUM_P(num)) {
4967 return fix_comp(num);
4968 }
4969 else if (RB_BIGNUM_TYPE_P(num)) {
4970 return rb_big_comp(num);
4971 }
4972 return Qnil;
4973}
4974
4975static VALUE
4976num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
4977{
4978 ID func = (ID)((VALUE *)arg)[0];
4979 VALUE x = ((VALUE *)arg)[1];
4980 if (recursive) {
4981 num_funcall_op_1_recursion(x, func, y);
4982 }
4983 return rb_check_funcall(x, func, 1, &y);
4984}
4985
4986VALUE
4988{
4989 VALUE ret, args[3];
4990
4991 args[0] = (VALUE)func;
4992 args[1] = x;
4993 args[2] = y;
4994 do_coerce(&args[1], &args[2], TRUE);
4995 ret = rb_exec_recursive_paired(num_funcall_bit_1,
4996 args[2], args[1], (VALUE)args);
4997 if (UNDEF_P(ret)) {
4998 /* show the original object, not coerced object */
4999 coerce_failed(x, y);
5000 }
5001 return ret;
5002}
5003
5004static VALUE
5005fix_and(VALUE x, VALUE y)
5006{
5007 if (FIXNUM_P(y)) {
5008 long val = FIX2LONG(x) & FIX2LONG(y);
5009 return LONG2NUM(val);
5010 }
5011
5012 if (RB_BIGNUM_TYPE_P(y)) {
5013 return rb_big_and(y, x);
5014 }
5015
5016 return rb_num_coerce_bit(x, y, '&');
5017}
5018
5019/*
5020 * call-seq:
5021 * self & other -> integer
5022 *
5023 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5024 * in +self+ and +other+ are 1, 0 otherwise:
5025 *
5026 * "%04b" % (0b0101 & 0b0110) # => "0100"
5027 *
5028 * Raises an exception if +other+ is not an \Integer.
5029 *
5030 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5031 *
5032 */
5033
5034VALUE
5035rb_int_and(VALUE x, VALUE y)
5036{
5037 if (FIXNUM_P(x)) {
5038 return fix_and(x, y);
5039 }
5040 else if (RB_BIGNUM_TYPE_P(x)) {
5041 return rb_big_and(x, y);
5042 }
5043 return Qnil;
5044}
5045
5046static VALUE
5047fix_or(VALUE x, VALUE y)
5048{
5049 if (FIXNUM_P(y)) {
5050 long val = FIX2LONG(x) | FIX2LONG(y);
5051 return LONG2NUM(val);
5052 }
5053
5054 if (RB_BIGNUM_TYPE_P(y)) {
5055 return rb_big_or(y, x);
5056 }
5057
5058 return rb_num_coerce_bit(x, y, '|');
5059}
5060
5061/*
5062 * call-seq:
5063 * self | other -> integer
5064 *
5065 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5066 * in +self+ or +other+ is 1, 0 otherwise:
5067 *
5068 * "%04b" % (0b0101 | 0b0110) # => "0111"
5069 *
5070 * Raises an exception if +other+ is not an \Integer.
5071 *
5072 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5073 *
5074 */
5075
5076static VALUE
5077int_or(VALUE x, VALUE y)
5078{
5079 if (FIXNUM_P(x)) {
5080 return fix_or(x, y);
5081 }
5082 else if (RB_BIGNUM_TYPE_P(x)) {
5083 return rb_big_or(x, y);
5084 }
5085 return Qnil;
5086}
5087
5088static VALUE
5089fix_xor(VALUE x, VALUE y)
5090{
5091 if (FIXNUM_P(y)) {
5092 long val = FIX2LONG(x) ^ FIX2LONG(y);
5093 return LONG2NUM(val);
5094 }
5095
5096 if (RB_BIGNUM_TYPE_P(y)) {
5097 return rb_big_xor(y, x);
5098 }
5099
5100 return rb_num_coerce_bit(x, y, '^');
5101}
5102
5103/*
5104 * call-seq:
5105 * self ^ other -> integer
5106 *
5107 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5108 * in +self+ and +other+ are different, 0 otherwise:
5109 *
5110 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5111 *
5112 * Raises an exception if +other+ is not an \Integer.
5113 *
5114 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5115 *
5116 */
5117
5118static VALUE
5119int_xor(VALUE x, VALUE y)
5120{
5121 if (FIXNUM_P(x)) {
5122 return fix_xor(x, y);
5123 }
5124 else if (RB_BIGNUM_TYPE_P(x)) {
5125 return rb_big_xor(x, y);
5126 }
5127 return Qnil;
5128}
5129
5130static VALUE
5131rb_fix_lshift(VALUE x, VALUE y)
5132{
5133 long val, width;
5134
5135 val = NUM2LONG(x);
5136 if (!val) return (rb_to_int(y), INT2FIX(0));
5137 if (!FIXNUM_P(y))
5138 return rb_big_lshift(rb_int2big(val), y);
5139 width = FIX2LONG(y);
5140 if (width < 0)
5141 return fix_rshift(val, (unsigned long)-width);
5142 return fix_lshift(val, width);
5143}
5144
5145static VALUE
5146fix_lshift(long val, unsigned long width)
5147{
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));
5151 }
5152 val = val << width;
5153 return LONG2NUM(val);
5154}
5155
5156/*
5157 * call-seq:
5158 * self << count -> integer
5159 *
5160 * Returns +self+ with bits shifted +count+ positions to the left,
5161 * or to the right if +count+ is negative:
5162 *
5163 * n = 0b11110000
5164 * "%08b" % (n << 1) # => "111100000"
5165 * "%08b" % (n << 3) # => "11110000000"
5166 * "%08b" % (n << -1) # => "01111000"
5167 * "%08b" % (n << -3) # => "00011110"
5168 *
5169 * Related: Integer#>>.
5170 *
5171 */
5172
5173VALUE
5174rb_int_lshift(VALUE x, VALUE y)
5175{
5176 if (FIXNUM_P(x)) {
5177 return rb_fix_lshift(x, y);
5178 }
5179 else if (RB_BIGNUM_TYPE_P(x)) {
5180 return rb_big_lshift(x, y);
5181 }
5182 return Qnil;
5183}
5184
5185static VALUE
5186rb_fix_rshift(VALUE x, VALUE y)
5187{
5188 long i, val;
5189
5190 val = FIX2LONG(x);
5191 if (!val) return (rb_to_int(y), INT2FIX(0));
5192 if (!FIXNUM_P(y))
5193 return rb_big_rshift(rb_int2big(val), y);
5194 i = FIX2LONG(y);
5195 if (i == 0) return x;
5196 if (i < 0)
5197 return fix_lshift(val, (unsigned long)-i);
5198 return fix_rshift(val, i);
5199}
5200
5201static VALUE
5202fix_rshift(long val, unsigned long i)
5203{
5204 if (i >= sizeof(long)*CHAR_BIT-1) {
5205 if (val < 0) return INT2FIX(-1);
5206 return INT2FIX(0);
5207 }
5208 val = RSHIFT(val, i);
5209 return LONG2FIX(val);
5210}
5211
5212/*
5213 * call-seq:
5214 * self >> count -> integer
5215 *
5216 * Returns +self+ with bits shifted +count+ positions to the right,
5217 * or to the left if +count+ is negative:
5218 *
5219 * n = 0b11110000
5220 * "%08b" % (n >> 1) # => "01111000"
5221 * "%08b" % (n >> 3) # => "00011110"
5222 * "%08b" % (n >> -1) # => "111100000"
5223 * "%08b" % (n >> -3) # => "11110000000"
5224 *
5225 * Related: Integer#<<.
5226 *
5227 */
5228
5229VALUE
5230rb_int_rshift(VALUE x, VALUE y)
5231{
5232 if (FIXNUM_P(x)) {
5233 return rb_fix_rshift(x, y);
5234 }
5235 else if (RB_BIGNUM_TYPE_P(x)) {
5236 return rb_big_rshift(x, y);
5237 }
5238 return Qnil;
5239}
5240
5241VALUE
5242rb_fix_aref(VALUE fix, VALUE idx)
5243{
5244 long val = FIX2LONG(fix);
5245 long i;
5246
5247 idx = rb_to_int(idx);
5248 if (!FIXNUM_P(idx)) {
5249 idx = rb_big_norm(idx);
5250 if (!FIXNUM_P(idx)) {
5251 if (!BIGNUM_SIGN(idx) || val >= 0)
5252 return INT2FIX(0);
5253 return INT2FIX(1);
5254 }
5255 }
5256 i = FIX2LONG(idx);
5257
5258 if (i < 0) return INT2FIX(0);
5259 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5260 if (val < 0) return INT2FIX(1);
5261 return INT2FIX(0);
5262 }
5263 if (val & (1L<<i))
5264 return INT2FIX(1);
5265 return INT2FIX(0);
5266}
5267
5268
5269/* copied from "r_less" in range.c */
5270/* compares _a_ and _b_ and returns:
5271 * < 0: a < b
5272 * = 0: a = b
5273 * > 0: a > b or non-comparable
5274 */
5275static int
5276compare_indexes(VALUE a, VALUE b)
5277{
5278 VALUE r = rb_funcall(a, id_cmp, 1, b);
5279
5280 if (NIL_P(r))
5281 return INT_MAX;
5282 return rb_cmpint(r, a, b);
5283}
5284
5285static VALUE
5286generate_mask(VALUE len)
5287{
5288 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5289}
5290
5291static VALUE
5292int_aref1(VALUE num, VALUE arg)
5293{
5294 VALUE orig_num = num, beg, end;
5295 int excl;
5296
5297 if (rb_range_values(arg, &beg, &end, &excl)) {
5298 if (NIL_P(beg)) {
5299 /* beginless range */
5300 if (!RTEST(num_negative_p(end))) {
5301 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5302 VALUE mask = generate_mask(end);
5303 if (int_zero_p(rb_int_and(num, mask))) {
5304 return INT2FIX(0);
5305 }
5306 else {
5307 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5308 }
5309 }
5310 else {
5311 return INT2FIX(0);
5312 }
5313 }
5314 num = rb_int_rshift(num, beg);
5315
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);
5322 }
5323 else if (cmp == 0) {
5324 if (excl) return INT2FIX(0);
5325 num = orig_num;
5326 arg = beg;
5327 goto one_bit;
5328 }
5329 return num;
5330 }
5331
5332one_bit:
5333 if (FIXNUM_P(num)) {
5334 return rb_fix_aref(num, arg);
5335 }
5336 else if (RB_BIGNUM_TYPE_P(num)) {
5337 return rb_big_aref(num, arg);
5338 }
5339 return Qnil;
5340}
5341
5342static VALUE
5343int_aref2(VALUE num, VALUE beg, VALUE len)
5344{
5345 num = rb_int_rshift(num, beg);
5346 VALUE mask = generate_mask(len);
5347 num = rb_int_and(num, mask);
5348 return num;
5349}
5350
5351/*
5352 * call-seq:
5353 * self[offset] -> 0 or 1
5354 * self[offset, size] -> integer
5355 * self[range] -> integer
5356 *
5357 * Returns a slice of bits from +self+.
5358 *
5359 * With argument +offset+, returns the bit at the given offset,
5360 * where offset 0 refers to the least significant bit:
5361 *
5362 * n = 0b10 # => 2
5363 * n[0] # => 0
5364 * n[1] # => 1
5365 * n[2] # => 0
5366 * n[3] # => 0
5367 *
5368 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5369 * Thus, negative index always returns zero:
5370 *
5371 * 255[-1] # => 0
5372 *
5373 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5374 * beginning at +offset+ and including bits of greater significance:
5375 *
5376 * n = 0b111000 # => 56
5377 * "%010b" % n[0, 10] # => "0000111000"
5378 * "%010b" % n[4, 10] # => "0000000011"
5379 *
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:
5382 *
5383 * n = 0b111000 # => 56
5384 * "%010b" % n[0..9] # => "0000111000"
5385 * "%010b" % n[4..9] # => "0000000011"
5386 *
5387 * Raises an exception if the slice cannot be constructed.
5388 */
5389
5390static VALUE
5391int_aref(int const argc, VALUE * const argv, VALUE const num)
5392{
5393 rb_check_arity(argc, 1, 2);
5394 if (argc == 2) {
5395 return int_aref2(num, argv[0], argv[1]);
5396 }
5397 return int_aref1(num, argv[0]);
5398
5399 return Qnil;
5400}
5401
5402/*
5403 * call-seq:
5404 * to_f -> float
5405 *
5406 * Converts +self+ to a Float:
5407 *
5408 * 1.to_f # => 1.0
5409 * -1.to_f # => -1.0
5410 *
5411 * If the value of +self+ does not fit in a Float,
5412 * the result is infinity:
5413 *
5414 * (10**400).to_f # => Infinity
5415 * (-10**400).to_f # => -Infinity
5416 *
5417 */
5418
5419static VALUE
5420int_to_f(VALUE num)
5421{
5422 double val;
5423
5424 if (FIXNUM_P(num)) {
5425 val = (double)FIX2LONG(num);
5426 }
5427 else if (RB_BIGNUM_TYPE_P(num)) {
5428 val = rb_big2dbl(num);
5429 }
5430 else {
5431 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5432 }
5433
5434 return DBL2NUM(val);
5435}
5436
5437static VALUE
5438fix_abs(VALUE fix)
5439{
5440 long i = FIX2LONG(fix);
5441
5442 if (i < 0) i = -i;
5443
5444 return LONG2NUM(i);
5445}
5446
5447VALUE
5448rb_int_abs(VALUE num)
5449{
5450 if (FIXNUM_P(num)) {
5451 return fix_abs(num);
5452 }
5453 else if (RB_BIGNUM_TYPE_P(num)) {
5454 return rb_big_abs(num);
5455 }
5456 return Qnil;
5457}
5458
5459static VALUE
5460fix_size(VALUE fix)
5461{
5462 return INT2FIX(sizeof(long));
5463}
5464
5465VALUE
5466rb_int_size(VALUE num)
5467{
5468 if (FIXNUM_P(num)) {
5469 return fix_size(num);
5470 }
5471 else if (RB_BIGNUM_TYPE_P(num)) {
5472 return rb_big_size_m(num);
5473 }
5474 return Qnil;
5475}
5476
5477static VALUE
5478rb_fix_bit_length(VALUE fix)
5479{
5480 long v = FIX2LONG(fix);
5481 if (v < 0)
5482 v = ~v;
5483 return LONG2FIX(bit_length(v));
5484}
5485
5486VALUE
5487rb_int_bit_length(VALUE num)
5488{
5489 if (FIXNUM_P(num)) {
5490 return rb_fix_bit_length(num);
5491 }
5492 else if (RB_BIGNUM_TYPE_P(num)) {
5493 return rb_big_bit_length(num);
5494 }
5495 return Qnil;
5496}
5497
5498static VALUE
5499rb_fix_digits(VALUE fix, long base)
5500{
5501 VALUE digits;
5502 long x = FIX2LONG(fix);
5503
5504 RUBY_ASSERT(x >= 0);
5505
5506 if (base < 2)
5507 rb_raise(rb_eArgError, "invalid radix %ld", base);
5508
5509 if (x == 0)
5510 return rb_ary_new_from_args(1, INT2FIX(0));
5511
5512 digits = rb_ary_new();
5513 while (x >= base) {
5514 long q = x % base;
5515 rb_ary_push(digits, LONG2NUM(q));
5516 x /= base;
5517 }
5518 rb_ary_push(digits, LONG2NUM(x));
5519
5520 return digits;
5521}
5522
5523static VALUE
5524rb_int_digits_bigbase(VALUE num, VALUE base)
5525{
5526 VALUE digits, bases;
5527
5528 RUBY_ASSERT(!rb_num_negative_p(num));
5529
5530 if (RB_BIGNUM_TYPE_P(base))
5531 base = rb_big_norm(base);
5532
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");
5537
5538 if (FIXNUM_P(base) && FIXNUM_P(num))
5539 return rb_fix_digits(num, FIX2LONG(base));
5540
5541 if (FIXNUM_P(num))
5542 return rb_ary_new_from_args(1, num);
5543
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);
5550 }
5551 return digits;
5552 }
5553
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);
5557 }
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);
5569 }
5570 }
5571
5572 return digits;
5573}
5574
5575/*
5576 * call-seq:
5577 * digits(base = 10) -> array_of_integers
5578 *
5579 * Returns an array of integers representing the +base+-radix
5580 * digits of +self+;
5581 * the first element of the array represents the least significant digit:
5582 *
5583 * 12345.digits # => [5, 4, 3, 2, 1]
5584 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5585 * 12345.digits(100) # => [45, 23, 1]
5586 *
5587 * Raises an exception if +self+ is negative or +base+ is less than 2.
5588 *
5589 */
5590
5591static VALUE
5592rb_int_digits(int argc, VALUE *argv, VALUE num)
5593{
5594 VALUE base_value;
5595 long base;
5596
5597 if (rb_num_negative_p(num))
5598 rb_raise(rb_eMathDomainError, "out of domain");
5599
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);
5607
5608 base = FIX2LONG(base_value);
5609 if (base < 0)
5610 rb_raise(rb_eArgError, "negative radix");
5611 else if (base < 2)
5612 rb_raise(rb_eArgError, "invalid radix %ld", base);
5613 }
5614 else
5615 base = 10;
5616
5617 if (FIXNUM_P(num))
5618 return rb_fix_digits(num, base);
5619 else if (RB_BIGNUM_TYPE_P(num))
5620 return rb_int_digits_bigbase(num, LONG2FIX(base));
5621
5622 return Qnil;
5623}
5624
5625static VALUE
5626int_upto_size(VALUE from, VALUE args, VALUE eobj)
5627{
5628 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5629}
5630
5631/*
5632 * call-seq:
5633 * upto(limit) {|i| ... } -> self
5634 * upto(limit) -> enumerator
5635 *
5636 * Calls the given block with each integer value from +self+ up to +limit+;
5637 * returns +self+:
5638 *
5639 * a = []
5640 * 5.upto(10) {|i| a << i } # => 5
5641 * a # => [5, 6, 7, 8, 9, 10]
5642 * a = []
5643 * -5.upto(0) {|i| a << i } # => -5
5644 * a # => [-5, -4, -3, -2, -1, 0]
5645 * 5.upto(4) {|i| fail 'Cannot happen' } # => 5
5646 *
5647 * With no block given, returns an Enumerator.
5648 *
5649 */
5650
5651static VALUE
5652int_upto(VALUE from, VALUE to)
5653{
5654 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size);
5655 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5656 long i, end;
5657
5658 end = FIX2LONG(to);
5659 for (i = FIX2LONG(from); i <= end; i++) {
5660 rb_yield(LONG2FIX(i));
5661 }
5662 }
5663 else {
5664 VALUE i = from, c;
5665
5666 while (!(c = rb_funcall(i, '>', 1, to))) {
5667 rb_yield(i);
5668 i = rb_funcall(i, '+', 1, INT2FIX(1));
5669 }
5670 ensure_cmp(c, i, to);
5671 }
5672 return from;
5673}
5674
5675static VALUE
5676int_downto_size(VALUE from, VALUE args, VALUE eobj)
5677{
5678 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5679}
5680
5681/*
5682 * call-seq:
5683 * downto(limit) {|i| ... } -> self
5684 * downto(limit) -> enumerator
5685 *
5686 * Calls the given block with each integer value from +self+ down to +limit+;
5687 * returns +self+:
5688 *
5689 * a = []
5690 * 10.downto(5) {|i| a << i } # => 10
5691 * a # => [10, 9, 8, 7, 6, 5]
5692 * a = []
5693 * 0.downto(-5) {|i| a << i } # => 0
5694 * a # => [0, -1, -2, -3, -4, -5]
5695 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5696 *
5697 * With no block given, returns an Enumerator.
5698 *
5699 */
5700
5701static VALUE
5702int_downto(VALUE from, VALUE to)
5703{
5704 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5705 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5706 long i, end;
5707
5708 end = FIX2LONG(to);
5709 for (i=FIX2LONG(from); i >= end; i--) {
5710 rb_yield(LONG2FIX(i));
5711 }
5712 }
5713 else {
5714 VALUE i = from, c;
5715
5716 while (!(c = rb_funcall(i, '<', 1, to))) {
5717 rb_yield(i);
5718 i = rb_funcall(i, '-', 1, INT2FIX(1));
5719 }
5720 if (NIL_P(c)) rb_cmperr(i, to);
5721 }
5722 return from;
5723}
5724
5725static VALUE
5726int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5727{
5728 return int_neg_p(num) ? INT2FIX(0) : num;
5729}
5730
5731/*
5732 * call-seq:
5733 * round(ndigits= 0, half: :up) -> integer
5734 *
5735 * Returns +self+ rounded to the nearest value with
5736 * a precision of +ndigits+ decimal digits.
5737 *
5738 * When +ndigits+ is negative, the returned value
5739 * has at least <tt>ndigits.abs</tt> trailing zeros:
5740 *
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
5746 *
5747 * Returns +self+ when +ndigits+ is zero or positive.
5748 *
5749 * 555.round # => 555
5750 * 555.round(1) # => 555
5751 * 555.round(50) # => 555
5752 *
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:
5756 *
5757 * - +:up+ or +nil+: round away from zero:
5758 *
5759 * 25.round(-1, half: :up) # => 30
5760 * (-25).round(-1, half: :up) # => -30
5761 *
5762 * - +:down+: round toward zero:
5763 *
5764 * 25.round(-1, half: :down) # => 20
5765 * (-25).round(-1, half: :down) # => -20
5766 *
5767 *
5768 * - +:even+: round toward the candidate whose last nonzero digit is even:
5769 *
5770 * 25.round(-1, half: :even) # => 20
5771 * 15.round(-1, half: :even) # => 20
5772 * (-25).round(-1, half: :even) # => -20
5773 *
5774 * Raises and exception if the value for +half+ is invalid.
5775 *
5776 * Related: Integer#truncate.
5777 *
5778 */
5779
5780static VALUE
5781int_round(int argc, VALUE* argv, VALUE num)
5782{
5783 int ndigits;
5784 int mode;
5785 VALUE nd, opt;
5786
5787 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
5788 ndigits = NUM2INT(nd);
5789 mode = rb_num_get_rounding_option(opt);
5790 if (ndigits >= 0) {
5791 return num;
5792 }
5793 return rb_int_round(num, ndigits, mode);
5794}
5795
5796/*
5797 * :markup: markdown
5798 *
5799 * call-seq:
5800 * floor(ndigits = 0) -> integer
5801 *
5802 * Returns an integer that is a "floor" value for `self`,
5803 * as specified by the given `ndigits`,
5804 * which must be an
5805 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5806 *
5807 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5808 *
5809 * ```
5810 * 0.floor(2) # => 0
5811 * 0.floor(-2) # => 0
5812 * ```
5813 *
5814 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5815 *
5816 * ```
5817 * 555.floor # => 555
5818 * 555.floor(50) # => 555
5819 * ```
5820 *
5821 * - When `self` is non-zero and `ndigits` is negative,
5822 * returns a value based on a computed granularity:
5823 *
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`.
5827 *
5828 * Examples with positive `self`:
5829 *
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 |
5837 *
5838 * Examples with negative `self`:
5839 *
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 |
5847 *
5848 * Related: Integer#ceil.
5849 *
5850 */
5851
5852static VALUE
5853int_floor(int argc, VALUE* argv, VALUE num)
5854{
5855 int ndigits;
5856
5857 if (!rb_check_arity(argc, 0, 1)) return num;
5858 ndigits = NUM2INT(argv[0]);
5859 if (ndigits >= 0) {
5860 return num;
5861 }
5862 return rb_int_floor(num, ndigits);
5863}
5864
5865/*
5866 * :markup: markdown
5867 *
5868 * call-seq:
5869 * ceil(ndigits = 0) -> integer
5870 *
5871 * Returns an integer that is a "ceiling" value for `self`,
5872 * as specified by the given `ndigits`,
5873 * which must be an
5874 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
5875 *
5876 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
5877 *
5878 * ```
5879 * 0.ceil(2) # => 0
5880 * 0.ceil(-2) # => 0
5881 * ```
5882 *
5883 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
5884 *
5885 * ```
5886 * 555.ceil # => 555
5887 * 555.ceil(50) # => 555
5888 * ```
5889 *
5890 * - When `self` is non-zero and `ndigits` is negative,
5891 * returns a value based on a computed granularity:
5892 *
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`.
5896 *
5897 * Examples with positive `self`:
5898 *
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 |
5906 *
5907 * Examples with negative `self`:
5908 *
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 |
5916 *
5917 * Related: Integer#floor.
5918 */
5919
5920static VALUE
5921int_ceil(int argc, VALUE* argv, VALUE num)
5922{
5923 int ndigits;
5924
5925 if (!rb_check_arity(argc, 0, 1)) return num;
5926 ndigits = NUM2INT(argv[0]);
5927 if (ndigits >= 0) {
5928 return num;
5929 }
5930 return rb_int_ceil(num, ndigits);
5931}
5932
5933/*
5934 * call-seq:
5935 * truncate(ndigits = 0) -> integer
5936 *
5937 * Returns +self+ truncated (toward zero) to
5938 * a precision of +ndigits+ decimal digits.
5939 *
5940 * When +ndigits+ is negative, the returned value
5941 * has at least <tt>ndigits.abs</tt> trailing zeros:
5942 *
5943 * 555.truncate(-1) # => 550
5944 * 555.truncate(-2) # => 500
5945 * -555.truncate(-2) # => -500
5946 *
5947 * Returns +self+ when +ndigits+ is zero or positive.
5948 *
5949 * 555.truncate # => 555
5950 * 555.truncate(50) # => 555
5951 *
5952 * Related: Integer#round.
5953 *
5954 */
5955
5956static VALUE
5957int_truncate(int argc, VALUE* argv, VALUE num)
5958{
5959 int ndigits;
5960
5961 if (!rb_check_arity(argc, 0, 1)) return num;
5962 ndigits = NUM2INT(argv[0]);
5963 if (ndigits >= 0) {
5964 return num;
5965 }
5966 return rb_int_truncate(num, ndigits);
5967}
5968
5969#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
5970rettype \
5971prefix##_isqrt(argtype n) \
5972{ \
5973 if (!argtype##_IN_DOUBLE_P(n)) { \
5974 unsigned int b = bit_length(n); \
5975 argtype t; \
5976 rettype x = (rettype)(n >> (b/2+1)); \
5977 x |= ((rettype)1LU << (b-1)/2); \
5978 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
5979 return x; \
5980 } \
5981 return (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
5982}
5983
5984#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
5985# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
5986#else
5987# define RB_ULONG_IN_DOUBLE_P(n) 1
5988#endif
5989#define RB_ULONG_TO_DOUBLE(n) (double)(n)
5990#define RB_ULONG unsigned long
5991DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
5992
5993#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
5994# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
5995# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
5996# else
5997# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
5998# endif
5999# ifdef ULL_TO_DOUBLE
6000# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6001# else
6002# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6003# endif
6004DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6005#endif
6006
6007#define domain_error(msg) \
6008 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6009
6010/*
6011 * call-seq:
6012 * Integer.sqrt(numeric) -> integer
6013 *
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+.
6017 *
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
6023 *
6024 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6025 *
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
6030 *
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.
6034 *
6035 * Integer.sqrt(10**46) # => 100000000000000000000000
6036 * Math.sqrt(10**46).floor # => 99999999999999991611392
6037 *
6038 * Raises an exception if +numeric+ is negative.
6039 *
6040 */
6041
6042static VALUE
6043rb_int_s_isqrt(VALUE self, VALUE num)
6044{
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");
6050 }
6051 n = FIX2ULONG(num);
6052 sq = rb_ulong_isqrt(n);
6053 return LONG2FIX(sq);
6054 }
6055 else {
6056 size_t biglen;
6057 if (RBIGNUM_NEGATIVE_P(num)) {
6058 domain_error("isqrt");
6059 }
6060 biglen = BIGNUM_LEN(num);
6061 if (biglen == 0) return INT2FIX(0);
6062#if SIZEOF_BDIGIT <= SIZEOF_LONG
6063 /* short-circuit */
6064 if (biglen == 1) {
6065 n = BIGNUM_DIGITS(num)[0];
6066 sq = rb_ulong_isqrt(n);
6067 return ULONG2NUM(sq);
6068 }
6069#endif
6070 return rb_big_isqrt(num);
6071 }
6072}
6073
6074/*
6075 * call-seq:
6076 * Integer.try_convert(object) -> object, integer, or nil
6077 *
6078 * If +object+ is an \Integer object, returns +object+.
6079 * Integer.try_convert(1) # => 1
6080 *
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
6084 *
6085 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6086 * Integer.try_convert([]) # => nil
6087 *
6088 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6089 */
6090static VALUE
6091int_s_try_convert(VALUE self, VALUE num)
6092{
6093 return rb_check_integer_type(num);
6094}
6095
6096/*
6097 * Document-class: ZeroDivisionError
6098 *
6099 * Raised when attempting to divide an integer by 0.
6100 *
6101 * 42 / 0 #=> ZeroDivisionError: divided by 0
6102 *
6103 * Note that only division by an exact 0 will raise the exception:
6104 *
6105 * 42 / 0.0 #=> Float::INFINITY
6106 * 42 / -0.0 #=> -Float::INFINITY
6107 * 0 / 0.0 #=> NaN
6108 */
6109
6110/*
6111 * Document-class: FloatDomainError
6112 *
6113 * Raised when attempting to convert special float values (in particular
6114 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6115 *
6116 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6117 */
6118
6119/*
6120 * Document-class: Numeric
6121 *
6122 * \Numeric is the class from which all higher-level numeric classes should inherit.
6123 *
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.
6127 *
6128 * a = 1
6129 * 1.object_id == a.object_id #=> true
6130 *
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.
6133 *
6134 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6135 * 1.dup #=> 1
6136 * 1.object_id == 1.dup.object_id #=> true
6137 *
6138 * For this reason, \Numeric should be used when defining other numeric classes.
6139 *
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).
6143 *
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.
6148 *
6149 * class Tally < Numeric
6150 * def initialize(string)
6151 * @string = string
6152 * end
6153 *
6154 * def to_s
6155 * @string
6156 * end
6157 *
6158 * def to_i
6159 * @string.size
6160 * end
6161 *
6162 * def coerce(other)
6163 * [self.class.new('|' * other.to_i), self]
6164 * end
6165 *
6166 * def <=>(other)
6167 * to_i <=> other.to_i
6168 * end
6169 *
6170 * def +(other)
6171 * self.class.new('|' * (to_i + other.to_i))
6172 * end
6173 *
6174 * def -(other)
6175 * self.class.new('|' * (to_i - other.to_i))
6176 * end
6177 *
6178 * def *(other)
6179 * self.class.new('|' * (to_i * other.to_i))
6180 * end
6181 *
6182 * def /(other)
6183 * self.class.new('|' * (to_i / other.to_i))
6184 * end
6185 * end
6186 *
6187 * tally = Tally.new('||')
6188 * puts tally * 2 #=> "||||"
6189 * puts tally > 1 #=> true
6190 *
6191 * == What's Here
6192 *
6193 * First, what's elsewhere. Class \Numeric:
6194 *
6195 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6196 * - Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].
6197 *
6198 * Here, class \Numeric provides methods for:
6199 *
6200 * - {Querying}[rdoc-ref:Numeric@Querying]
6201 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6202 * - {Converting}[rdoc-ref:Numeric@Converting]
6203 * - {Other}[rdoc-ref:Numeric@Other]
6204 *
6205 * === Querying
6206 *
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.
6216 *
6217 * === Comparing
6218 *
6219 * - #<=>: Returns:
6220 *
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.
6225 *
6226 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6227 *
6228 * === Converting
6229 *
6230 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6231 * - #-@: Returns the value of +self+, negated.
6232 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6233 * - #abs2: Returns the square of +self+.
6234 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6235 * Math::PI otherwise.
6236 * - #ceil: Returns the smallest number greater than or equal to +self+,
6237 * to a given precision.
6238 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6239 * for the given other value.
6240 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6241 * - #denominator: Returns the denominator (always positive)
6242 * of the Rational representation of +self+.
6243 * - #div: Returns the value of +self+ divided by the given value
6244 * and converted to an integer.
6245 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6246 * from dividing +self+ the given divisor.
6247 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6248 * - #floor: Returns the largest number less than or equal to +self+,
6249 * to a given precision.
6250 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6251 * the given value.
6252 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6253 * - #numerator: Returns the numerator of the Rational representation of +self+;
6254 * has the same sign as +self+.
6255 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6256 * - #quo: Returns the value of +self+ divided by the given value.
6257 * - #real: Returns the real part of +self+.
6258 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6259 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6260 * - #round: Returns the value of +self+ rounded to the nearest value
6261 * for the given a precision.
6262 * - #to_c: Returns the Complex representation of +self+.
6263 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6264 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6265 *
6266 * === Other
6267 *
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.
6271 *
6272 */
6273void
6274Init_Numeric(void)
6275{
6276#ifdef _UNICOSMP
6277 /* Turn off floating point exceptions for divide by zero, etc. */
6278 _set_Creg(0, 0);
6279#endif
6280 id_coerce = rb_intern_const("coerce");
6281 id_to = rb_intern_const("to");
6282 id_by = rb_intern_const("by");
6283
6284 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6286 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6287
6288 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6290 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6291 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6292
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);
6306
6307 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6308 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6309
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);
6317
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);
6323
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);
6341
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);
6353
6354 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6355
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);
6362
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);
6367
6368 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6369 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6370
6371 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6372
6373#define fix_to_s_static(n) do { \
6374 VALUE lit = rb_fstring_literal(#n); \
6375 rb_fix_to_s_static[n] = lit; \
6376 rb_vm_register_global_object(lit); \
6377 RB_GC_GUARD(lit); \
6378 } while (0)
6379
6380 fix_to_s_static(0);
6381 fix_to_s_static(1);
6382 fix_to_s_static(2);
6383 fix_to_s_static(3);
6384 fix_to_s_static(4);
6385 fix_to_s_static(5);
6386 fix_to_s_static(6);
6387 fix_to_s_static(7);
6388 fix_to_s_static(8);
6389 fix_to_s_static(9);
6390
6391#undef fix_to_s_static
6392
6394
6397
6398 /*
6399 * The base of the floating point, or number of unique digits used to
6400 * represent the number.
6401 *
6402 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6403 */
6404 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6405 /*
6406 * The number of base digits for the +double+ data type.
6407 *
6408 * Usually defaults to 53.
6409 */
6410 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6411 /*
6412 * The minimum number of significant decimal digits in a double-precision
6413 * floating point.
6414 *
6415 * Usually defaults to 15.
6416 */
6417 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6418 /*
6419 * The smallest possible exponent value in a double-precision floating
6420 * point.
6421 *
6422 * Usually defaults to -1021.
6423 */
6424 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6425 /*
6426 * The largest possible exponent value in a double-precision floating
6427 * point.
6428 *
6429 * Usually defaults to 1024.
6430 */
6431 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6432 /*
6433 * The smallest negative exponent in a double-precision floating point
6434 * where 10 raised to this power minus 1.
6435 *
6436 * Usually defaults to -307.
6437 */
6438 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6439 /*
6440 * The largest positive exponent in a double-precision floating point where
6441 * 10 raised to this power minus 1.
6442 *
6443 * Usually defaults to 308.
6444 */
6445 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6446 /*
6447 * The smallest positive normalized number in a double-precision floating point.
6448 *
6449 * Usually defaults to 2.2250738585072014e-308.
6450 *
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.
6455 */
6456 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6457 /*
6458 * The largest possible integer in a double-precision floating point number.
6459 *
6460 * Usually defaults to 1.7976931348623157e+308.
6461 */
6462 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6463 /*
6464 * The difference between 1 and the smallest double-precision floating
6465 * point number greater than 1.
6466 *
6467 * Usually defaults to 2.2204460492503131e-16.
6468 */
6469 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6470 /*
6471 * An expression representing positive infinity.
6472 */
6473 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6474 /*
6475 * An expression representing a value which is "not a number".
6476 */
6477 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6478
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);
6501
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);
6508
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);
6514}
6515
6516#undef rb_float_value
6517double
6518rb_float_value(VALUE v)
6519{
6520 return rb_float_value_inline(v);
6521}
6522
6523#undef rb_float_new
6524VALUE
6525rb_float_new(double d)
6526{
6527 return rb_float_new_inline(d);
6528}
6529
6530#include "numeric.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define LONG_LONG
Definition long_long.h:38
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
VALUE rb_float_new_in_heap(double d)
Identical to rb_float_new(), except it does not generate Flonums.
Definition numeric.c:991
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1187
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:980
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2297
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2345
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2166
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:2635
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:936
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:2424
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:135
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:203
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1680
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1440
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2344
VALUE rb_eZeroDivError
ZeroDivisionError exception.
Definition numeric.c:200
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1427
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1434
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
VALUE rb_eFloatDomainError
FloatDomainError exception.
Definition numeric.c:201
VALUE rb_eMathDomainError
Math::DomainError exception.
Definition math.c:30
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3599
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:669
VALUE rb_cInteger
Module class.
Definition numeric.c:198
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:196
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:247
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:680
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:179
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:865
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFloat
Float class.
Definition numeric.c:197
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3192
Encoding relates APIs.
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3803
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1099
#define RGENGC_WB_PROTECTED_FLOAT
This is a compile-time flag to enable/disable write barrier for struct RFloat.
Definition gc.h:534
Defines RBIMPL_HAS_BUILTIN.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:206
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
Definition enumerator.h:193
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:206
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3442
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:3909
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4559
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
Definition numeric.c:1633
VALUE rb_num_coerce_bit(VALUE lhs, VALUE rhs, ID op)
This one is optimised for bitwise operations, but the API is identical to rb_num_coerce_bin().
Definition numeric.c:4987
VALUE rb_num_coerce_relop(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_cmp(), except for return values.
Definition numeric.c:499
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:484
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:477
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1804
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1960
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1498
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1532
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3445
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1567
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2693
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2851
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1284
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:668
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
Definition vm_method.c:1705
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:986
ID rb_to_id(VALUE str)
Definition string.c:12479
int len
Length of the buffer.
Definition io.h:8
unsigned long rb_num2uint(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3356
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3350
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3344
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3362
LONG_LONG rb_num2ll(VALUE num)
Converts an instance of rb_cNumeric into C's long long.
unsigned LONG_LONG rb_num2ull(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long long.
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1354
#define RB_FIX2ULONG
Just another name of rb_fix2ulong.
Definition long.h:54
void rb_out_of_int(SIGNED_VALUE num)
This is an utility function to raise an rb_eRangeError.
Definition numeric.c:3271
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3196
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3265
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:281
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
Definition rbignum.h:74
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:442
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:427
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
Definition numeric.c:3400
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3418
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3409
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3428
#define RTEST
This is an old name of RB_TEST.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376