* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / numeric.c
blob25e169acb7829cfd86fc6bac957610c96af209d3
1 /**********************************************************************
3 numeric.c -
5 $Author$
6 created at: Fri Aug 13 18:33:09 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/ruby.h"
13 #include "ruby/encoding.h"
14 #include <ctype.h>
15 #include <math.h>
16 #include <stdio.h>
18 #if defined(__FreeBSD__) && __FreeBSD__ < 4
19 #include <floatingpoint.h>
20 #endif
22 #ifdef HAVE_FLOAT_H
23 #include <float.h>
24 #endif
26 #ifdef HAVE_IEEEFP_H
27 #include <ieeefp.h>
28 #endif
30 /* use IEEE 64bit values if not defined */
31 #ifndef FLT_RADIX
32 #define FLT_RADIX 2
33 #endif
34 #ifndef FLT_ROUNDS
35 #define FLT_ROUNDS 1
36 #endif
37 #ifndef DBL_MIN
38 #define DBL_MIN 2.2250738585072014e-308
39 #endif
40 #ifndef DBL_MAX
41 #define DBL_MAX 1.7976931348623157e+308
42 #endif
43 #ifndef DBL_MIN_EXP
44 #define DBL_MIN_EXP (-1021)
45 #endif
46 #ifndef DBL_MAX_EXP
47 #define DBL_MAX_EXP 1024
48 #endif
49 #ifndef DBL_MIN_10_EXP
50 #define DBL_MIN_10_EXP (-307)
51 #endif
52 #ifndef DBL_MAX_10_EXP
53 #define DBL_MAX_10_EXP 308
54 #endif
55 #ifndef DBL_DIG
56 #define DBL_DIG 15
57 #endif
58 #ifndef DBL_MANT_DIG
59 #define DBL_MANT_DIG 53
60 #endif
61 #ifndef DBL_EPSILON
62 #define DBL_EPSILON 2.2204460492503131e-16
63 #endif
65 #ifndef HAVE_ROUND
66 double
67 round(double x)
69 double f;
71 if (x > 0.0) {
72 f = floor(x);
73 x = f + (x - f >= 0.5);
75 else if (x < 0.0) {
76 f = ceil(x);
77 x = f - (f - x >= 0.5);
79 return x;
81 #endif
83 static ID id_coerce, id_to_i, id_eq;
85 VALUE rb_cNumeric;
86 VALUE rb_cFloat;
87 VALUE rb_cInteger;
88 VALUE rb_cFixnum;
90 VALUE rb_eZeroDivError;
91 VALUE rb_eFloatDomainError;
93 void
94 rb_num_zerodiv(void)
96 rb_raise(rb_eZeroDivError, "divided by 0");
101 * call-seq:
102 * num.coerce(numeric) => array
104 * If <i>aNumeric</i> is the same type as <i>num</i>, returns an array
105 * containing <i>aNumeric</i> and <i>num</i>. Otherwise, returns an
106 * array with both <i>aNumeric</i> and <i>num</i> represented as
107 * <code>Float</code> objects. This coercion mechanism is used by
108 * Ruby to handle mixed-type numeric operations: it is intended to
109 * find a compatible common type between the two operands of the operator.
111 * 1.coerce(2.5) #=> [2.5, 1.0]
112 * 1.2.coerce(3) #=> [3.0, 1.2]
113 * 1.coerce(2) #=> [2, 1]
116 static VALUE
117 num_coerce(VALUE x, VALUE y)
119 if (CLASS_OF(x) == CLASS_OF(y))
120 return rb_assoc_new(y, x);
121 x = rb_Float(x);
122 y = rb_Float(y);
123 return rb_assoc_new(y, x);
126 static VALUE
127 coerce_body(VALUE *x)
129 return rb_funcall(x[1], id_coerce, 1, x[0]);
132 static VALUE
133 coerce_rescue(VALUE *x)
135 volatile VALUE v = rb_inspect(x[1]);
137 rb_raise(rb_eTypeError, "%s can't be coerced into %s",
138 rb_special_const_p(x[1])?
139 RSTRING_PTR(v):
140 rb_obj_classname(x[1]),
141 rb_obj_classname(x[0]));
142 return Qnil; /* dummy */
145 static int
146 do_coerce(VALUE *x, VALUE *y, int err)
148 VALUE ary;
149 VALUE a[2];
151 a[0] = *x; a[1] = *y;
153 ary = rb_rescue(coerce_body, (VALUE)a, err?coerce_rescue:0, (VALUE)a);
154 if (TYPE(ary) != T_ARRAY || RARRAY_LEN(ary) != 2) {
155 if (err) {
156 rb_raise(rb_eTypeError, "coerce must return [x, y]");
158 return Qfalse;
161 *x = RARRAY_PTR(ary)[0];
162 *y = RARRAY_PTR(ary)[1];
163 return Qtrue;
166 VALUE
167 rb_num_coerce_bin(VALUE x, VALUE y, ID func)
169 do_coerce(&x, &y, Qtrue);
170 return rb_funcall(x, func, 1, y);
173 VALUE
174 rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
176 if (do_coerce(&x, &y, Qfalse))
177 return rb_funcall(x, func, 1, y);
178 return Qnil;
181 VALUE
182 rb_num_coerce_relop(VALUE x, VALUE y, ID func)
184 VALUE c, x0 = x, y0 = y;
186 if (!do_coerce(&x, &y, Qfalse) ||
187 NIL_P(c = rb_funcall(x, func, 1, y))) {
188 rb_cmperr(x0, y0);
189 return Qnil; /* not reached */
191 return c;
195 * Trap attempts to add methods to <code>Numeric</code> objects. Always
196 * raises a <code>TypeError</code>
199 static VALUE
200 num_sadded(VALUE x, VALUE name)
202 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
203 /* Numerics should be values; singleton_methods should not be added to them */
204 rb_raise(rb_eTypeError,
205 "can't define singleton method \"%s\" for %s",
206 rb_id2name(rb_to_id(name)),
207 rb_obj_classname(x));
208 return Qnil; /* not reached */
211 /* :nodoc: */
212 static VALUE
213 num_init_copy(VALUE x, VALUE y)
215 /* Numerics are immutable values, which should not be copied */
216 rb_raise(rb_eTypeError, "can't copy %s", rb_obj_classname(x));
217 return Qnil; /* not reached */
221 * call-seq:
222 * +num => num
224 * Unary Plus---Returns the receiver's value.
227 static VALUE
228 num_uplus(VALUE num)
230 return num;
234 * call-seq:
235 * -num => numeric
237 * Unary Minus---Returns the receiver's value, negated.
240 static VALUE
241 num_uminus(VALUE num)
243 VALUE zero;
245 zero = INT2FIX(0);
246 do_coerce(&zero, &num, Qtrue);
248 return rb_funcall(zero, '-', 1, num);
252 * call-seq:
253 * num.quo(numeric) => result
255 * Returns most exact division (rational for integers, float for floats).
258 static VALUE
259 num_quo(VALUE x, VALUE y)
261 return rb_funcall(rb_rational_raw1(x), '/', 1, y);
266 * call-seq:
267 * num.fdiv(numeric) => float
269 * Returns float division.
272 static VALUE
273 num_fdiv(VALUE x, VALUE y)
275 return rb_funcall(rb_Float(x), '/', 1, y);
279 static VALUE num_floor(VALUE num);
282 * call-seq:
283 * num.div(numeric) => integer
285 * Uses <code>/</code> to perform division, then converts the result to
286 * an integer. <code>Numeric</code> does not define the <code>/</code>
287 * operator; this is left to subclasses.
290 static VALUE
291 num_div(VALUE x, VALUE y)
293 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
294 return num_floor(rb_funcall(x, '/', 1, y));
299 * call-seq:
300 * num.divmod( aNumeric ) -> anArray
302 * Returns an array containing the quotient and modulus obtained by
303 * dividing <i>num</i> by <i>aNumeric</i>. If <code>q, r =
304 * x.divmod(y)</code>, then
306 * q = floor(float(x)/float(y))
307 * x = q*y + r
309 * The quotient is rounded toward -infinity, as shown in the following table:
311 * a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b)
312 * ------+-----+---------------+---------+-------------+---------------
313 * 13 | 4 | 3, 1 | 3 | 1 | 1
314 * ------+-----+---------------+---------+-------------+---------------
315 * 13 | -4 | -4, -3 | -3 | -3 | 1
316 * ------+-----+---------------+---------+-------------+---------------
317 * -13 | 4 | -4, 3 | -4 | 3 | -1
318 * ------+-----+---------------+---------+-------------+---------------
319 * -13 | -4 | 3, -1 | 3 | -1 | -1
320 * ------+-----+---------------+---------+-------------+---------------
321 * 11.5 | 4 | 2, 3.5 | 2.875 | 3.5 | 3.5
322 * ------+-----+---------------+---------+-------------+---------------
323 * 11.5 | -4 | -3, -0.5 | -2.875 | -0.5 | 3.5
324 * ------+-----+---------------+---------+-------------+---------------
325 * -11.5 | 4 | -3, 0.5 | -2.875 | 0.5 | -3.5
326 * ------+-----+---------------+---------+-------------+---------------
327 * -11.5 | -4 | 2, -3.5 | 2.875 | -3.5 | -3.5
330 * Examples
332 * 11.divmod(3) #=> [3, 2]
333 * 11.divmod(-3) #=> [-4, -1]
334 * 11.divmod(3.5) #=> [3, 0.5]
335 * (-11).divmod(3.5) #=> [-4, 3.0]
336 * (11.5).divmod(3.5) #=> [3, 1.0]
339 static VALUE
340 num_divmod(VALUE x, VALUE y)
342 return rb_assoc_new(num_div(x, y), rb_funcall(x, '%', 1, y));
346 * call-seq:
347 * num.modulo(numeric) => result
349 * Equivalent to
350 * <i>num</i>.<code>divmod(</code><i>aNumeric</i><code>)[1]</code>.
353 static VALUE
354 num_modulo(VALUE x, VALUE y)
356 return rb_funcall(x, '%', 1, y);
360 * call-seq:
361 * num.remainder(numeric) => result
363 * If <i>num</i> and <i>numeric</i> have different signs, returns
364 * <em>mod</em>-<i>numeric</i>; otherwise, returns <em>mod</em>. In
365 * both cases <em>mod</em> is the value
366 * <i>num</i>.<code>modulo(</code><i>numeric</i><code>)</code>. The
367 * differences between <code>remainder</code> and modulo
368 * (<code>%</code>) are shown in the table under <code>Numeric#divmod</code>.
371 static VALUE
372 num_remainder(VALUE x, VALUE y)
374 VALUE z = rb_funcall(x, '%', 1, y);
376 if ((!rb_equal(z, INT2FIX(0))) &&
377 ((RTEST(rb_funcall(x, '<', 1, INT2FIX(0))) &&
378 RTEST(rb_funcall(y, '>', 1, INT2FIX(0)))) ||
379 (RTEST(rb_funcall(x, '>', 1, INT2FIX(0))) &&
380 RTEST(rb_funcall(y, '<', 1, INT2FIX(0)))))) {
381 return rb_funcall(z, '-', 1, y);
383 return z;
387 * call-seq:
388 * num.scalar? -> true or false
390 * Returns <code>true</code> if <i>num</i> is an <code>Scalar</code>
391 * (i.e. non <code>Complex</code>).
394 static VALUE
395 num_scalar_p(VALUE num)
397 return Qtrue;
401 * call-seq:
402 * num.integer? -> true or false
404 * Returns <code>true</code> if <i>num</i> is an <code>Integer</code>
405 * (including <code>Fixnum</code> and <code>Bignum</code>).
408 static VALUE
409 num_int_p(VALUE num)
411 return Qfalse;
415 * call-seq:
416 * num.abs => num or numeric
418 * Returns the absolute value of <i>num</i>.
420 * 12.abs #=> 12
421 * (-34.56).abs #=> 34.56
422 * -34.56.abs #=> 34.56
425 static VALUE
426 num_abs(VALUE num)
428 if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) {
429 return rb_funcall(num, rb_intern("-@"), 0);
431 return num;
436 * call-seq:
437 * num.zero? => true or false
439 * Returns <code>true</code> if <i>num</i> has a zero value.
442 static VALUE
443 num_zero_p(VALUE num)
445 if (rb_equal(num, INT2FIX(0))) {
446 return Qtrue;
448 return Qfalse;
453 * call-seq:
454 * num.nonzero? => num or nil
456 * Returns <i>num</i> if <i>num</i> is not zero, <code>nil</code>
457 * otherwise. This behavior is useful when chaining comparisons:
459 * a = %w( z Bb bB bb BB a aA Aa AA A )
460 * b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
461 * b #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
464 static VALUE
465 num_nonzero_p(VALUE num)
467 if (RTEST(rb_funcall(num, rb_intern("zero?"), 0, 0))) {
468 return Qnil;
470 return num;
474 * call-seq:
475 * num.to_int => integer
477 * Invokes the child class's <code>to_i</code> method to convert
478 * <i>num</i> to an integer.
481 static VALUE
482 num_to_int(VALUE num)
484 return rb_funcall(num, id_to_i, 0, 0);
488 /********************************************************************
490 * Document-class: Float
492 * <code>Float</code> objects represent real numbers using the native
493 * architecture's double-precision floating point representation.
496 VALUE
497 rb_float_new(double d)
499 NEWOBJ(flt, struct RFloat);
500 OBJSETUP(flt, rb_cFloat, T_FLOAT);
502 flt->float_value = d;
503 return (VALUE)flt;
507 * call-seq:
508 * flt.to_s => string
510 * Returns a string containing a representation of self. As well as a
511 * fixed or exponential form of the number, the call may return
512 * ``<code>NaN</code>'', ``<code>Infinity</code>'', and
513 * ``<code>-Infinity</code>''.
516 static VALUE
517 flo_to_s(VALUE flt)
519 char buf[32];
520 double value = RFLOAT_VALUE(flt);
521 char *p, *e;
523 if (isinf(value))
524 return rb_usascii_str_new2(value < 0 ? "-Infinity" : "Infinity");
525 else if(isnan(value))
526 return rb_usascii_str_new2("NaN");
528 sprintf(buf, "%#.15g", value); /* ensure to print decimal point */
529 if (!(e = strchr(buf, 'e'))) {
530 e = buf + strlen(buf);
532 if (!ISDIGIT(e[-1])) { /* reformat if ended with decimal point (ex 111111111111111.) */
533 sprintf(buf, "%#.14e", value);
534 if (!(e = strchr(buf, 'e'))) {
535 e = buf + strlen(buf);
538 p = e;
539 while (p[-1]=='0' && ISDIGIT(p[-2]))
540 p--;
541 memmove(p, e, strlen(e)+1);
542 return rb_usascii_str_new2(buf);
546 * MISSING: documentation
549 static VALUE
550 flo_coerce(VALUE x, VALUE y)
552 return rb_assoc_new(rb_Float(y), x);
556 * call-seq:
557 * -float => float
559 * Returns float, negated.
562 static VALUE
563 flo_uminus(VALUE flt)
565 return DOUBLE2NUM(-RFLOAT_VALUE(flt));
569 * call-seq:
570 * float + other => float
572 * Returns a new float which is the sum of <code>float</code>
573 * and <code>other</code>.
576 static VALUE
577 flo_plus(VALUE x, VALUE y)
579 switch (TYPE(y)) {
580 case T_FIXNUM:
581 return DOUBLE2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
582 case T_BIGNUM:
583 return DOUBLE2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
584 case T_FLOAT:
585 return DOUBLE2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
586 default:
587 return rb_num_coerce_bin(x, y, '+');
592 * call-seq:
593 * float + other => float
595 * Returns a new float which is the difference of <code>float</code>
596 * and <code>other</code>.
599 static VALUE
600 flo_minus(VALUE x, VALUE y)
602 switch (TYPE(y)) {
603 case T_FIXNUM:
604 return DOUBLE2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
605 case T_BIGNUM:
606 return DOUBLE2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
607 case T_FLOAT:
608 return DOUBLE2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
609 default:
610 return rb_num_coerce_bin(x, y, '-');
615 * call-seq:
616 * float * other => float
618 * Returns a new float which is the product of <code>float</code>
619 * and <code>other</code>.
622 static VALUE
623 flo_mul(VALUE x, VALUE y)
625 switch (TYPE(y)) {
626 case T_FIXNUM:
627 return DOUBLE2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
628 case T_BIGNUM:
629 return DOUBLE2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
630 case T_FLOAT:
631 return DOUBLE2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
632 default:
633 return rb_num_coerce_bin(x, y, '*');
638 * call-seq:
639 * float / other => float
641 * Returns a new float which is the result of dividing
642 * <code>float</code> by <code>other</code>.
645 static VALUE
646 flo_div(VALUE x, VALUE y)
648 long f_y;
649 double d;
651 switch (TYPE(y)) {
652 case T_FIXNUM:
653 f_y = FIX2LONG(y);
654 return DOUBLE2NUM(RFLOAT_VALUE(x) / (double)f_y);
655 case T_BIGNUM:
656 d = rb_big2dbl(y);
657 return DOUBLE2NUM(RFLOAT_VALUE(x) / d);
658 case T_FLOAT:
659 return DOUBLE2NUM(RFLOAT_VALUE(x) / RFLOAT_VALUE(y));
660 default:
661 return rb_num_coerce_bin(x, y, '/');
665 static VALUE
666 flo_quo(VALUE x, VALUE y)
668 return rb_funcall(x, '/', 1, y);
671 static void
672 flodivmod(double x, double y, double *divp, double *modp)
674 double div, mod;
676 #ifdef HAVE_FMOD
677 mod = fmod(x, y);
678 #else
680 double z;
682 modf(x/y, &z);
683 mod = x - z * y;
685 #endif
686 if (isinf(x) && !isinf(y) && !isnan(y))
687 div = x;
688 else
689 div = (x - mod) / y;
690 if (y*mod < 0) {
691 mod += y;
692 div -= 1.0;
694 if (modp) *modp = mod;
695 if (divp) *divp = div;
700 * call-seq:
701 * flt % other => float
702 * flt.modulo(other) => float
704 * Return the modulo after division of <code>flt</code> by <code>other</code>.
706 * 6543.21.modulo(137) #=> 104.21
707 * 6543.21.modulo(137.24) #=> 92.9299999999996
710 static VALUE
711 flo_mod(VALUE x, VALUE y)
713 double fy, mod;
715 switch (TYPE(y)) {
716 case T_FIXNUM:
717 fy = (double)FIX2LONG(y);
718 break;
719 case T_BIGNUM:
720 fy = rb_big2dbl(y);
721 break;
722 case T_FLOAT:
723 fy = RFLOAT_VALUE(y);
724 break;
725 default:
726 return rb_num_coerce_bin(x, y, '%');
728 flodivmod(RFLOAT_VALUE(x), fy, 0, &mod);
729 return DOUBLE2NUM(mod);
732 static VALUE
733 dbl2ival(double d)
735 if (FIXABLE(d)) {
736 d = round(d);
737 return LONG2FIX((long)d);
739 else if (isnan(d) || isinf(d)) {
740 /* special case: cannot return integer value */
741 return rb_float_new(d);
743 else {
744 return rb_dbl2big(d);
749 * call-seq:
750 * flt.divmod(numeric) => array
752 * See <code>Numeric#divmod</code>.
755 static VALUE
756 flo_divmod(VALUE x, VALUE y)
758 double fy, div, mod;
759 volatile VALUE a, b;
761 switch (TYPE(y)) {
762 case T_FIXNUM:
763 fy = (double)FIX2LONG(y);
764 break;
765 case T_BIGNUM:
766 fy = rb_big2dbl(y);
767 break;
768 case T_FLOAT:
769 fy = RFLOAT_VALUE(y);
770 break;
771 default:
772 return rb_num_coerce_bin(x, y, rb_intern("divmod"));
774 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
775 a = dbl2ival(div);
776 b = DOUBLE2NUM(mod);
777 return rb_assoc_new(a, b);
781 * call-seq:
783 * flt ** other => float
785 * Raises <code>float</code> the <code>other</code> power.
788 static VALUE
789 flo_pow(VALUE x, VALUE y)
791 switch (TYPE(y)) {
792 case T_FIXNUM:
793 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), (double)FIX2LONG(y)));
794 case T_BIGNUM:
795 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), rb_big2dbl(y)));
796 case T_FLOAT:
797 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), RFLOAT_VALUE(y)));
798 default:
799 return rb_num_coerce_bin(x, y, rb_intern("**"));
804 * call-seq:
805 * num.eql?(numeric) => true or false
807 * Returns <code>true</code> if <i>num</i> and <i>numeric</i> are the
808 * same type and have equal values.
810 * 1 == 1.0 #=> true
811 * 1.eql?(1.0) #=> false
812 * (1.0).eql?(1.0) #=> true
815 static VALUE
816 num_eql(VALUE x, VALUE y)
818 if (TYPE(x) != TYPE(y)) return Qfalse;
820 return rb_equal(x, y);
824 * call-seq:
825 * num <=> other -> 0 or nil
827 * Returns zero if <i>num</i> equals <i>other</i>, <code>nil</code>
828 * otherwise.
831 static VALUE
832 num_cmp(VALUE x, VALUE y)
834 if (x == y) return INT2FIX(0);
835 return Qnil;
838 static VALUE
839 num_equal(VALUE x, VALUE y)
841 if (x == y) return Qtrue;
842 return rb_funcall(y, id_eq, 1, x);
846 * call-seq:
847 * flt == obj => true or false
849 * Returns <code>true</code> only if <i>obj</i> has the same value
850 * as <i>flt</i>. Contrast this with <code>Float#eql?</code>, which
851 * requires <i>obj</i> to be a <code>Float</code>.
853 * 1.0 == 1 #=> true
857 static VALUE
858 flo_eq(VALUE x, VALUE y)
860 volatile double a, b;
862 switch (TYPE(y)) {
863 case T_FIXNUM:
864 b = FIX2LONG(y);
865 break;
866 case T_BIGNUM:
867 b = rb_big2dbl(y);
868 break;
869 case T_FLOAT:
870 b = RFLOAT_VALUE(y);
871 if (isnan(b)) return Qfalse;
872 break;
873 default:
874 return num_equal(x, y);
876 a = RFLOAT_VALUE(x);
877 if (isnan(a)) return Qfalse;
878 return (a == b)?Qtrue:Qfalse;
882 * call-seq:
883 * flt.hash => integer
885 * Returns a hash code for this float.
888 static VALUE
889 flo_hash(VALUE num)
891 double d;
892 int hash;
894 d = RFLOAT_VALUE(num);
895 hash = rb_memhash(&d, sizeof(d));
896 return INT2FIX(hash);
899 VALUE
900 rb_dbl_cmp(double a, double b)
902 if (isnan(a) || isnan(b)) return Qnil;
903 if (a == b) return INT2FIX(0);
904 if (a > b) return INT2FIX(1);
905 if (a < b) return INT2FIX(-1);
906 return Qnil;
910 * call-seq:
911 * flt <=> numeric => -1, 0, +1
913 * Returns -1, 0, or +1 depending on whether <i>flt</i> is less than,
914 * equal to, or greater than <i>numeric</i>. This is the basis for the
915 * tests in <code>Comparable</code>.
918 static VALUE
919 flo_cmp(VALUE x, VALUE y)
921 double a, b;
923 a = RFLOAT_VALUE(x);
924 switch (TYPE(y)) {
925 case T_FIXNUM:
926 b = (double)FIX2LONG(y);
927 break;
929 case T_BIGNUM:
930 b = rb_big2dbl(y);
931 break;
933 case T_FLOAT:
934 b = RFLOAT_VALUE(y);
935 break;
937 default:
938 return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
940 return rb_dbl_cmp(a, b);
944 * call-seq:
945 * flt > other => true or false
947 * <code>true</code> if <code>flt</code> is greater than <code>other</code>.
950 static VALUE
951 flo_gt(VALUE x, VALUE y)
953 double a, b;
955 a = RFLOAT_VALUE(x);
956 switch (TYPE(y)) {
957 case T_FIXNUM:
958 b = (double)FIX2LONG(y);
959 break;
961 case T_BIGNUM:
962 b = rb_big2dbl(y);
963 break;
965 case T_FLOAT:
966 b = RFLOAT_VALUE(y);
967 if (isnan(b)) return Qfalse;
968 break;
970 default:
971 return rb_num_coerce_relop(x, y, '>');
973 if (isnan(a)) return Qfalse;
974 return (a > b)?Qtrue:Qfalse;
978 * call-seq:
979 * flt >= other => true or false
981 * <code>true</code> if <code>flt</code> is greater than
982 * or equal to <code>other</code>.
985 static VALUE
986 flo_ge(VALUE x, VALUE y)
988 double a, b;
990 a = RFLOAT_VALUE(x);
991 switch (TYPE(y)) {
992 case T_FIXNUM:
993 b = (double)FIX2LONG(y);
994 break;
996 case T_BIGNUM:
997 b = rb_big2dbl(y);
998 break;
1000 case T_FLOAT:
1001 b = RFLOAT_VALUE(y);
1002 if (isnan(b)) return Qfalse;
1003 break;
1005 default:
1006 return rb_num_coerce_relop(x, y, rb_intern(">="));
1008 if (isnan(a)) return Qfalse;
1009 return (a >= b)?Qtrue:Qfalse;
1013 * call-seq:
1014 * flt < other => true or false
1016 * <code>true</code> if <code>flt</code> is less than <code>other</code>.
1019 static VALUE
1020 flo_lt(VALUE x, VALUE y)
1022 double a, b;
1024 a = RFLOAT_VALUE(x);
1025 switch (TYPE(y)) {
1026 case T_FIXNUM:
1027 b = (double)FIX2LONG(y);
1028 break;
1030 case T_BIGNUM:
1031 b = rb_big2dbl(y);
1032 break;
1034 case T_FLOAT:
1035 b = RFLOAT_VALUE(y);
1036 if (isnan(b)) return Qfalse;
1037 break;
1039 default:
1040 return rb_num_coerce_relop(x, y, '<');
1042 if (isnan(a)) return Qfalse;
1043 return (a < b)?Qtrue:Qfalse;
1047 * call-seq:
1048 * flt <= other => true or false
1050 * <code>true</code> if <code>flt</code> is less than
1051 * or equal to <code>other</code>.
1054 static VALUE
1055 flo_le(VALUE x, VALUE y)
1057 double a, b;
1059 a = RFLOAT_VALUE(x);
1060 switch (TYPE(y)) {
1061 case T_FIXNUM:
1062 b = (double)FIX2LONG(y);
1063 break;
1065 case T_BIGNUM:
1066 b = rb_big2dbl(y);
1067 break;
1069 case T_FLOAT:
1070 b = RFLOAT_VALUE(y);
1071 if (isnan(b)) return Qfalse;
1072 break;
1074 default:
1075 return rb_num_coerce_relop(x, y, rb_intern("<="));
1077 if (isnan(a)) return Qfalse;
1078 return (a <= b)?Qtrue:Qfalse;
1082 * call-seq:
1083 * flt.eql?(obj) => true or false
1085 * Returns <code>true</code> only if <i>obj</i> is a
1086 * <code>Float</code> with the same value as <i>flt</i>. Contrast this
1087 * with <code>Float#==</code>, which performs type conversions.
1089 * 1.0.eql?(1) #=> false
1092 static VALUE
1093 flo_eql(VALUE x, VALUE y)
1095 if (TYPE(y) == T_FLOAT) {
1096 double a = RFLOAT_VALUE(x);
1097 double b = RFLOAT_VALUE(y);
1099 if (isnan(a) || isnan(b)) return Qfalse;
1100 if (a == b) return Qtrue;
1102 return Qfalse;
1106 * call-seq:
1107 * flt.to_f => flt
1109 * As <code>flt</code> is already a float, returns <i>self</i>.
1112 static VALUE
1113 flo_to_f(VALUE num)
1115 return num;
1119 * call-seq:
1120 * flt.abs => float
1122 * Returns the absolute value of <i>flt</i>.
1124 * (-34.56).abs #=> 34.56
1125 * -34.56.abs #=> 34.56
1129 static VALUE
1130 flo_abs(VALUE flt)
1132 double val = fabs(RFLOAT_VALUE(flt));
1133 return DOUBLE2NUM(val);
1137 * call-seq:
1138 * flt.zero? -> true or false
1140 * Returns <code>true</code> if <i>flt</i> is 0.0.
1144 static VALUE
1145 flo_zero_p(VALUE num)
1147 if (RFLOAT_VALUE(num) == 0.0) {
1148 return Qtrue;
1150 return Qfalse;
1154 * call-seq:
1155 * flt.nan? -> true or false
1157 * Returns <code>true</code> if <i>flt</i> is an invalid IEEE floating
1158 * point number.
1160 * a = -1.0 #=> -1.0
1161 * a.nan? #=> false
1162 * a = 0.0/0.0 #=> NaN
1163 * a.nan? #=> true
1166 static VALUE
1167 flo_is_nan_p(VALUE num)
1169 double value = RFLOAT_VALUE(num);
1171 return isnan(value) ? Qtrue : Qfalse;
1175 * call-seq:
1176 * flt.infinite? -> nil, -1, +1
1178 * Returns <code>nil</code>, -1, or +1 depending on whether <i>flt</i>
1179 * is finite, -infinity, or +infinity.
1181 * (0.0).infinite? #=> nil
1182 * (-1.0/0.0).infinite? #=> -1
1183 * (+1.0/0.0).infinite? #=> 1
1186 static VALUE
1187 flo_is_infinite_p(VALUE num)
1189 double value = RFLOAT_VALUE(num);
1191 if (isinf(value)) {
1192 return INT2FIX( value < 0 ? -1 : 1 );
1195 return Qnil;
1199 * call-seq:
1200 * flt.finite? -> true or false
1202 * Returns <code>true</code> if <i>flt</i> is a valid IEEE floating
1203 * point number (it is not infinite, and <code>nan?</code> is
1204 * <code>false</code>).
1208 static VALUE
1209 flo_is_finite_p(VALUE num)
1211 double value = RFLOAT_VALUE(num);
1213 #if HAVE_FINITE
1214 if (!finite(value))
1215 return Qfalse;
1216 #else
1217 if (isinf(value) || isnan(value))
1218 return Qfalse;
1219 #endif
1221 return Qtrue;
1225 * call-seq:
1226 * flt.floor => integer
1228 * Returns the largest integer less than or equal to <i>flt</i>.
1230 * 1.2.floor #=> 1
1231 * 2.0.floor #=> 2
1232 * (-1.2).floor #=> -2
1233 * (-2.0).floor #=> -2
1236 static VALUE
1237 flo_floor(VALUE num)
1239 double f = floor(RFLOAT_VALUE(num));
1240 long val;
1242 if (!FIXABLE(f)) {
1243 return rb_dbl2big(f);
1245 val = f;
1246 return LONG2FIX(val);
1250 * call-seq:
1251 * flt.ceil => integer
1253 * Returns the smallest <code>Integer</code> greater than or equal to
1254 * <i>flt</i>.
1256 * 1.2.ceil #=> 2
1257 * 2.0.ceil #=> 2
1258 * (-1.2).ceil #=> -1
1259 * (-2.0).ceil #=> -2
1262 static VALUE
1263 flo_ceil(VALUE num)
1265 double f = ceil(RFLOAT_VALUE(num));
1266 long val;
1268 if (!FIXABLE(f)) {
1269 return rb_dbl2big(f);
1271 val = f;
1272 return LONG2FIX(val);
1276 * call-seq:
1277 * flt.round([ndigits]) => integer or float
1279 * Rounds <i>flt</i> to a given precision in decimal digits (default 0 digits).
1280 * Precision may be negative. Returns a a floating point number when ndigits
1281 * is more than one.
1283 * 1.5.round #=> 2
1284 * (-1.5).round #=> -2
1287 static VALUE
1288 flo_round(int argc, VALUE *argv, VALUE num)
1290 VALUE nd;
1291 double number, f;
1292 int ndigits = 0, i;
1293 long val;
1295 if (argc > 0 && rb_scan_args(argc, argv, "01", &nd) == 1) {
1296 ndigits = NUM2INT(nd);
1298 number = RFLOAT_VALUE(num);
1299 f = 1.0;
1300 i = abs(ndigits);
1301 while (--i >= 0)
1302 f = f*10.0;
1304 if (isinf(f)) {
1305 if (ndigits < 0) number = 0;
1307 else {
1308 if (ndigits < 0) number /= f;
1309 else number *= f;
1310 number = round(number);
1311 if (ndigits < 0) number *= f;
1312 else number /= f;
1315 if (ndigits > 0) return DOUBLE2NUM(number);
1317 if (!FIXABLE(number)) {
1318 return rb_dbl2big(number);
1320 val = number;
1321 return LONG2FIX(val);
1325 * call-seq:
1326 * flt.to_i => integer
1327 * flt.to_int => integer
1328 * flt.truncate => integer
1330 * Returns <i>flt</i> truncated to an <code>Integer</code>.
1333 static VALUE
1334 flo_truncate(VALUE num)
1336 double f = RFLOAT_VALUE(num);
1337 long val;
1339 if (f > 0.0) f = floor(f);
1340 if (f < 0.0) f = ceil(f);
1342 if (!FIXABLE(f)) {
1343 return rb_dbl2big(f);
1345 val = f;
1346 return LONG2FIX(val);
1351 * call-seq:
1352 * num.floor => integer
1354 * Returns the largest integer less than or equal to <i>num</i>.
1355 * <code>Numeric</code> implements this by converting <i>anInteger</i>
1356 * to a <code>Float</code> and invoking <code>Float#floor</code>.
1358 * 1.floor #=> 1
1359 * (-1).floor #=> -1
1362 static VALUE
1363 num_floor(VALUE num)
1365 return flo_floor(rb_Float(num));
1370 * call-seq:
1371 * num.ceil => integer
1373 * Returns the smallest <code>Integer</code> greater than or equal to
1374 * <i>num</i>. Class <code>Numeric</code> achieves this by converting
1375 * itself to a <code>Float</code> then invoking
1376 * <code>Float#ceil</code>.
1378 * 1.ceil #=> 1
1379 * 1.2.ceil #=> 2
1380 * (-1.2).ceil #=> -1
1381 * (-1.0).ceil #=> -1
1384 static VALUE
1385 num_ceil(VALUE num)
1387 return flo_ceil(rb_Float(num));
1391 * call-seq:
1392 * num.round([ndigits]) => integer or float
1394 * Rounds <i>num</i> to a given precision in decimal digits (default 0 digits).
1395 * Precision may be negative. Returns a a floating point number when ndigits
1396 * is more than one. <code>Numeric</code> implements this by converting itself
1397 * to a <code>Float</code> and invoking <code>Float#round</code>.
1400 static VALUE
1401 num_round(int argc, VALUE* argv, VALUE num)
1403 return flo_round(argc, argv, rb_Float(num));
1407 * call-seq:
1408 * num.truncate => integer
1410 * Returns <i>num</i> truncated to an integer. <code>Numeric</code>
1411 * implements this by converting its value to a float and invoking
1412 * <code>Float#truncate</code>.
1415 static VALUE
1416 num_truncate(VALUE num)
1418 return flo_truncate(rb_Float(num));
1423 * call-seq:
1424 * num.step(limit, step ) {|i| block } => num
1426 * Invokes <em>block</em> with the sequence of numbers starting at
1427 * <i>num</i>, incremented by <i>step</i> on each call. The loop
1428 * finishes when the value to be passed to the block is greater than
1429 * <i>limit</i> (if <i>step</i> is positive) or less than
1430 * <i>limit</i> (if <i>step</i> is negative). If all the arguments are
1431 * integers, the loop operates using an integer counter. If any of the
1432 * arguments are floating point numbers, all are converted to floats,
1433 * and the loop is executed <i>floor(n + n*epsilon)+ 1</i> times,
1434 * where <i>n = (limit - num)/step</i>. Otherwise, the loop
1435 * starts at <i>num</i>, uses either the <code><</code> or
1436 * <code>></code> operator to compare the counter against
1437 * <i>limit</i>, and increments itself using the <code>+</code>
1438 * operator.
1440 * 1.step(10, 2) { |i| print i, " " }
1441 * Math::E.step(Math::PI, 0.2) { |f| print f, " " }
1443 * <em>produces:</em>
1445 * 1 3 5 7 9
1446 * 2.71828182845905 2.91828182845905 3.11828182845905
1449 static VALUE
1450 num_step(int argc, VALUE *argv, VALUE from)
1452 VALUE to, step;
1454 RETURN_ENUMERATOR(from, argc, argv);
1455 if (argc == 1) {
1456 to = argv[0];
1457 step = INT2FIX(1);
1459 else {
1460 if (argc == 2) {
1461 to = argv[0];
1462 step = argv[1];
1464 else {
1465 rb_raise(rb_eArgError, "wrong number of arguments");
1467 if (rb_equal(step, INT2FIX(0))) {
1468 rb_raise(rb_eArgError, "step can't be 0");
1472 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
1473 long i, end, diff;
1475 i = FIX2LONG(from);
1476 end = FIX2LONG(to);
1477 diff = FIX2LONG(step);
1479 if (diff > 0) {
1480 while (i <= end) {
1481 rb_yield(LONG2FIX(i));
1482 i += diff;
1485 else {
1486 while (i >= end) {
1487 rb_yield(LONG2FIX(i));
1488 i += diff;
1492 else if (TYPE(from) == T_FLOAT || TYPE(to) == T_FLOAT || TYPE(step) == T_FLOAT) {
1493 const double epsilon = DBL_EPSILON;
1494 double beg = NUM2DBL(from);
1495 double end = NUM2DBL(to);
1496 double unit = NUM2DBL(step);
1497 double n = (end - beg)/unit;
1498 double err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
1499 long i;
1501 if (err>0.5) err=0.5;
1502 n = floor(n + err) + 1;
1503 for (i=0; i<n; i++) {
1504 rb_yield(DOUBLE2NUM(i*unit+beg));
1507 else {
1508 VALUE i = from;
1509 ID cmp;
1511 if (RTEST(rb_funcall(step, '>', 1, INT2FIX(0)))) {
1512 cmp = '>';
1514 else {
1515 cmp = '<';
1517 for (;;) {
1518 if (RTEST(rb_funcall(i, cmp, 1, to))) break;
1519 rb_yield(i);
1520 i = rb_funcall(i, '+', 1, step);
1523 return from;
1526 SIGNED_VALUE
1527 rb_num2long(VALUE val)
1529 again:
1530 if (NIL_P(val)) {
1531 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
1534 if (FIXNUM_P(val)) return FIX2LONG(val);
1536 switch (TYPE(val)) {
1537 case T_FLOAT:
1538 if (RFLOAT_VALUE(val) <= (double)LONG_MAX
1539 && RFLOAT_VALUE(val) >= (double)LONG_MIN) {
1540 return (SIGNED_VALUE)(RFLOAT_VALUE(val));
1542 else {
1543 char buf[24];
1544 char *s;
1546 sprintf(buf, "%-.10g", RFLOAT_VALUE(val));
1547 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1548 rb_raise(rb_eRangeError, "float %s out of range of integer", buf);
1551 case T_BIGNUM:
1552 return rb_big2long(val);
1554 default:
1555 val = rb_to_int(val);
1556 goto again;
1560 VALUE
1561 rb_num2ulong(VALUE val)
1563 if (TYPE(val) == T_BIGNUM) {
1564 return rb_big2ulong(val);
1566 return (VALUE)rb_num2long(val);
1569 #if SIZEOF_INT < SIZEOF_VALUE
1570 static void
1571 check_int(SIGNED_VALUE num)
1573 const char *s;
1575 if (num < INT_MIN) {
1576 s = "small";
1578 else if (num > INT_MAX) {
1579 s = "big";
1581 else {
1582 return;
1584 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'", num, s);
1587 static void
1588 check_uint(VALUE num, VALUE sign)
1590 static const VALUE mask = ~(VALUE)UINT_MAX;
1592 if (RTEST(sign)) {
1593 /* minus */
1594 if ((num & mask) != mask || (num & ~mask) <= INT_MAX + 1UL)
1595 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too small to convert to `unsigned int'", num);
1597 else {
1598 /* plus */
1599 if ((num & mask) != 0)
1600 rb_raise(rb_eRangeError, "integer %"PRIuVALUE " too big to convert to `unsigned int'", num);
1604 long
1605 rb_num2int(VALUE val)
1607 long num = rb_num2long(val);
1609 check_int(num);
1610 return num;
1613 long
1614 rb_fix2int(VALUE val)
1616 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
1618 check_int(num);
1619 return num;
1622 unsigned long
1623 rb_num2uint(VALUE val)
1625 unsigned long num = rb_num2ulong(val);
1627 check_uint(num, rb_funcall(val, '<', 1, INT2FIX(0)));
1628 return num;
1631 unsigned long
1632 rb_fix2uint(VALUE val)
1634 unsigned long num;
1636 if (!FIXNUM_P(val)) {
1637 return rb_num2uint(val);
1639 num = FIX2ULONG(val);
1641 check_uint(num, rb_funcall(val, '<', 1, INT2FIX(0)));
1642 return num;
1644 #else
1645 long
1646 rb_num2int(VALUE val)
1648 return rb_num2long(val);
1651 long
1652 rb_fix2int(VALUE val)
1654 return FIX2INT(val);
1656 #endif
1658 VALUE
1659 rb_num2fix(VALUE val)
1661 long v;
1663 if (FIXNUM_P(val)) return val;
1665 v = rb_num2long(val);
1666 if (!FIXABLE(v))
1667 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " out of range of fixnum", v);
1668 return LONG2FIX(v);
1671 #if HAVE_LONG_LONG
1673 LONG_LONG
1674 rb_num2ll(VALUE val)
1676 if (NIL_P(val)) {
1677 rb_raise(rb_eTypeError, "no implicit conversion from nil");
1680 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
1682 switch (TYPE(val)) {
1683 case T_FLOAT:
1684 if (RFLOAT_VALUE(val) <= (double)LLONG_MAX
1685 && RFLOAT_VALUE(val) >= (double)LLONG_MIN) {
1686 return (LONG_LONG)(RFLOAT_VALUE(val));
1688 else {
1689 char buf[24];
1690 char *s;
1692 sprintf(buf, "%-.10g", RFLOAT_VALUE(val));
1693 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1694 rb_raise(rb_eRangeError, "float %s out of range of long long", buf);
1697 case T_BIGNUM:
1698 return rb_big2ll(val);
1700 case T_STRING:
1701 rb_raise(rb_eTypeError, "no implicit conversion from string");
1702 return Qnil; /* not reached */
1704 case T_TRUE:
1705 case T_FALSE:
1706 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
1707 return Qnil; /* not reached */
1709 default:
1710 val = rb_to_int(val);
1711 return NUM2LL(val);
1715 unsigned LONG_LONG
1716 rb_num2ull(VALUE val)
1718 if (TYPE(val) == T_BIGNUM) {
1719 return rb_big2ull(val);
1721 return (unsigned LONG_LONG)rb_num2ll(val);
1724 #endif /* HAVE_LONG_LONG */
1726 static VALUE
1727 num_numerator(VALUE num)
1729 return rb_funcall(rb_Rational1(num), rb_intern("numerator"), 0);
1732 static VALUE
1733 num_denominator(VALUE num)
1735 return rb_funcall(rb_Rational1(num), rb_intern("denominator"), 0);
1739 * Document-class: Integer
1741 * <code>Integer</code> is the basis for the two concrete classes that
1742 * hold whole numbers, <code>Bignum</code> and <code>Fixnum</code>.
1748 * call-seq:
1749 * int.to_i => int
1750 * int.to_int => int
1751 * int.floor => int
1752 * int.ceil => int
1753 * int.round => int
1754 * int.truncate => int
1756 * As <i>int</i> is already an <code>Integer</code>, all these
1757 * methods simply return the receiver.
1760 static VALUE
1761 int_to_i(VALUE num)
1763 return num;
1767 * call-seq:
1768 * int.integer? -> true
1770 * Always returns <code>true</code>.
1773 static VALUE
1774 int_int_p(VALUE num)
1776 return Qtrue;
1780 * call-seq:
1781 * int.odd? -> true or false
1783 * Returns <code>true</code> if <i>int</i> is an odd number.
1786 static VALUE
1787 int_odd_p(VALUE num)
1789 if (rb_funcall(num, '%', 1, INT2FIX(2)) != INT2FIX(0)) {
1790 return Qtrue;
1792 return Qfalse;
1796 * call-seq:
1797 * int.even? -> true or false
1799 * Returns <code>true</code> if <i>int</i> is an even number.
1802 static VALUE
1803 int_even_p(VALUE num)
1805 if (rb_funcall(num, '%', 1, INT2FIX(2)) == INT2FIX(0)) {
1806 return Qtrue;
1808 return Qfalse;
1812 * call-seq:
1813 * fixnum.next => integer
1814 * fixnum.succ => integer
1816 * Returns the <code>Integer</code> equal to <i>int</i> + 1.
1818 * 1.next #=> 2
1819 * (-1).next #=> 0
1822 static VALUE
1823 fix_succ(VALUE num)
1825 long i = FIX2LONG(num) + 1;
1826 return LONG2NUM(i);
1830 * call-seq:
1831 * int.next => integer
1832 * int.succ => integer
1834 * Returns the <code>Integer</code> equal to <i>int</i> + 1.
1836 * 1.next #=> 2
1837 * (-1).next #=> 0
1840 static VALUE
1841 int_succ(VALUE num)
1843 if (FIXNUM_P(num)) {
1844 long i = FIX2LONG(num) + 1;
1845 return LONG2NUM(i);
1847 return rb_funcall(num, '+', 1, INT2FIX(1));
1851 * call-seq:
1852 * int.pred => integer
1854 * Returns the <code>Integer</code> equal to <i>int</i> - 1.
1856 * 1.pred #=> 0
1857 * (-1).pred #=> -2
1860 static VALUE
1861 int_pred(VALUE num)
1863 if (FIXNUM_P(num)) {
1864 long i = FIX2LONG(num) - 1;
1865 return LONG2NUM(i);
1867 return rb_funcall(num, '-', 1, INT2FIX(1));
1871 * call-seq:
1872 * int.chr([encoding]) => string
1874 * Returns a string containing the character represented by the
1875 * receiver's value according to +encoding+.
1877 * 65.chr #=> "A"
1878 * 230.chr #=> "\346"
1879 * 255.chr(Encoding::UTF_8) #=> "\303\277"
1882 static VALUE
1883 int_chr(int argc, VALUE *argv, VALUE num)
1885 char c;
1886 int n;
1887 long i = NUM2LONG(num);
1888 rb_encoding *enc;
1889 VALUE str;
1891 switch (argc) {
1892 case 0:
1893 if (i < 0 || 0xff < i) {
1894 out_of_range:
1895 rb_raise(rb_eRangeError, "%"PRIdVALUE " out of char range", i);
1897 c = i;
1898 if (i < 0x80) {
1899 return rb_usascii_str_new(&c, 1);
1901 else {
1902 return rb_str_new(&c, 1);
1904 case 1:
1905 break;
1906 default:
1907 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
1908 break;
1910 enc = rb_to_encoding(argv[0]);
1911 if (!enc) enc = rb_ascii8bit_encoding();
1912 if (i < 0 || (n = rb_enc_codelen(i, enc)) <= 0) goto out_of_range;
1913 str = rb_enc_str_new(0, n, enc);
1914 rb_enc_mbcput(i, RSTRING_PTR(str), enc);
1915 return str;
1918 static VALUE
1919 int_numerator(VALUE num)
1921 return num;
1924 static VALUE
1925 int_denominator(VALUE num)
1927 return INT2FIX(1);
1930 /********************************************************************
1932 * Document-class: Fixnum
1934 * A <code>Fixnum</code> holds <code>Integer</code> values that can be
1935 * represented in a native machine word (minus 1 bit). If any operation
1936 * on a <code>Fixnum</code> exceeds this range, the value is
1937 * automatically converted to a <code>Bignum</code>.
1939 * <code>Fixnum</code> objects have immediate value. This means that
1940 * when they are assigned or passed as parameters, the actual object is
1941 * passed, rather than a reference to that object. Assignment does not
1942 * alias <code>Fixnum</code> objects. There is effectively only one
1943 * <code>Fixnum</code> object instance for any given integer value, so,
1944 * for example, you cannot add a singleton method to a
1945 * <code>Fixnum</code>.
1950 * call-seq:
1951 * Fixnum.induced_from(obj) => fixnum
1953 * Convert <code>obj</code> to a Fixnum. Works with numeric parameters.
1954 * Also works with Symbols, but this is deprecated.
1957 static VALUE
1958 rb_fix_induced_from(VALUE klass, VALUE x)
1960 return rb_num2fix(x);
1964 * call-seq:
1965 * Integer.induced_from(obj) => fixnum, bignum
1967 * Convert <code>obj</code> to an Integer.
1970 static VALUE
1971 rb_int_induced_from(VALUE klass, VALUE x)
1973 switch (TYPE(x)) {
1974 case T_FIXNUM:
1975 case T_BIGNUM:
1976 return x;
1977 case T_FLOAT:
1978 case T_RATIONAL:
1979 return rb_funcall(x, id_to_i, 0);
1980 default:
1981 rb_raise(rb_eTypeError, "failed to convert %s into Integer",
1982 rb_obj_classname(x));
1987 * call-seq:
1988 * Float.induced_from(obj) => float
1990 * Convert <code>obj</code> to a float.
1993 static VALUE
1994 rb_flo_induced_from(VALUE klass, VALUE x)
1996 switch (TYPE(x)) {
1997 case T_FIXNUM:
1998 case T_BIGNUM:
1999 case T_RATIONAL:
2000 return rb_funcall(x, rb_intern("to_f"), 0);
2001 case T_FLOAT:
2002 return x;
2003 default:
2004 rb_raise(rb_eTypeError, "failed to convert %s into Float",
2005 rb_obj_classname(x));
2010 * call-seq:
2011 * -fix => integer
2013 * Negates <code>fix</code> (which might return a Bignum).
2016 static VALUE
2017 fix_uminus(VALUE num)
2019 return LONG2NUM(-FIX2LONG(num));
2022 VALUE
2023 rb_fix2str(VALUE x, int base)
2025 extern const char ruby_digitmap[];
2026 char buf[SIZEOF_VALUE*CHAR_BIT + 2], *b = buf + sizeof buf;
2027 long val = FIX2LONG(x);
2028 int neg = 0;
2030 if (base < 2 || 36 < base) {
2031 rb_raise(rb_eArgError, "invalid radix %d", base);
2033 if (val == 0) {
2034 return rb_usascii_str_new2("0");
2036 if (val < 0) {
2037 val = -val;
2038 neg = 1;
2040 *--b = '\0';
2041 do {
2042 *--b = ruby_digitmap[(int)(val % base)];
2043 } while (val /= base);
2044 if (neg) {
2045 *--b = '-';
2048 return rb_usascii_str_new2(b);
2052 * call-seq:
2053 * fix.to_s( base=10 ) -> aString
2055 * Returns a string containing the representation of <i>fix</i> radix
2056 * <i>base</i> (between 2 and 36).
2058 * 12345.to_s #=> "12345"
2059 * 12345.to_s(2) #=> "11000000111001"
2060 * 12345.to_s(8) #=> "30071"
2061 * 12345.to_s(10) #=> "12345"
2062 * 12345.to_s(16) #=> "3039"
2063 * 12345.to_s(36) #=> "9ix"
2066 static VALUE
2067 fix_to_s(int argc, VALUE *argv, VALUE x)
2069 int base;
2071 if (argc == 0) base = 10;
2072 else {
2073 VALUE b;
2075 rb_scan_args(argc, argv, "01", &b);
2076 base = NUM2INT(b);
2079 return rb_fix2str(x, base);
2083 * call-seq:
2084 * fix + numeric => numeric_result
2086 * Performs addition: the class of the resulting object depends on
2087 * the class of <code>numeric</code> and on the magnitude of the
2088 * result.
2091 static VALUE
2092 fix_plus(VALUE x, VALUE y)
2094 if (FIXNUM_P(y)) {
2095 long a, b, c;
2096 VALUE r;
2098 a = FIX2LONG(x);
2099 b = FIX2LONG(y);
2100 c = a + b;
2101 r = LONG2NUM(c);
2103 return r;
2105 switch (TYPE(y)) {
2106 case T_BIGNUM:
2107 return rb_big_plus(y, x);
2108 case T_FLOAT:
2109 return DOUBLE2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
2110 default:
2111 return rb_num_coerce_bin(x, y, '+');
2116 * call-seq:
2117 * fix - numeric => numeric_result
2119 * Performs subtraction: the class of the resulting object depends on
2120 * the class of <code>numeric</code> and on the magnitude of the
2121 * result.
2124 static VALUE
2125 fix_minus(VALUE x, VALUE y)
2127 if (FIXNUM_P(y)) {
2128 long a, b, c;
2129 VALUE r;
2131 a = FIX2LONG(x);
2132 b = FIX2LONG(y);
2133 c = a - b;
2134 r = LONG2NUM(c);
2136 return r;
2138 switch (TYPE(y)) {
2139 case T_BIGNUM:
2140 x = rb_int2big(FIX2LONG(x));
2141 return rb_big_minus(x, y);
2142 case T_FLOAT:
2143 return DOUBLE2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
2144 default:
2145 return rb_num_coerce_bin(x, y, '-');
2149 #define SQRT_LONG_MAX ((SIGNED_VALUE)1<<((SIZEOF_LONG*CHAR_BIT-1)/2))
2150 /*tests if N*N would overflow*/
2151 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
2154 * call-seq:
2155 * fix * numeric => numeric_result
2157 * Performs multiplication: the class of the resulting object depends on
2158 * the class of <code>numeric</code> and on the magnitude of the
2159 * result.
2162 static VALUE
2163 fix_mul(VALUE x, VALUE y)
2165 if (FIXNUM_P(y)) {
2166 #ifdef __HP_cc
2167 /* avoids an optimization bug of HP aC++/ANSI C B3910B A.06.05 [Jul 25 2005] */
2168 volatile
2169 #endif
2170 SIGNED_VALUE a, b;
2171 #if SIZEOF_VALUE * 2 <= SIZEOF_LONG_LONG
2172 LONG_LONG d;
2173 #else
2174 SIGNED_VALUE c;
2175 VALUE r;
2176 #endif
2178 a = FIX2LONG(x);
2179 b = FIX2LONG(y);
2181 #if SIZEOF_VALUE * 2 <= SIZEOF_LONG_LONG
2182 d = (LONG_LONG)a * b;
2183 if (FIXABLE(d)) return LONG2FIX(d);
2184 return rb_ll2inum(d);
2185 #else
2186 if (FIT_SQRT_LONG(a) && FIT_SQRT_LONG(b))
2187 return LONG2FIX(a*b);
2188 c = a * b;
2189 r = LONG2FIX(c);
2191 if (a == 0) return x;
2192 if (FIX2LONG(r) != c || c/a != b) {
2193 r = rb_big_mul(rb_int2big(a), rb_int2big(b));
2195 return r;
2196 #endif
2198 switch (TYPE(y)) {
2199 case T_BIGNUM:
2200 return rb_big_mul(y, x);
2201 case T_FLOAT:
2202 return DOUBLE2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
2203 default:
2204 return rb_num_coerce_bin(x, y, '*');
2208 static void
2209 fixdivmod(long x, long y, long *divp, long *modp)
2211 long div, mod;
2213 if (y == 0) rb_num_zerodiv();
2214 if (y < 0) {
2215 if (x < 0)
2216 div = -x / -y;
2217 else
2218 div = - (x / -y);
2220 else {
2221 if (x < 0)
2222 div = - (-x / y);
2223 else
2224 div = x / y;
2226 mod = x - div*y;
2227 if ((mod < 0 && y > 0) || (mod > 0 && y < 0)) {
2228 mod += y;
2229 div -= 1;
2231 if (divp) *divp = div;
2232 if (modp) *modp = mod;
2236 * call-seq:
2237 * fix.fdiv(numeric) => float
2239 * Returns the floating point result of dividing <i>fix</i> by
2240 * <i>numeric</i>.
2242 * 654321.fdiv(13731) #=> 47.6528293642124
2243 * 654321.fdiv(13731.24) #=> 47.6519964693647
2247 static VALUE
2248 fix_fdiv(VALUE x, VALUE y)
2250 if (FIXNUM_P(y)) {
2251 return DOUBLE2NUM((double)FIX2LONG(x) / (double)FIX2LONG(y));
2253 switch (TYPE(y)) {
2254 case T_BIGNUM:
2255 return DOUBLE2NUM((double)FIX2LONG(x) / rb_big2dbl(y));
2256 case T_FLOAT:
2257 return DOUBLE2NUM((double)FIX2LONG(x) / RFLOAT_VALUE(y));
2258 default:
2259 return rb_num_coerce_bin(x, y, rb_intern("fdiv"));
2263 static VALUE
2264 fix_divide(VALUE x, VALUE y, ID op)
2266 if (FIXNUM_P(y)) {
2267 long div;
2269 fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
2270 return LONG2NUM(div);
2272 switch (TYPE(y)) {
2273 case T_BIGNUM:
2274 x = rb_int2big(FIX2LONG(x));
2275 return rb_big_div(x, y);
2276 case T_FLOAT:
2278 double div;
2280 if (op == '/') {
2281 div = (double)FIX2LONG(x) / RFLOAT_VALUE(y);
2282 return DOUBLE2NUM(div);
2284 else {
2285 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
2286 div = (double)FIX2LONG(x) / RFLOAT_VALUE(y);
2287 return rb_dbl2big(floor(div));
2290 default:
2291 return rb_num_coerce_bin(x, y, op);
2296 * call-seq:
2297 * fix / numeric => numeric_result
2299 * Performs division: the class of the resulting object depends on
2300 * the class of <code>numeric</code> and on the magnitude of the
2301 * result.
2304 static VALUE
2305 fix_div(VALUE x, VALUE y)
2307 return fix_divide(x, y, '/');
2311 * call-seq:
2312 * fix.div(numeric) => numeric_result
2314 * Performs integer division: returns integer value.
2317 static VALUE
2318 fix_idiv(VALUE x, VALUE y)
2320 return fix_divide(x, y, rb_intern("div"));
2324 * call-seq:
2325 * fix % other => Numeric
2326 * fix.modulo(other) => Numeric
2328 * Returns <code>fix</code> modulo <code>other</code>.
2329 * See <code>Numeric.divmod</code> for more information.
2332 static VALUE
2333 fix_mod(VALUE x, VALUE y)
2335 if (FIXNUM_P(y)) {
2336 long mod;
2338 fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
2339 return LONG2NUM(mod);
2341 switch (TYPE(y)) {
2342 case T_BIGNUM:
2343 x = rb_int2big(FIX2LONG(x));
2344 return rb_big_modulo(x, y);
2345 case T_FLOAT:
2347 double mod;
2349 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), 0, &mod);
2350 return DOUBLE2NUM(mod);
2352 default:
2353 return rb_num_coerce_bin(x, y, '%');
2358 * call-seq:
2359 * fix.divmod(numeric) => array
2361 * See <code>Numeric#divmod</code>.
2363 static VALUE
2364 fix_divmod(VALUE x, VALUE y)
2366 if (FIXNUM_P(y)) {
2367 long div, mod;
2369 fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, &mod);
2371 return rb_assoc_new(LONG2NUM(div), LONG2NUM(mod));
2373 switch (TYPE(y)) {
2374 case T_BIGNUM:
2375 x = rb_int2big(FIX2LONG(x));
2376 return rb_big_divmod(x, y);
2377 case T_FLOAT:
2379 double div, mod;
2380 volatile VALUE a, b;
2382 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
2383 a = dbl2ival(div);
2384 b = DOUBLE2NUM(mod);
2385 return rb_assoc_new(a, b);
2387 default:
2388 return rb_num_coerce_bin(x, y, rb_intern("divmod"));
2392 static VALUE
2393 int_pow(long x, unsigned long y)
2395 int neg = x < 0;
2396 long z = 1;
2398 if (neg) x = -x;
2399 if (y & 1)
2400 z = x;
2401 else
2402 neg = 0;
2403 y &= ~1;
2404 do {
2405 while (y % 2 == 0) {
2406 if (!FIT_SQRT_LONG(x)) {
2407 VALUE v;
2408 bignum:
2409 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
2410 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
2411 return v;
2413 x = x * x;
2414 y >>= 1;
2417 long xz = x * z;
2418 if (!POSFIXABLE(xz) || xz / x != z) {
2419 goto bignum;
2421 z = xz;
2423 } while (--y);
2424 if (neg) z = -z;
2425 return LONG2NUM(z);
2429 * call-seq:
2430 * fix ** other => Numeric
2432 * Raises <code>fix</code> to the <code>other</code> power, which may
2433 * be negative or fractional.
2435 * 2 ** 3 #=> 8
2436 * 2 ** -1 #=> 0.5
2437 * 2 ** 0.5 #=> 1.4142135623731
2440 static VALUE
2441 fix_pow(VALUE x, VALUE y)
2443 static const double zero = 0.0;
2444 long a = FIX2LONG(x);
2446 if (FIXNUM_P(y)) {
2447 long b = FIX2LONG(y);
2449 if (b < 0)
2450 return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2452 if (b == 0) return INT2FIX(1);
2453 if (b == 1) return x;
2454 if (a == 0) {
2455 if (b > 0) return INT2FIX(0);
2456 return DOUBLE2NUM(1.0 / zero);
2458 if (a == 1) return INT2FIX(1);
2459 if (a == -1) {
2460 if (b % 2 == 0)
2461 return INT2FIX(1);
2462 else
2463 return INT2FIX(-1);
2465 return int_pow(a, b);
2467 switch (TYPE(y)) {
2468 case T_BIGNUM:
2470 if (rb_funcall(y, '<', 1, INT2FIX(0)))
2471 return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2473 if (a == 0) return INT2FIX(0);
2474 if (a == 1) return INT2FIX(1);
2475 if (a == -1) {
2476 if (int_even_p(y)) return INT2FIX(1);
2477 else return INT2FIX(-1);
2479 x = rb_int2big(FIX2LONG(x));
2480 return rb_big_pow(x, y);
2481 case T_FLOAT:
2482 if (RFLOAT_VALUE(y) == 0.0) return DOUBLE2NUM(1.0);
2483 if (a == 0) {
2484 return DOUBLE2NUM(RFLOAT_VALUE(y) < 0 ? (1.0 / zero) : 0.0);
2486 if (a == 1) return DOUBLE2NUM(1.0);
2487 return DOUBLE2NUM(pow((double)a, RFLOAT_VALUE(y)));
2488 default:
2489 return rb_num_coerce_bin(x, y, rb_intern("**"));
2494 * call-seq:
2495 * fix == other
2497 * Return <code>true</code> if <code>fix</code> equals <code>other</code>
2498 * numerically.
2500 * 1 == 2 #=> false
2501 * 1 == 1.0 #=> true
2504 static VALUE
2505 fix_equal(VALUE x, VALUE y)
2507 if (x == y) return Qtrue;
2508 if (FIXNUM_P(y)) return Qfalse;
2509 switch (TYPE(y)) {
2510 case T_BIGNUM:
2511 return rb_big_eq(y, x);
2512 case T_FLOAT:
2513 return (double)FIX2LONG(x) == RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2514 default:
2515 return num_equal(x, y);
2520 * call-seq:
2521 * fix <=> numeric => -1, 0, +1
2523 * Comparison---Returns -1, 0, or +1 depending on whether <i>fix</i> is
2524 * less than, equal to, or greater than <i>numeric</i>. This is the
2525 * basis for the tests in <code>Comparable</code>.
2528 static VALUE
2529 fix_cmp(VALUE x, VALUE y)
2531 if (x == y) return INT2FIX(0);
2532 if (FIXNUM_P(y)) {
2533 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
2534 return INT2FIX(-1);
2536 switch (TYPE(y)) {
2537 case T_BIGNUM:
2538 return rb_big_cmp(rb_int2big(FIX2LONG(x)), y);
2539 case T_FLOAT:
2540 return rb_dbl_cmp((double)FIX2LONG(x), RFLOAT_VALUE(y));
2541 default:
2542 return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
2547 * call-seq:
2548 * fix > other => true or false
2550 * Returns <code>true</code> if the value of <code>fix</code> is
2551 * greater than that of <code>other</code>.
2554 static VALUE
2555 fix_gt(VALUE x, VALUE y)
2557 if (FIXNUM_P(y)) {
2558 if (FIX2LONG(x) > FIX2LONG(y)) return Qtrue;
2559 return Qfalse;
2561 switch (TYPE(y)) {
2562 case T_BIGNUM:
2563 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) > 0 ? Qtrue : Qfalse;
2564 case T_FLOAT:
2565 return (double)FIX2LONG(x) > RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2566 default:
2567 return rb_num_coerce_relop(x, y, '>');
2572 * call-seq:
2573 * fix >= other => true or false
2575 * Returns <code>true</code> if the value of <code>fix</code> is
2576 * greater than or equal to that of <code>other</code>.
2579 static VALUE
2580 fix_ge(VALUE x, VALUE y)
2582 if (FIXNUM_P(y)) {
2583 if (FIX2LONG(x) >= FIX2LONG(y)) return Qtrue;
2584 return Qfalse;
2586 switch (TYPE(y)) {
2587 case T_BIGNUM:
2588 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) >= 0 ? Qtrue : Qfalse;
2589 case T_FLOAT:
2590 return (double)FIX2LONG(x) >= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2591 default:
2592 return rb_num_coerce_relop(x, y, rb_intern(">="));
2597 * call-seq:
2598 * fix < other => true or false
2600 * Returns <code>true</code> if the value of <code>fix</code> is
2601 * less than that of <code>other</code>.
2604 static VALUE
2605 fix_lt(VALUE x, VALUE y)
2607 if (FIXNUM_P(y)) {
2608 if (FIX2LONG(x) < FIX2LONG(y)) return Qtrue;
2609 return Qfalse;
2611 switch (TYPE(y)) {
2612 case T_BIGNUM:
2613 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) < 0 ? Qtrue : Qfalse;
2614 case T_FLOAT:
2615 return (double)FIX2LONG(x) < RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2616 default:
2617 return rb_num_coerce_relop(x, y, '<');
2622 * call-seq:
2623 * fix <= other => true or false
2625 * Returns <code>true</code> if the value of <code>fix</code> is
2626 * less than or equal to that of <code>other</code>.
2629 static VALUE
2630 fix_le(VALUE x, VALUE y)
2632 if (FIXNUM_P(y)) {
2633 if (FIX2LONG(x) <= FIX2LONG(y)) return Qtrue;
2634 return Qfalse;
2636 switch (TYPE(y)) {
2637 case T_BIGNUM:
2638 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) <= 0 ? Qtrue : Qfalse;
2639 case T_FLOAT:
2640 return (double)FIX2LONG(x) <= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2641 default:
2642 return rb_num_coerce_relop(x, y, rb_intern("<="));
2647 * call-seq:
2648 * ~fix => integer
2650 * One's complement: returns a number where each bit is flipped.
2653 static VALUE
2654 fix_rev(VALUE num)
2656 long val = FIX2LONG(num);
2658 val = ~val;
2659 return LONG2NUM(val);
2662 static VALUE
2663 bit_coerce(VALUE x)
2665 while (!FIXNUM_P(x) && TYPE(x) != T_BIGNUM) {
2666 if (TYPE(x) == T_FLOAT) {
2667 rb_raise(rb_eTypeError, "can't convert Float into Integer");
2669 x = rb_to_int(x);
2671 return x;
2675 * call-seq:
2676 * fix & other => integer
2678 * Bitwise AND.
2681 static VALUE
2682 fix_and(VALUE x, VALUE y)
2684 long val;
2686 if (!FIXNUM_P(y = bit_coerce(y))) {
2687 return rb_big_and(y, x);
2689 val = FIX2LONG(x) & FIX2LONG(y);
2690 return LONG2NUM(val);
2694 * call-seq:
2695 * fix | other => integer
2697 * Bitwise OR.
2700 static VALUE
2701 fix_or(VALUE x, VALUE y)
2703 long val;
2705 if (!FIXNUM_P(y = bit_coerce(y))) {
2706 return rb_big_or(y, x);
2708 val = FIX2LONG(x) | FIX2LONG(y);
2709 return LONG2NUM(val);
2713 * call-seq:
2714 * fix ^ other => integer
2716 * Bitwise EXCLUSIVE OR.
2719 static VALUE
2720 fix_xor(VALUE x, VALUE y)
2722 long val;
2724 if (!FIXNUM_P(y = bit_coerce(y))) {
2725 return rb_big_xor(y, x);
2727 val = FIX2LONG(x) ^ FIX2LONG(y);
2728 return LONG2NUM(val);
2731 static VALUE fix_lshift(long, unsigned long);
2732 static VALUE fix_rshift(long, unsigned long);
2735 * call-seq:
2736 * fix << count => integer
2738 * Shifts _fix_ left _count_ positions (right if _count_ is negative).
2741 static VALUE
2742 rb_fix_lshift(VALUE x, VALUE y)
2744 long val, width;
2746 val = NUM2LONG(x);
2747 if (!FIXNUM_P(y))
2748 return rb_big_lshift(rb_int2big(val), y);
2749 width = FIX2LONG(y);
2750 if (width < 0)
2751 return fix_rshift(val, (unsigned long)-width);
2752 return fix_lshift(val, width);
2755 static VALUE
2756 fix_lshift(long val, unsigned long width)
2758 if (width > (SIZEOF_LONG*CHAR_BIT-1)
2759 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
2760 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
2762 val = val << width;
2763 return LONG2NUM(val);
2767 * call-seq:
2768 * fix >> count => integer
2770 * Shifts _fix_ right _count_ positions (left if _count_ is negative).
2773 static VALUE
2774 rb_fix_rshift(VALUE x, VALUE y)
2776 long i, val;
2778 val = FIX2LONG(x);
2779 if (!FIXNUM_P(y))
2780 return rb_big_rshift(rb_int2big(val), y);
2781 i = FIX2LONG(y);
2782 if (i == 0) return x;
2783 if (i < 0)
2784 return fix_lshift(val, (unsigned long)-i);
2785 return fix_rshift(val, i);
2788 static VALUE
2789 fix_rshift(long val, unsigned long i)
2791 if (i >= sizeof(long)*CHAR_BIT-1) {
2792 if (val < 0) return INT2FIX(-1);
2793 return INT2FIX(0);
2795 val = RSHIFT(val, i);
2796 return LONG2FIX(val);
2800 * call-seq:
2801 * fix[n] => 0, 1
2803 * Bit Reference---Returns the <em>n</em>th bit in the binary
2804 * representation of <i>fix</i>, where <i>fix</i>[0] is the least
2805 * significant bit.
2807 * a = 0b11001100101010
2808 * 30.downto(0) do |n| print a[n] end
2810 * <em>produces:</em>
2812 * 0000000000000000011001100101010
2815 static VALUE
2816 fix_aref(VALUE fix, VALUE idx)
2818 long val = FIX2LONG(fix);
2819 long i;
2821 idx = rb_to_int(idx);
2822 if (!FIXNUM_P(idx)) {
2823 idx = rb_big_norm(idx);
2824 if (!FIXNUM_P(idx)) {
2825 if (!RBIGNUM_SIGN(idx) || val >= 0)
2826 return INT2FIX(0);
2827 return INT2FIX(1);
2830 i = FIX2LONG(idx);
2832 if (i < 0) return INT2FIX(0);
2833 if (SIZEOF_LONG*CHAR_BIT-1 < i) {
2834 if (val < 0) return INT2FIX(1);
2835 return INT2FIX(0);
2837 if (val & (1L<<i))
2838 return INT2FIX(1);
2839 return INT2FIX(0);
2843 * call-seq:
2844 * fix.to_f -> float
2846 * Converts <i>fix</i> to a <code>Float</code>.
2850 static VALUE
2851 fix_to_f(VALUE num)
2853 double val;
2855 val = (double)FIX2LONG(num);
2857 return DOUBLE2NUM(val);
2861 * call-seq:
2862 * fix.abs -> aFixnum
2864 * Returns the absolute value of <i>fix</i>.
2866 * -12345.abs #=> 12345
2867 * 12345.abs #=> 12345
2871 static VALUE
2872 fix_abs(VALUE fix)
2874 long i = FIX2LONG(fix);
2876 if (i < 0) i = -i;
2878 return LONG2NUM(i);
2884 * call-seq:
2885 * fix.size -> fixnum
2887 * Returns the number of <em>bytes</em> in the machine representation
2888 * of a <code>Fixnum</code>.
2890 * 1.size #=> 4
2891 * -1.size #=> 4
2892 * 2147483647.size #=> 4
2895 static VALUE
2896 fix_size(VALUE fix)
2898 return INT2FIX(sizeof(long));
2902 * call-seq:
2903 * int.upto(limit) {|i| block } => int
2905 * Iterates <em>block</em>, passing in integer values from <i>int</i>
2906 * up to and including <i>limit</i>.
2908 * 5.upto(10) { |i| print i, " " }
2910 * <em>produces:</em>
2912 * 5 6 7 8 9 10
2915 static VALUE
2916 int_upto(VALUE from, VALUE to)
2918 RETURN_ENUMERATOR(from, 1, &to);
2919 if (FIXNUM_P(from) && FIXNUM_P(to)) {
2920 long i, end;
2922 end = FIX2LONG(to);
2923 for (i = FIX2LONG(from); i <= end; i++) {
2924 rb_yield(LONG2FIX(i));
2927 else {
2928 VALUE i = from, c;
2930 while (!(c = rb_funcall(i, '>', 1, to))) {
2931 rb_yield(i);
2932 i = rb_funcall(i, '+', 1, INT2FIX(1));
2934 if (NIL_P(c)) rb_cmperr(i, to);
2936 return from;
2940 * call-seq:
2941 * int.downto(limit) {|i| block } => int
2943 * Iterates <em>block</em>, passing decreasing values from <i>int</i>
2944 * down to and including <i>limit</i>.
2946 * 5.downto(1) { |n| print n, ".. " }
2947 * print " Liftoff!\n"
2949 * <em>produces:</em>
2951 * 5.. 4.. 3.. 2.. 1.. Liftoff!
2954 static VALUE
2955 int_downto(VALUE from, VALUE to)
2957 RETURN_ENUMERATOR(from, 1, &to);
2958 if (FIXNUM_P(from) && FIXNUM_P(to)) {
2959 long i, end;
2961 end = FIX2LONG(to);
2962 for (i=FIX2LONG(from); i >= end; i--) {
2963 rb_yield(LONG2FIX(i));
2966 else {
2967 VALUE i = from, c;
2969 while (!(c = rb_funcall(i, '<', 1, to))) {
2970 rb_yield(i);
2971 i = rb_funcall(i, '-', 1, INT2FIX(1));
2973 if (NIL_P(c)) rb_cmperr(i, to);
2975 return from;
2979 * call-seq:
2980 * int.times {|i| block } => int
2982 * Iterates block <i>int</i> times, passing in values from zero to
2983 * <i>int</i> - 1.
2985 * 5.times do |i|
2986 * print i, " "
2987 * end
2989 * <em>produces:</em>
2991 * 0 1 2 3 4
2994 static VALUE
2995 int_dotimes(VALUE num)
2997 RETURN_ENUMERATOR(num, 0, 0);
2999 if (FIXNUM_P(num)) {
3000 long i, end;
3002 end = FIX2LONG(num);
3003 for (i=0; i<end; i++) {
3004 rb_yield(LONG2FIX(i));
3007 else {
3008 VALUE i = INT2FIX(0);
3010 for (;;) {
3011 if (!RTEST(rb_funcall(i, '<', 1, num))) break;
3012 rb_yield(i);
3013 i = rb_funcall(i, '+', 1, INT2FIX(1));
3016 return num;
3019 static VALUE
3020 int_round(int argc, VALUE* argv, VALUE num)
3022 VALUE n, f, h, r;
3023 int ndigits;
3025 if (argc == 0) return num;
3026 rb_scan_args(argc, argv, "1", &n);
3027 ndigits = NUM2INT(n);
3028 if (ndigits > 0) {
3029 return rb_Float(num);
3031 if (ndigits == 0) {
3032 return num;
3034 ndigits = -ndigits;
3035 if (ndigits < 0) {
3036 rb_raise(rb_eArgError, "ndigits out of range");
3038 f = int_pow(10, ndigits);
3039 if (FIXNUM_P(num) && FIXNUM_P(f)) {
3040 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
3041 int neg = x < 0;
3042 if (neg) x = -x;
3043 x = (x + y / 2) / y * y;
3044 if (neg) x = -x;
3045 return LONG2NUM(x);
3047 h = rb_funcall(f, '/', 1, INT2FIX(2));
3048 r = rb_funcall(num, '%', 1, f);
3049 n = rb_funcall(num, '-', 1, r);
3050 if (!RTEST(rb_funcall(r, '<', 1, h))) {
3051 n = rb_funcall(n, '+', 1, f);
3053 return n;
3057 * call-seq:
3058 * fix.zero? => true or false
3060 * Returns <code>true</code> if <i>fix</i> is zero.
3064 static VALUE
3065 fix_zero_p(VALUE num)
3067 if (FIX2LONG(num) == 0) {
3068 return Qtrue;
3070 return Qfalse;
3074 * call-seq:
3075 * fix.odd? -> true or false
3077 * Returns <code>true</code> if <i>fix</i> is an odd number.
3080 static VALUE
3081 fix_odd_p(VALUE num)
3083 if (num & 2) {
3084 return Qtrue;
3086 return Qfalse;
3090 * call-seq:
3091 * fix.even? -> true or false
3093 * Returns <code>true</code> if <i>fix</i> is an even number.
3096 static VALUE
3097 fix_even_p(VALUE num)
3099 if (num & 2) {
3100 return Qfalse;
3102 return Qtrue;
3105 void
3106 Init_Numeric(void)
3108 #undef rb_intern
3109 #define rb_intern(str) rb_intern_const(str)
3111 #if defined(__FreeBSD__) && __FreeBSD__ < 4
3112 /* allow divide by zero -- Inf */
3113 fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV|FP_X_OFL));
3114 #elif defined(_UNICOSMP)
3115 /* Turn off floating point exceptions for divide by zero, etc. */
3116 _set_Creg(0, 0);
3117 #elif defined(__BORLANDC__)
3118 /* Turn off floating point exceptions for overflow, etc. */
3119 _control87(MCW_EM, MCW_EM);
3120 #endif
3121 id_coerce = rb_intern("coerce");
3122 id_to_i = rb_intern("to_i");
3123 id_eq = rb_intern("==");
3125 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
3126 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
3127 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
3129 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
3130 rb_include_module(rb_cNumeric, rb_mComparable);
3131 rb_define_method(rb_cNumeric, "initialize_copy", num_init_copy, 1);
3132 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
3134 rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
3135 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
3136 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
3137 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
3138 rb_define_method(rb_cNumeric, "quo", num_quo, 1);
3139 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
3140 rb_define_method(rb_cNumeric, "div", num_div, 1);
3141 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
3142 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
3143 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
3144 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
3145 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
3147 rb_define_method(rb_cNumeric, "scalar?", num_scalar_p, 0);
3148 rb_define_method(rb_cNumeric, "integer?", num_int_p, 0);
3149 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
3150 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
3152 rb_define_method(rb_cNumeric, "floor", num_floor, 0);
3153 rb_define_method(rb_cNumeric, "ceil", num_ceil, 0);
3154 rb_define_method(rb_cNumeric, "round", num_round, -1);
3155 rb_define_method(rb_cNumeric, "truncate", num_truncate, 0);
3156 rb_define_method(rb_cNumeric, "step", num_step, -1);
3158 rb_define_method(rb_cNumeric, "numerator", num_numerator, 0);
3159 rb_define_method(rb_cNumeric, "denominator", num_denominator, 0);
3161 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
3162 rb_undef_alloc_func(rb_cInteger);
3163 rb_undef_method(CLASS_OF(rb_cInteger), "new");
3165 rb_define_method(rb_cInteger, "integer?", int_int_p, 0);
3166 rb_define_method(rb_cInteger, "odd?", int_odd_p, 0);
3167 rb_define_method(rb_cInteger, "even?", int_even_p, 0);
3168 rb_define_method(rb_cInteger, "upto", int_upto, 1);
3169 rb_define_method(rb_cInteger, "downto", int_downto, 1);
3170 rb_define_method(rb_cInteger, "times", int_dotimes, 0);
3171 rb_include_module(rb_cInteger, rb_mPrecision);
3172 rb_define_method(rb_cInteger, "succ", int_succ, 0);
3173 rb_define_method(rb_cInteger, "next", int_succ, 0);
3174 rb_define_method(rb_cInteger, "pred", int_pred, 0);
3175 rb_define_method(rb_cInteger, "chr", int_chr, -1);
3176 rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
3177 rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
3178 rb_define_method(rb_cInteger, "floor", int_to_i, 0);
3179 rb_define_method(rb_cInteger, "ceil", int_to_i, 0);
3180 rb_define_method(rb_cInteger, "truncate", int_to_i, 0);
3181 rb_define_method(rb_cInteger, "round", int_round, -1);
3183 rb_cFixnum = rb_define_class("Fixnum", rb_cInteger);
3184 rb_include_module(rb_cFixnum, rb_mPrecision);
3185 rb_define_singleton_method(rb_cFixnum, "induced_from", rb_fix_induced_from, 1);
3186 rb_define_singleton_method(rb_cInteger, "induced_from", rb_int_induced_from, 1);
3188 rb_define_method(rb_cInteger, "numerator", int_numerator, 0);
3189 rb_define_method(rb_cInteger, "denominator", int_denominator, 0);
3191 rb_define_method(rb_cFixnum, "to_s", fix_to_s, -1);
3193 rb_define_method(rb_cFixnum, "-@", fix_uminus, 0);
3194 rb_define_method(rb_cFixnum, "+", fix_plus, 1);
3195 rb_define_method(rb_cFixnum, "-", fix_minus, 1);
3196 rb_define_method(rb_cFixnum, "*", fix_mul, 1);
3197 rb_define_method(rb_cFixnum, "/", fix_div, 1);
3198 rb_define_method(rb_cFixnum, "div", fix_idiv, 1);
3199 rb_define_method(rb_cFixnum, "%", fix_mod, 1);
3200 rb_define_method(rb_cFixnum, "modulo", fix_mod, 1);
3201 rb_define_method(rb_cFixnum, "divmod", fix_divmod, 1);
3202 rb_define_method(rb_cFixnum, "fdiv", fix_fdiv, 1);
3203 rb_define_method(rb_cFixnum, "**", fix_pow, 1);
3205 rb_define_method(rb_cFixnum, "abs", fix_abs, 0);
3207 rb_define_method(rb_cFixnum, "==", fix_equal, 1);
3208 rb_define_method(rb_cFixnum, "<=>", fix_cmp, 1);
3209 rb_define_method(rb_cFixnum, ">", fix_gt, 1);
3210 rb_define_method(rb_cFixnum, ">=", fix_ge, 1);
3211 rb_define_method(rb_cFixnum, "<", fix_lt, 1);
3212 rb_define_method(rb_cFixnum, "<=", fix_le, 1);
3214 rb_define_method(rb_cFixnum, "~", fix_rev, 0);
3215 rb_define_method(rb_cFixnum, "&", fix_and, 1);
3216 rb_define_method(rb_cFixnum, "|", fix_or, 1);
3217 rb_define_method(rb_cFixnum, "^", fix_xor, 1);
3218 rb_define_method(rb_cFixnum, "[]", fix_aref, 1);
3220 rb_define_method(rb_cFixnum, "<<", rb_fix_lshift, 1);
3221 rb_define_method(rb_cFixnum, ">>", rb_fix_rshift, 1);
3223 rb_define_method(rb_cFixnum, "to_f", fix_to_f, 0);
3224 rb_define_method(rb_cFixnum, "size", fix_size, 0);
3225 rb_define_method(rb_cFixnum, "zero?", fix_zero_p, 0);
3226 rb_define_method(rb_cFixnum, "odd?", fix_odd_p, 0);
3227 rb_define_method(rb_cFixnum, "even?", fix_even_p, 0);
3228 rb_define_method(rb_cFixnum, "succ", fix_succ, 0);
3230 rb_cFloat = rb_define_class("Float", rb_cNumeric);
3232 rb_undef_alloc_func(rb_cFloat);
3233 rb_undef_method(CLASS_OF(rb_cFloat), "new");
3235 rb_define_singleton_method(rb_cFloat, "induced_from", rb_flo_induced_from, 1);
3236 rb_include_module(rb_cFloat, rb_mPrecision);
3238 rb_define_const(rb_cFloat, "ROUNDS", INT2FIX(FLT_ROUNDS));
3239 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
3240 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
3241 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
3242 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
3243 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
3244 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
3245 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
3246 rb_define_const(rb_cFloat, "MIN", DOUBLE2NUM(DBL_MIN));
3247 rb_define_const(rb_cFloat, "MAX", DOUBLE2NUM(DBL_MAX));
3248 rb_define_const(rb_cFloat, "EPSILON", DOUBLE2NUM(DBL_EPSILON));
3250 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
3251 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
3252 rb_define_method(rb_cFloat, "-@", flo_uminus, 0);
3253 rb_define_method(rb_cFloat, "+", flo_plus, 1);
3254 rb_define_method(rb_cFloat, "-", flo_minus, 1);
3255 rb_define_method(rb_cFloat, "*", flo_mul, 1);
3256 rb_define_method(rb_cFloat, "/", flo_div, 1);
3257 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
3258 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
3259 rb_define_method(rb_cFloat, "%", flo_mod, 1);
3260 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
3261 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
3262 rb_define_method(rb_cFloat, "**", flo_pow, 1);
3263 rb_define_method(rb_cFloat, "==", flo_eq, 1);
3264 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
3265 rb_define_method(rb_cFloat, ">", flo_gt, 1);
3266 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
3267 rb_define_method(rb_cFloat, "<", flo_lt, 1);
3268 rb_define_method(rb_cFloat, "<=", flo_le, 1);
3269 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
3270 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
3271 rb_define_method(rb_cFloat, "to_f", flo_to_f, 0);
3272 rb_define_method(rb_cFloat, "abs", flo_abs, 0);
3273 rb_define_method(rb_cFloat, "zero?", flo_zero_p, 0);
3275 rb_define_method(rb_cFloat, "to_i", flo_truncate, 0);
3276 rb_define_method(rb_cFloat, "to_int", flo_truncate, 0);
3277 rb_define_method(rb_cFloat, "floor", flo_floor, 0);
3278 rb_define_method(rb_cFloat, "ceil", flo_ceil, 0);
3279 rb_define_method(rb_cFloat, "round", flo_round, -1);
3280 rb_define_method(rb_cFloat, "truncate", flo_truncate, 0);
3282 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
3283 rb_define_method(rb_cFloat, "infinite?", flo_is_infinite_p, 0);
3284 rb_define_method(rb_cFloat, "finite?", flo_is_finite_p, 0);