* string.c (rb_str_each_line): return original string.
[ruby-svn.git] / numeric.c
blob0ae4bb08279dd811716fae2e7f00c414ccf9e193
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 return rb_assoc_new(rb_Float(y), rb_Float(x));
124 static VALUE
125 coerce_body(VALUE *x)
127 return rb_funcall(x[1], id_coerce, 1, x[0]);
130 static VALUE
131 coerce_rescue(VALUE *x)
133 volatile VALUE v = rb_inspect(x[1]);
135 rb_raise(rb_eTypeError, "%s can't be coerced into %s",
136 rb_special_const_p(x[1])?
137 RSTRING_PTR(v):
138 rb_obj_classname(x[1]),
139 rb_obj_classname(x[0]));
140 return Qnil; /* dummy */
143 static int
144 do_coerce(VALUE *x, VALUE *y, int err)
146 VALUE ary;
147 VALUE a[2];
149 a[0] = *x; a[1] = *y;
151 ary = rb_rescue(coerce_body, (VALUE)a, err?coerce_rescue:0, (VALUE)a);
152 if (TYPE(ary) != T_ARRAY || RARRAY_LEN(ary) != 2) {
153 if (err) {
154 rb_raise(rb_eTypeError, "coerce must return [x, y]");
156 return Qfalse;
159 *x = RARRAY_PTR(ary)[0];
160 *y = RARRAY_PTR(ary)[1];
161 return Qtrue;
164 VALUE
165 rb_num_coerce_bin(VALUE x, VALUE y, ID func)
167 do_coerce(&x, &y, Qtrue);
168 return rb_funcall(x, func, 1, y);
171 VALUE
172 rb_num_coerce_cmp(VALUE x, VALUE y, ID func)
174 if (do_coerce(&x, &y, Qfalse))
175 return rb_funcall(x, func, 1, y);
176 return Qnil;
179 VALUE
180 rb_num_coerce_relop(VALUE x, VALUE y, ID func)
182 VALUE c, x0 = x, y0 = y;
184 if (!do_coerce(&x, &y, Qfalse) ||
185 NIL_P(c = rb_funcall(x, func, 1, y))) {
186 rb_cmperr(x0, y0);
187 return Qnil; /* not reached */
189 return c;
193 * Trap attempts to add methods to <code>Numeric</code> objects. Always
194 * raises a <code>TypeError</code>
197 static VALUE
198 num_sadded(VALUE x, VALUE name)
200 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
201 /* Numerics should be values; singleton_methods should not be added to them */
202 rb_raise(rb_eTypeError,
203 "can't define singleton method \"%s\" for %s",
204 rb_id2name(rb_to_id(name)),
205 rb_obj_classname(x));
206 return Qnil; /* not reached */
209 /* :nodoc: */
210 static VALUE
211 num_init_copy(VALUE x, VALUE y)
213 /* Numerics are immutable values, which should not be copied */
214 rb_raise(rb_eTypeError, "can't copy %s", rb_obj_classname(x));
215 return Qnil; /* not reached */
219 * call-seq:
220 * +num => num
222 * Unary Plus---Returns the receiver's value.
225 static VALUE
226 num_uplus(VALUE num)
228 return num;
232 * call-seq:
233 * -num => numeric
235 * Unary Minus---Returns the receiver's value, negated.
238 static VALUE
239 num_uminus(VALUE num)
241 VALUE zero;
243 zero = INT2FIX(0);
244 do_coerce(&zero, &num, Qtrue);
246 return rb_funcall(zero, '-', 1, num);
250 * call-seq:
251 * num.quo(numeric) => result
252 * num.fdiv(numeric) => result
254 * Equivalent to <code>Numeric#/</code>, but overridden in subclasses.
257 static VALUE
258 num_quo(VALUE x, VALUE y)
260 return rb_funcall(x, '/', 1, y);
264 static VALUE num_floor(VALUE num);
267 * call-seq:
268 * num.div(numeric) => integer
270 * Uses <code>/</code> to perform division, then converts the result to
271 * an integer. <code>Numeric</code> does not define the <code>/</code>
272 * operator; this is left to subclasses.
275 static VALUE
276 num_div(VALUE x, VALUE y)
278 return num_floor(rb_funcall(x, '/', 1, y));
283 * call-seq:
284 * num.divmod( aNumeric ) -> anArray
286 * Returns an array containing the quotient and modulus obtained by
287 * dividing <i>num</i> by <i>aNumeric</i>. If <code>q, r =
288 * x.divmod(y)</code>, then
290 * q = floor(float(x)/float(y))
291 * x = q*y + r
293 * The quotient is rounded toward -infinity, as shown in the following table:
295 * a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b)
296 * ------+-----+---------------+---------+-------------+---------------
297 * 13 | 4 | 3, 1 | 3 | 1 | 1
298 * ------+-----+---------------+---------+-------------+---------------
299 * 13 | -4 | -4, -3 | -3 | -3 | 1
300 * ------+-----+---------------+---------+-------------+---------------
301 * -13 | 4 | -4, 3 | -4 | 3 | -1
302 * ------+-----+---------------+---------+-------------+---------------
303 * -13 | -4 | 3, -1 | 3 | -1 | -1
304 * ------+-----+---------------+---------+-------------+---------------
305 * 11.5 | 4 | 2, 3.5 | 2.875 | 3.5 | 3.5
306 * ------+-----+---------------+---------+-------------+---------------
307 * 11.5 | -4 | -3, -0.5 | -2.875 | -0.5 | 3.5
308 * ------+-----+---------------+---------+-------------+---------------
309 * -11.5 | 4 | -3, 0.5 | -2.875 | 0.5 | -3.5
310 * ------+-----+---------------+---------+-------------+---------------
311 * -11.5 | -4 | 2, -3.5 | 2.875 | -3.5 | -3.5
314 * Examples
316 * 11.divmod(3) #=> [3, 2]
317 * 11.divmod(-3) #=> [-4, -1]
318 * 11.divmod(3.5) #=> [3, 0.5]
319 * (-11).divmod(3.5) #=> [-4, 3.0]
320 * (11.5).divmod(3.5) #=> [3, 1.0]
323 static VALUE
324 num_divmod(VALUE x, VALUE y)
326 return rb_assoc_new(num_div(x, y), rb_funcall(x, '%', 1, y));
330 * call-seq:
331 * num.modulo(numeric) => result
333 * Equivalent to
334 * <i>num</i>.<code>divmod(</code><i>aNumeric</i><code>)[1]</code>.
337 static VALUE
338 num_modulo(VALUE x, VALUE y)
340 return rb_funcall(x, '%', 1, y);
344 * call-seq:
345 * num.remainder(numeric) => result
347 * If <i>num</i> and <i>numeric</i> have different signs, returns
348 * <em>mod</em>-<i>numeric</i>; otherwise, returns <em>mod</em>. In
349 * both cases <em>mod</em> is the value
350 * <i>num</i>.<code>modulo(</code><i>numeric</i><code>)</code>. The
351 * differences between <code>remainder</code> and modulo
352 * (<code>%</code>) are shown in the table under <code>Numeric#divmod</code>.
355 static VALUE
356 num_remainder(VALUE x, VALUE y)
358 VALUE z = rb_funcall(x, '%', 1, y);
360 if ((!rb_equal(z, INT2FIX(0))) &&
361 ((RTEST(rb_funcall(x, '<', 1, INT2FIX(0))) &&
362 RTEST(rb_funcall(y, '>', 1, INT2FIX(0)))) ||
363 (RTEST(rb_funcall(x, '>', 1, INT2FIX(0))) &&
364 RTEST(rb_funcall(y, '<', 1, INT2FIX(0)))))) {
365 return rb_funcall(z, '-', 1, y);
367 return z;
371 * call-seq:
372 * num.scalar? -> true or false
374 * Returns <code>true</code> if <i>num</i> is an <code>Scalar</code>
375 * (i.e. non <code>Complex</code>).
378 static VALUE
379 num_scalar_p(VALUE num)
381 return Qtrue;
385 * call-seq:
386 * num.integer? -> true or false
388 * Returns <code>true</code> if <i>num</i> is an <code>Integer</code>
389 * (including <code>Fixnum</code> and <code>Bignum</code>).
392 static VALUE
393 num_int_p(VALUE num)
395 return Qfalse;
399 * call-seq:
400 * num.abs => num or numeric
402 * Returns the absolute value of <i>num</i>.
404 * 12.abs #=> 12
405 * (-34.56).abs #=> 34.56
406 * -34.56.abs #=> 34.56
409 static VALUE
410 num_abs(VALUE num)
412 if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) {
413 return rb_funcall(num, rb_intern("-@"), 0);
415 return num;
420 * call-seq:
421 * num.zero? => true or false
423 * Returns <code>true</code> if <i>num</i> has a zero value.
426 static VALUE
427 num_zero_p(VALUE num)
429 if (rb_equal(num, INT2FIX(0))) {
430 return Qtrue;
432 return Qfalse;
437 * call-seq:
438 * num.nonzero? => num or nil
440 * Returns <i>num</i> if <i>num</i> is not zero, <code>nil</code>
441 * otherwise. This behavior is useful when chaining comparisons:
443 * a = %w( z Bb bB bb BB a aA Aa AA A )
444 * b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
445 * b #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
448 static VALUE
449 num_nonzero_p(VALUE num)
451 if (RTEST(rb_funcall(num, rb_intern("zero?"), 0, 0))) {
452 return Qnil;
454 return num;
458 * call-seq:
459 * num.to_int => integer
461 * Invokes the child class's <code>to_i</code> method to convert
462 * <i>num</i> to an integer.
465 static VALUE
466 num_to_int(VALUE num)
468 return rb_funcall(num, id_to_i, 0, 0);
472 /********************************************************************
474 * Document-class: Float
476 * <code>Float</code> objects represent real numbers using the native
477 * architecture's double-precision floating point representation.
480 VALUE
481 rb_float_new(double d)
483 NEWOBJ(flt, struct RFloat);
484 OBJSETUP(flt, rb_cFloat, T_FLOAT);
486 flt->float_value = d;
487 return (VALUE)flt;
491 * call-seq:
492 * flt.to_s => string
494 * Returns a string containing a representation of self. As well as a
495 * fixed or exponential form of the number, the call may return
496 * ``<code>NaN</code>'', ``<code>Infinity</code>'', and
497 * ``<code>-Infinity</code>''.
500 static VALUE
501 flo_to_s(VALUE flt)
503 char buf[32];
504 double value = RFLOAT_VALUE(flt);
505 char *p, *e;
507 if (isinf(value))
508 return rb_usascii_str_new2(value < 0 ? "-Infinity" : "Infinity");
509 else if(isnan(value))
510 return rb_usascii_str_new2("NaN");
512 sprintf(buf, "%#.15g", value); /* ensure to print decimal point */
513 if (!(e = strchr(buf, 'e'))) {
514 e = buf + strlen(buf);
516 if (!ISDIGIT(e[-1])) { /* reformat if ended with decimal point (ex 111111111111111.) */
517 sprintf(buf, "%#.14e", value);
518 if (!(e = strchr(buf, 'e'))) {
519 e = buf + strlen(buf);
522 p = e;
523 while (p[-1]=='0' && ISDIGIT(p[-2]))
524 p--;
525 memmove(p, e, strlen(e)+1);
526 return rb_usascii_str_new2(buf);
530 * MISSING: documentation
533 static VALUE
534 flo_coerce(VALUE x, VALUE y)
536 return rb_assoc_new(rb_Float(y), x);
540 * call-seq:
541 * -float => float
543 * Returns float, negated.
546 static VALUE
547 flo_uminus(VALUE flt)
549 return DOUBLE2NUM(-RFLOAT_VALUE(flt));
553 * call-seq:
554 * float + other => float
556 * Returns a new float which is the sum of <code>float</code>
557 * and <code>other</code>.
560 static VALUE
561 flo_plus(VALUE x, VALUE y)
563 switch (TYPE(y)) {
564 case T_FIXNUM:
565 return DOUBLE2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
566 case T_BIGNUM:
567 return DOUBLE2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
568 case T_FLOAT:
569 return DOUBLE2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
570 default:
571 return rb_num_coerce_bin(x, y, '+');
576 * call-seq:
577 * float + other => float
579 * Returns a new float which is the difference of <code>float</code>
580 * and <code>other</code>.
583 static VALUE
584 flo_minus(VALUE x, VALUE y)
586 switch (TYPE(y)) {
587 case T_FIXNUM:
588 return DOUBLE2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
589 case T_BIGNUM:
590 return DOUBLE2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
591 case T_FLOAT:
592 return DOUBLE2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
593 default:
594 return rb_num_coerce_bin(x, y, '-');
599 * call-seq:
600 * float * other => float
602 * Returns a new float which is the product of <code>float</code>
603 * and <code>other</code>.
606 static VALUE
607 flo_mul(VALUE x, VALUE y)
609 switch (TYPE(y)) {
610 case T_FIXNUM:
611 return DOUBLE2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
612 case T_BIGNUM:
613 return DOUBLE2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
614 case T_FLOAT:
615 return DOUBLE2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
616 default:
617 return rb_num_coerce_bin(x, y, '*');
622 * call-seq:
623 * float / other => float
625 * Returns a new float which is the result of dividing
626 * <code>float</code> by <code>other</code>.
629 static VALUE
630 flo_div(VALUE x, VALUE y)
632 long f_y;
633 double d;
635 switch (TYPE(y)) {
636 case T_FIXNUM:
637 f_y = FIX2LONG(y);
638 return DOUBLE2NUM(RFLOAT_VALUE(x) / (double)f_y);
639 case T_BIGNUM:
640 d = rb_big2dbl(y);
641 return DOUBLE2NUM(RFLOAT_VALUE(x) / d);
642 case T_FLOAT:
643 return DOUBLE2NUM(RFLOAT_VALUE(x) / RFLOAT_VALUE(y));
644 default:
645 return rb_num_coerce_bin(x, y, '/');
649 static VALUE
650 flo_quo(VALUE x, VALUE y)
652 return rb_funcall(x, '/', 1, y);
655 static void
656 flodivmod(double x, double y, double *divp, double *modp)
658 double div, mod;
660 #ifdef HAVE_FMOD
661 mod = fmod(x, y);
662 #else
664 double z;
666 modf(x/y, &z);
667 mod = x - z * y;
669 #endif
670 if (isinf(x) && !isinf(y) && !isnan(y))
671 div = x;
672 else
673 div = (x - mod) / y;
674 if (y*mod < 0) {
675 mod += y;
676 div -= 1.0;
678 if (modp) *modp = mod;
679 if (divp) *divp = div;
684 * call-seq:
685 * flt % other => float
686 * flt.modulo(other) => float
688 * Return the modulo after division of <code>flt</code> by <code>other</code>.
690 * 6543.21.modulo(137) #=> 104.21
691 * 6543.21.modulo(137.24) #=> 92.9299999999996
694 static VALUE
695 flo_mod(VALUE x, VALUE y)
697 double fy, mod;
699 switch (TYPE(y)) {
700 case T_FIXNUM:
701 fy = (double)FIX2LONG(y);
702 break;
703 case T_BIGNUM:
704 fy = rb_big2dbl(y);
705 break;
706 case T_FLOAT:
707 fy = RFLOAT_VALUE(y);
708 break;
709 default:
710 return rb_num_coerce_bin(x, y, '%');
712 flodivmod(RFLOAT_VALUE(x), fy, 0, &mod);
713 return DOUBLE2NUM(mod);
716 static VALUE
717 dbl2ival(double d)
719 if (FIXABLE(d)) {
720 d = round(d);
721 return LONG2FIX((long)d);
723 else if (isnan(d) || isinf(d)) {
724 /* special case: cannot return integer value */
725 return rb_float_new(d);
727 else {
728 return rb_dbl2big(d);
733 * call-seq:
734 * flt.divmod(numeric) => array
736 * See <code>Numeric#divmod</code>.
739 static VALUE
740 flo_divmod(VALUE x, VALUE y)
742 double fy, div, mod;
743 volatile VALUE a, b;
745 switch (TYPE(y)) {
746 case T_FIXNUM:
747 fy = (double)FIX2LONG(y);
748 break;
749 case T_BIGNUM:
750 fy = rb_big2dbl(y);
751 break;
752 case T_FLOAT:
753 fy = RFLOAT_VALUE(y);
754 break;
755 default:
756 return rb_num_coerce_bin(x, y, rb_intern("divmod"));
758 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
759 a = dbl2ival(div);
760 b = DOUBLE2NUM(mod);
761 return rb_assoc_new(a, b);
765 * call-seq:
767 * flt ** other => float
769 * Raises <code>float</code> the <code>other</code> power.
772 static VALUE
773 flo_pow(VALUE x, VALUE y)
775 switch (TYPE(y)) {
776 case T_FIXNUM:
777 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), (double)FIX2LONG(y)));
778 case T_BIGNUM:
779 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), rb_big2dbl(y)));
780 case T_FLOAT:
781 return DOUBLE2NUM(pow(RFLOAT_VALUE(x), RFLOAT_VALUE(y)));
782 default:
783 return rb_num_coerce_bin(x, y, rb_intern("**"));
788 * call-seq:
789 * num.eql?(numeric) => true or false
791 * Returns <code>true</code> if <i>num</i> and <i>numeric</i> are the
792 * same type and have equal values.
794 * 1 == 1.0 #=> true
795 * 1.eql?(1.0) #=> false
796 * (1.0).eql?(1.0) #=> true
799 static VALUE
800 num_eql(VALUE x, VALUE y)
802 if (TYPE(x) != TYPE(y)) return Qfalse;
804 return rb_equal(x, y);
808 * call-seq:
809 * num <=> other -> 0 or nil
811 * Returns zero if <i>num</i> equals <i>other</i>, <code>nil</code>
812 * otherwise.
815 static VALUE
816 num_cmp(VALUE x, VALUE y)
818 if (x == y) return INT2FIX(0);
819 return Qnil;
822 static VALUE
823 num_equal(VALUE x, VALUE y)
825 if (x == y) return Qtrue;
826 return rb_funcall(y, id_eq, 1, x);
830 * call-seq:
831 * flt == obj => true or false
833 * Returns <code>true</code> only if <i>obj</i> has the same value
834 * as <i>flt</i>. Contrast this with <code>Float#eql?</code>, which
835 * requires <i>obj</i> to be a <code>Float</code>.
837 * 1.0 == 1 #=> true
841 static VALUE
842 flo_eq(VALUE x, VALUE y)
844 volatile double a, b;
846 switch (TYPE(y)) {
847 case T_FIXNUM:
848 b = FIX2LONG(y);
849 break;
850 case T_BIGNUM:
851 b = rb_big2dbl(y);
852 break;
853 case T_FLOAT:
854 b = RFLOAT_VALUE(y);
855 if (isnan(b)) return Qfalse;
856 break;
857 default:
858 return num_equal(x, y);
860 a = RFLOAT_VALUE(x);
861 if (isnan(a)) return Qfalse;
862 return (a == b)?Qtrue:Qfalse;
866 * call-seq:
867 * flt.hash => integer
869 * Returns a hash code for this float.
872 static VALUE
873 flo_hash(VALUE num)
875 double d;
876 int hash;
878 d = RFLOAT_VALUE(num);
879 hash = rb_memhash(&d, sizeof(d));
880 return INT2FIX(hash);
883 VALUE
884 rb_dbl_cmp(double a, double b)
886 if (isnan(a) || isnan(b)) return Qnil;
887 if (a == b) return INT2FIX(0);
888 if (a > b) return INT2FIX(1);
889 if (a < b) return INT2FIX(-1);
890 return Qnil;
894 * call-seq:
895 * flt <=> numeric => -1, 0, +1
897 * Returns -1, 0, or +1 depending on whether <i>flt</i> is less than,
898 * equal to, or greater than <i>numeric</i>. This is the basis for the
899 * tests in <code>Comparable</code>.
902 static VALUE
903 flo_cmp(VALUE x, VALUE y)
905 double a, b;
907 a = RFLOAT_VALUE(x);
908 switch (TYPE(y)) {
909 case T_FIXNUM:
910 b = (double)FIX2LONG(y);
911 break;
913 case T_BIGNUM:
914 b = rb_big2dbl(y);
915 break;
917 case T_FLOAT:
918 b = RFLOAT_VALUE(y);
919 break;
921 default:
922 return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
924 return rb_dbl_cmp(a, b);
928 * call-seq:
929 * flt > other => true or false
931 * <code>true</code> if <code>flt</code> is greater than <code>other</code>.
934 static VALUE
935 flo_gt(VALUE x, VALUE y)
937 double a, b;
939 a = RFLOAT_VALUE(x);
940 switch (TYPE(y)) {
941 case T_FIXNUM:
942 b = (double)FIX2LONG(y);
943 break;
945 case T_BIGNUM:
946 b = rb_big2dbl(y);
947 break;
949 case T_FLOAT:
950 b = RFLOAT_VALUE(y);
951 if (isnan(b)) return Qfalse;
952 break;
954 default:
955 return rb_num_coerce_relop(x, y, '>');
957 if (isnan(a)) return Qfalse;
958 return (a > b)?Qtrue:Qfalse;
962 * call-seq:
963 * flt >= other => true or false
965 * <code>true</code> if <code>flt</code> is greater than
966 * or equal to <code>other</code>.
969 static VALUE
970 flo_ge(VALUE x, VALUE y)
972 double a, b;
974 a = RFLOAT_VALUE(x);
975 switch (TYPE(y)) {
976 case T_FIXNUM:
977 b = (double)FIX2LONG(y);
978 break;
980 case T_BIGNUM:
981 b = rb_big2dbl(y);
982 break;
984 case T_FLOAT:
985 b = RFLOAT_VALUE(y);
986 if (isnan(b)) return Qfalse;
987 break;
989 default:
990 return rb_num_coerce_relop(x, y, rb_intern(">="));
992 if (isnan(a)) return Qfalse;
993 return (a >= b)?Qtrue:Qfalse;
997 * call-seq:
998 * flt < other => true or false
1000 * <code>true</code> if <code>flt</code> is less than <code>other</code>.
1003 static VALUE
1004 flo_lt(VALUE x, VALUE y)
1006 double a, b;
1008 a = RFLOAT_VALUE(x);
1009 switch (TYPE(y)) {
1010 case T_FIXNUM:
1011 b = (double)FIX2LONG(y);
1012 break;
1014 case T_BIGNUM:
1015 b = rb_big2dbl(y);
1016 break;
1018 case T_FLOAT:
1019 b = RFLOAT_VALUE(y);
1020 if (isnan(b)) return Qfalse;
1021 break;
1023 default:
1024 return rb_num_coerce_relop(x, y, '<');
1026 if (isnan(a)) return Qfalse;
1027 return (a < b)?Qtrue:Qfalse;
1031 * call-seq:
1032 * flt <= other => true or false
1034 * <code>true</code> if <code>flt</code> is less than
1035 * or equal to <code>other</code>.
1038 static VALUE
1039 flo_le(VALUE x, VALUE y)
1041 double a, b;
1043 a = RFLOAT_VALUE(x);
1044 switch (TYPE(y)) {
1045 case T_FIXNUM:
1046 b = (double)FIX2LONG(y);
1047 break;
1049 case T_BIGNUM:
1050 b = rb_big2dbl(y);
1051 break;
1053 case T_FLOAT:
1054 b = RFLOAT_VALUE(y);
1055 if (isnan(b)) return Qfalse;
1056 break;
1058 default:
1059 return rb_num_coerce_relop(x, y, rb_intern("<="));
1061 if (isnan(a)) return Qfalse;
1062 return (a <= b)?Qtrue:Qfalse;
1066 * call-seq:
1067 * flt.eql?(obj) => true or false
1069 * Returns <code>true</code> only if <i>obj</i> is a
1070 * <code>Float</code> with the same value as <i>flt</i>. Contrast this
1071 * with <code>Float#==</code>, which performs type conversions.
1073 * 1.0.eql?(1) #=> false
1076 static VALUE
1077 flo_eql(VALUE x, VALUE y)
1079 if (TYPE(y) == T_FLOAT) {
1080 double a = RFLOAT_VALUE(x);
1081 double b = RFLOAT_VALUE(y);
1083 if (isnan(a) || isnan(b)) return Qfalse;
1084 if (a == b) return Qtrue;
1086 return Qfalse;
1090 * call-seq:
1091 * flt.to_f => flt
1093 * As <code>flt</code> is already a float, returns <i>self</i>.
1096 static VALUE
1097 flo_to_f(VALUE num)
1099 return num;
1103 * call-seq:
1104 * flt.abs => float
1106 * Returns the absolute value of <i>flt</i>.
1108 * (-34.56).abs #=> 34.56
1109 * -34.56.abs #=> 34.56
1113 static VALUE
1114 flo_abs(VALUE flt)
1116 double val = fabs(RFLOAT_VALUE(flt));
1117 return DOUBLE2NUM(val);
1121 * call-seq:
1122 * flt.zero? -> true or false
1124 * Returns <code>true</code> if <i>flt</i> is 0.0.
1128 static VALUE
1129 flo_zero_p(VALUE num)
1131 if (RFLOAT_VALUE(num) == 0.0) {
1132 return Qtrue;
1134 return Qfalse;
1138 * call-seq:
1139 * flt.nan? -> true or false
1141 * Returns <code>true</code> if <i>flt</i> is an invalid IEEE floating
1142 * point number.
1144 * a = -1.0 #=> -1.0
1145 * a.nan? #=> false
1146 * a = 0.0/0.0 #=> NaN
1147 * a.nan? #=> true
1150 static VALUE
1151 flo_is_nan_p(VALUE num)
1153 double value = RFLOAT_VALUE(num);
1155 return isnan(value) ? Qtrue : Qfalse;
1159 * call-seq:
1160 * flt.infinite? -> nil, -1, +1
1162 * Returns <code>nil</code>, -1, or +1 depending on whether <i>flt</i>
1163 * is finite, -infinity, or +infinity.
1165 * (0.0).infinite? #=> nil
1166 * (-1.0/0.0).infinite? #=> -1
1167 * (+1.0/0.0).infinite? #=> 1
1170 static VALUE
1171 flo_is_infinite_p(VALUE num)
1173 double value = RFLOAT_VALUE(num);
1175 if (isinf(value)) {
1176 return INT2FIX( value < 0 ? -1 : 1 );
1179 return Qnil;
1183 * call-seq:
1184 * flt.finite? -> true or false
1186 * Returns <code>true</code> if <i>flt</i> is a valid IEEE floating
1187 * point number (it is not infinite, and <code>nan?</code> is
1188 * <code>false</code>).
1192 static VALUE
1193 flo_is_finite_p(VALUE num)
1195 double value = RFLOAT_VALUE(num);
1197 #if HAVE_FINITE
1198 if (!finite(value))
1199 return Qfalse;
1200 #else
1201 if (isinf(value) || isnan(value))
1202 return Qfalse;
1203 #endif
1205 return Qtrue;
1209 * call-seq:
1210 * flt.floor => integer
1212 * Returns the largest integer less than or equal to <i>flt</i>.
1214 * 1.2.floor #=> 1
1215 * 2.0.floor #=> 2
1216 * (-1.2).floor #=> -2
1217 * (-2.0).floor #=> -2
1220 static VALUE
1221 flo_floor(VALUE num)
1223 double f = floor(RFLOAT_VALUE(num));
1224 long val;
1226 if (!FIXABLE(f)) {
1227 return rb_dbl2big(f);
1229 val = f;
1230 return LONG2FIX(val);
1234 * call-seq:
1235 * flt.ceil => integer
1237 * Returns the smallest <code>Integer</code> greater than or equal to
1238 * <i>flt</i>.
1240 * 1.2.ceil #=> 2
1241 * 2.0.ceil #=> 2
1242 * (-1.2).ceil #=> -1
1243 * (-2.0).ceil #=> -2
1246 static VALUE
1247 flo_ceil(VALUE num)
1249 double f = ceil(RFLOAT_VALUE(num));
1250 long val;
1252 if (!FIXABLE(f)) {
1253 return rb_dbl2big(f);
1255 val = f;
1256 return LONG2FIX(val);
1260 * call-seq:
1261 * flt.round([ndigits]) => integer or float
1263 * Rounds <i>flt</i> to a given precision in decimal digits (default 0 digits).
1264 * Precision may be negative. Returns a a floating point number when ndigits
1265 * is more than one.
1267 * 1.5.round #=> 2
1268 * (-1.5).round #=> -2
1271 static VALUE
1272 flo_round(int argc, VALUE *argv, VALUE num)
1274 VALUE nd;
1275 double number, f;
1276 int ndigits = 0, i;
1277 long val;
1279 if (argc > 0 && rb_scan_args(argc, argv, "01", &nd) == 1) {
1280 ndigits = NUM2INT(nd);
1282 number = RFLOAT_VALUE(num);
1283 f = 1.0;
1284 i = abs(ndigits);
1285 while (--i >= 0)
1286 f = f*10.0;
1288 if (ndigits < 0) number /= f;
1289 else number *= f;
1290 number = round(number);
1291 if (ndigits < 0) number *= f;
1292 else number /= f;
1294 if (ndigits > 0) return DOUBLE2NUM(number);
1296 if (!FIXABLE(number)) {
1297 return rb_dbl2big(number);
1299 val = number;
1300 return LONG2FIX(val);
1304 * call-seq:
1305 * flt.to_i => integer
1306 * flt.to_int => integer
1307 * flt.truncate => integer
1309 * Returns <i>flt</i> truncated to an <code>Integer</code>.
1312 static VALUE
1313 flo_truncate(VALUE num)
1315 double f = RFLOAT_VALUE(num);
1316 long val;
1318 if (f > 0.0) f = floor(f);
1319 if (f < 0.0) f = ceil(f);
1321 if (!FIXABLE(f)) {
1322 return rb_dbl2big(f);
1324 val = f;
1325 return LONG2FIX(val);
1330 * call-seq:
1331 * num.floor => integer
1333 * Returns the largest integer less than or equal to <i>num</i>.
1334 * <code>Numeric</code> implements this by converting <i>anInteger</i>
1335 * to a <code>Float</code> and invoking <code>Float#floor</code>.
1337 * 1.floor #=> 1
1338 * (-1).floor #=> -1
1341 static VALUE
1342 num_floor(VALUE num)
1344 return flo_floor(rb_Float(num));
1349 * call-seq:
1350 * num.ceil => integer
1352 * Returns the smallest <code>Integer</code> greater than or equal to
1353 * <i>num</i>. Class <code>Numeric</code> achieves this by converting
1354 * itself to a <code>Float</code> then invoking
1355 * <code>Float#ceil</code>.
1357 * 1.ceil #=> 1
1358 * 1.2.ceil #=> 2
1359 * (-1.2).ceil #=> -1
1360 * (-1.0).ceil #=> -1
1363 static VALUE
1364 num_ceil(VALUE num)
1366 return flo_ceil(rb_Float(num));
1370 * call-seq:
1371 * num.round([ndigits]) => integer or float
1373 * Rounds <i>num</i> to a given precision in decimal digits (default 0 digits).
1374 * Precision may be negative. Returns a a floating point number when ndigits
1375 * is more than one. <code>Numeric</code> implements this by converting itself
1376 * to a <code>Float</code> and invoking <code>Float#round</code>.
1379 static VALUE
1380 num_round(int argc, VALUE* argv, VALUE num)
1382 return flo_round(argc, argv, rb_Float(num));
1386 * call-seq:
1387 * num.truncate => integer
1389 * Returns <i>num</i> truncated to an integer. <code>Numeric</code>
1390 * implements this by converting its value to a float and invoking
1391 * <code>Float#truncate</code>.
1394 static VALUE
1395 num_truncate(VALUE num)
1397 return flo_truncate(rb_Float(num));
1402 * call-seq:
1403 * num.step(limit, step ) {|i| block } => num
1405 * Invokes <em>block</em> with the sequence of numbers starting at
1406 * <i>num</i>, incremented by <i>step</i> on each call. The loop
1407 * finishes when the value to be passed to the block is greater than
1408 * <i>limit</i> (if <i>step</i> is positive) or less than
1409 * <i>limit</i> (if <i>step</i> is negative). If all the arguments are
1410 * integers, the loop operates using an integer counter. If any of the
1411 * arguments are floating point numbers, all are converted to floats,
1412 * and the loop is executed <i>floor(n + n*epsilon)+ 1</i> times,
1413 * where <i>n = (limit - num)/step</i>. Otherwise, the loop
1414 * starts at <i>num</i>, uses either the <code><</code> or
1415 * <code>></code> operator to compare the counter against
1416 * <i>limit</i>, and increments itself using the <code>+</code>
1417 * operator.
1419 * 1.step(10, 2) { |i| print i, " " }
1420 * Math::E.step(Math::PI, 0.2) { |f| print f, " " }
1422 * <em>produces:</em>
1424 * 1 3 5 7 9
1425 * 2.71828182845905 2.91828182845905 3.11828182845905
1428 static VALUE
1429 num_step(int argc, VALUE *argv, VALUE from)
1431 VALUE to, step;
1433 RETURN_ENUMERATOR(from, argc, argv);
1434 if (argc == 1) {
1435 to = argv[0];
1436 step = INT2FIX(1);
1438 else {
1439 if (argc == 2) {
1440 to = argv[0];
1441 step = argv[1];
1443 else {
1444 rb_raise(rb_eArgError, "wrong number of arguments");
1446 if (rb_equal(step, INT2FIX(0))) {
1447 rb_raise(rb_eArgError, "step can't be 0");
1451 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
1452 long i, end, diff;
1454 i = FIX2LONG(from);
1455 end = FIX2LONG(to);
1456 diff = FIX2LONG(step);
1458 if (diff > 0) {
1459 while (i <= end) {
1460 rb_yield(LONG2FIX(i));
1461 i += diff;
1464 else {
1465 while (i >= end) {
1466 rb_yield(LONG2FIX(i));
1467 i += diff;
1471 else if (TYPE(from) == T_FLOAT || TYPE(to) == T_FLOAT || TYPE(step) == T_FLOAT) {
1472 const double epsilon = DBL_EPSILON;
1473 double beg = NUM2DBL(from);
1474 double end = NUM2DBL(to);
1475 double unit = NUM2DBL(step);
1476 double n = (end - beg)/unit;
1477 double err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
1478 long i;
1480 if (err>0.5) err=0.5;
1481 n = floor(n + err) + 1;
1482 for (i=0; i<n; i++) {
1483 rb_yield(DOUBLE2NUM(i*unit+beg));
1486 else {
1487 VALUE i = from;
1488 ID cmp;
1490 if (RTEST(rb_funcall(step, '>', 1, INT2FIX(0)))) {
1491 cmp = '>';
1493 else {
1494 cmp = '<';
1496 for (;;) {
1497 if (RTEST(rb_funcall(i, cmp, 1, to))) break;
1498 rb_yield(i);
1499 i = rb_funcall(i, '+', 1, step);
1502 return from;
1505 SIGNED_VALUE
1506 rb_num2long(VALUE val)
1508 again:
1509 if (NIL_P(val)) {
1510 rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
1513 if (FIXNUM_P(val)) return FIX2LONG(val);
1515 switch (TYPE(val)) {
1516 case T_FLOAT:
1517 if (RFLOAT_VALUE(val) <= (double)LONG_MAX
1518 && RFLOAT_VALUE(val) >= (double)LONG_MIN) {
1519 return (SIGNED_VALUE)(RFLOAT_VALUE(val));
1521 else {
1522 char buf[24];
1523 char *s;
1525 sprintf(buf, "%-.10g", RFLOAT_VALUE(val));
1526 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1527 rb_raise(rb_eRangeError, "float %s out of range of integer", buf);
1530 case T_BIGNUM:
1531 return rb_big2long(val);
1533 default:
1534 val = rb_to_int(val);
1535 goto again;
1539 VALUE
1540 rb_num2ulong(VALUE val)
1542 if (TYPE(val) == T_BIGNUM) {
1543 return rb_big2ulong(val);
1545 return (VALUE)rb_num2long(val);
1548 #if SIZEOF_INT < SIZEOF_VALUE
1549 static void
1550 check_int(SIGNED_VALUE num)
1552 const char *s;
1554 if (num < INT_MIN) {
1555 s = "small";
1557 else if (num > INT_MAX) {
1558 s = "big";
1560 else {
1561 return;
1563 #ifdef LONG_LONG_VALUE
1564 rb_raise(rb_eRangeError, "integer %lld too %s to convert to `int'", num, s);
1565 #else
1566 rb_raise(rb_eRangeError, "integer %ld too %s to convert to `int'", num, s);
1567 #endif
1570 static void
1571 check_uint(VALUE num)
1573 if (num > UINT_MAX) {
1574 #ifdef LONG_LONG_VALUE
1575 rb_raise(rb_eRangeError, "integer %llu too big to convert to `unsigned int'", num);
1576 #else
1577 rb_raise(rb_eRangeError, "integer %lu too big to convert to `unsigned int'", num);
1578 #endif
1582 long
1583 rb_num2int(VALUE val)
1585 long num = rb_num2long(val);
1587 check_int(num);
1588 return num;
1591 long
1592 rb_fix2int(VALUE val)
1594 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
1596 check_int(num);
1597 return num;
1600 unsigned long
1601 rb_num2uint(VALUE val)
1603 unsigned long num = rb_num2ulong(val);
1605 if (RTEST(rb_funcall(INT2FIX(0), '<', 1, val))) {
1606 check_uint(num);
1608 return num;
1611 unsigned long
1612 rb_fix2uint(VALUE val)
1614 unsigned long num;
1616 if (!FIXNUM_P(val)) {
1617 return rb_num2uint(val);
1619 num = FIX2ULONG(val);
1620 if (FIX2LONG(val) > 0) {
1621 check_uint(num);
1623 return num;
1625 #else
1626 long
1627 rb_num2int(VALUE val)
1629 return rb_num2long(val);
1632 long
1633 rb_fix2int(VALUE val)
1635 return FIX2INT(val);
1637 #endif
1639 VALUE
1640 rb_num2fix(VALUE val)
1642 long v;
1644 if (FIXNUM_P(val)) return val;
1646 v = rb_num2long(val);
1647 if (!FIXABLE(v))
1648 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
1649 return LONG2FIX(v);
1652 #if HAVE_LONG_LONG
1654 LONG_LONG
1655 rb_num2ll(VALUE val)
1657 if (NIL_P(val)) {
1658 rb_raise(rb_eTypeError, "no implicit conversion from nil");
1661 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
1663 switch (TYPE(val)) {
1664 case T_FLOAT:
1665 if (RFLOAT_VALUE(val) <= (double)LLONG_MAX
1666 && RFLOAT_VALUE(val) >= (double)LLONG_MIN) {
1667 return (LONG_LONG)(RFLOAT_VALUE(val));
1669 else {
1670 char buf[24];
1671 char *s;
1673 sprintf(buf, "%-.10g", RFLOAT_VALUE(val));
1674 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1675 rb_raise(rb_eRangeError, "float %s out of range of long long", buf);
1678 case T_BIGNUM:
1679 return rb_big2ll(val);
1681 case T_STRING:
1682 rb_raise(rb_eTypeError, "no implicit conversion from string");
1683 return Qnil; /* not reached */
1685 case T_TRUE:
1686 case T_FALSE:
1687 rb_raise(rb_eTypeError, "no implicit conversion from boolean");
1688 return Qnil; /* not reached */
1690 default:
1691 val = rb_to_int(val);
1692 return NUM2LL(val);
1696 unsigned LONG_LONG
1697 rb_num2ull(VALUE val)
1699 if (TYPE(val) == T_BIGNUM) {
1700 return rb_big2ull(val);
1702 return (unsigned LONG_LONG)rb_num2ll(val);
1705 #endif /* HAVE_LONG_LONG */
1707 static VALUE
1708 num_numerator(VALUE num)
1710 return rb_funcall(rb_Rational1(num), rb_intern("numerator"), 0);
1713 static VALUE
1714 num_denominator(VALUE num)
1716 return rb_funcall(rb_Rational1(num), rb_intern("denominator"), 0);
1720 * Document-class: Integer
1722 * <code>Integer</code> is the basis for the two concrete classes that
1723 * hold whole numbers, <code>Bignum</code> and <code>Fixnum</code>.
1729 * call-seq:
1730 * int.to_i => int
1731 * int.to_int => int
1732 * int.floor => int
1733 * int.ceil => int
1734 * int.round => int
1735 * int.truncate => int
1737 * As <i>int</i> is already an <code>Integer</code>, all these
1738 * methods simply return the receiver.
1741 static VALUE
1742 int_to_i(VALUE num)
1744 return num;
1748 * call-seq:
1749 * int.integer? -> true
1751 * Always returns <code>true</code>.
1754 static VALUE
1755 int_int_p(VALUE num)
1757 return Qtrue;
1761 * call-seq:
1762 * int.odd? -> true or false
1764 * Returns <code>true</code> if <i>int</i> is an odd number.
1767 static VALUE
1768 int_odd_p(VALUE num)
1770 if (rb_funcall(num, '%', 1, INT2FIX(2)) != INT2FIX(0)) {
1771 return Qtrue;
1773 return Qfalse;
1777 * call-seq:
1778 * int.even? -> true or false
1780 * Returns <code>true</code> if <i>int</i> is an even number.
1783 static VALUE
1784 int_even_p(VALUE num)
1786 if (rb_funcall(num, '%', 1, INT2FIX(2)) == INT2FIX(0)) {
1787 return Qtrue;
1789 return Qfalse;
1793 * call-seq:
1794 * fixnum.next => integer
1795 * fixnum.succ => integer
1797 * Returns the <code>Integer</code> equal to <i>int</i> + 1.
1799 * 1.next #=> 2
1800 * (-1).next #=> 0
1803 static VALUE
1804 fix_succ(VALUE num)
1806 long i = FIX2LONG(num) + 1;
1807 return LONG2NUM(i);
1811 * call-seq:
1812 * int.next => integer
1813 * int.succ => integer
1815 * Returns the <code>Integer</code> equal to <i>int</i> + 1.
1817 * 1.next #=> 2
1818 * (-1).next #=> 0
1821 static VALUE
1822 int_succ(VALUE num)
1824 if (FIXNUM_P(num)) {
1825 long i = FIX2LONG(num) + 1;
1826 return LONG2NUM(i);
1828 return rb_funcall(num, '+', 1, INT2FIX(1));
1832 * call-seq:
1833 * int.pred => integer
1835 * Returns the <code>Integer</code> equal to <i>int</i> - 1.
1837 * 1.pred #=> 0
1838 * (-1).pred #=> -2
1841 static VALUE
1842 int_pred(VALUE num)
1844 if (FIXNUM_P(num)) {
1845 long i = FIX2LONG(num) - 1;
1846 return LONG2NUM(i);
1848 return rb_funcall(num, '-', 1, INT2FIX(1));
1852 * call-seq:
1853 * int.chr([encoding]) => string
1855 * Returns a string containing the character represented by the
1856 * receiver's value according to +encoding+.
1858 * 65.chr #=> "A"
1859 * 230.chr #=> "\346"
1860 * 255.chr(Encoding::UTF_8) #=> "\303\277"
1863 static VALUE
1864 int_chr(int argc, VALUE *argv, VALUE num)
1866 char c;
1867 int n;
1868 long i = NUM2LONG(num);
1869 rb_encoding *enc;
1870 VALUE str;
1872 switch (argc) {
1873 case 0:
1874 if (i < 0 || 0xff < i) {
1875 out_of_range:
1876 rb_raise(rb_eRangeError, "%ld out of char range", i);
1878 c = i;
1879 if (i < 0x80) {
1880 return rb_usascii_str_new(&c, 1);
1882 else {
1883 return rb_str_new(&c, 1);
1885 case 1:
1886 break;
1887 default:
1888 rb_raise(rb_eArgError, "wrong number of arguments (%d for 0 or 1)", argc);
1889 break;
1891 enc = rb_to_encoding(argv[0]);
1892 if (!enc) enc = rb_ascii8bit_encoding();
1893 if (i < 0 || (n = rb_enc_codelen(i, enc)) <= 0) goto out_of_range;
1894 str = rb_enc_str_new(0, n, enc);
1895 rb_enc_mbcput(i, RSTRING_PTR(str), enc);
1896 return str;
1899 static VALUE
1900 int_numerator(VALUE num)
1902 return num;
1905 static VALUE
1906 int_denominator(VALUE num)
1908 return INT2FIX(1);
1911 /********************************************************************
1913 * Document-class: Fixnum
1915 * A <code>Fixnum</code> holds <code>Integer</code> values that can be
1916 * represented in a native machine word (minus 1 bit). If any operation
1917 * on a <code>Fixnum</code> exceeds this range, the value is
1918 * automatically converted to a <code>Bignum</code>.
1920 * <code>Fixnum</code> objects have immediate value. This means that
1921 * when they are assigned or passed as parameters, the actual object is
1922 * passed, rather than a reference to that object. Assignment does not
1923 * alias <code>Fixnum</code> objects. There is effectively only one
1924 * <code>Fixnum</code> object instance for any given integer value, so,
1925 * for example, you cannot add a singleton method to a
1926 * <code>Fixnum</code>.
1931 * call-seq:
1932 * Fixnum.induced_from(obj) => fixnum
1934 * Convert <code>obj</code> to a Fixnum. Works with numeric parameters.
1935 * Also works with Symbols, but this is deprecated.
1938 static VALUE
1939 rb_fix_induced_from(VALUE klass, VALUE x)
1941 return rb_num2fix(x);
1945 * call-seq:
1946 * Integer.induced_from(obj) => fixnum, bignum
1948 * Convert <code>obj</code> to an Integer.
1951 static VALUE
1952 rb_int_induced_from(VALUE klass, VALUE x)
1954 switch (TYPE(x)) {
1955 case T_FIXNUM:
1956 case T_BIGNUM:
1957 return x;
1958 case T_FLOAT:
1959 case T_RATIONAL:
1960 return rb_funcall(x, id_to_i, 0);
1961 default:
1962 rb_raise(rb_eTypeError, "failed to convert %s into Integer",
1963 rb_obj_classname(x));
1968 * call-seq:
1969 * Float.induced_from(obj) => float
1971 * Convert <code>obj</code> to a float.
1974 static VALUE
1975 rb_flo_induced_from(VALUE klass, VALUE x)
1977 switch (TYPE(x)) {
1978 case T_FIXNUM:
1979 case T_BIGNUM:
1980 case T_RATIONAL:
1981 return rb_funcall(x, rb_intern("to_f"), 0);
1982 case T_FLOAT:
1983 return x;
1984 default:
1985 rb_raise(rb_eTypeError, "failed to convert %s into Float",
1986 rb_obj_classname(x));
1991 * call-seq:
1992 * -fix => integer
1994 * Negates <code>fix</code> (which might return a Bignum).
1997 static VALUE
1998 fix_uminus(VALUE num)
2000 return LONG2NUM(-FIX2LONG(num));
2003 VALUE
2004 rb_fix2str(VALUE x, int base)
2006 extern const char ruby_digitmap[];
2007 char buf[SIZEOF_VALUE*CHAR_BIT + 2], *b = buf + sizeof buf;
2008 long val = FIX2LONG(x);
2009 int neg = 0;
2011 if (base < 2 || 36 < base) {
2012 rb_raise(rb_eArgError, "invalid radix %d", base);
2014 if (val == 0) {
2015 return rb_usascii_str_new2("0");
2017 if (val < 0) {
2018 val = -val;
2019 neg = 1;
2021 *--b = '\0';
2022 do {
2023 *--b = ruby_digitmap[(int)(val % base)];
2024 } while (val /= base);
2025 if (neg) {
2026 *--b = '-';
2029 return rb_usascii_str_new2(b);
2033 * call-seq:
2034 * fix.to_s( base=10 ) -> aString
2036 * Returns a string containing the representation of <i>fix</i> radix
2037 * <i>base</i> (between 2 and 36).
2039 * 12345.to_s #=> "12345"
2040 * 12345.to_s(2) #=> "11000000111001"
2041 * 12345.to_s(8) #=> "30071"
2042 * 12345.to_s(10) #=> "12345"
2043 * 12345.to_s(16) #=> "3039"
2044 * 12345.to_s(36) #=> "9ix"
2047 static VALUE
2048 fix_to_s(int argc, VALUE *argv, VALUE x)
2050 int base;
2052 if (argc == 0) base = 10;
2053 else {
2054 VALUE b;
2056 rb_scan_args(argc, argv, "01", &b);
2057 base = NUM2INT(b);
2060 return rb_fix2str(x, base);
2064 * call-seq:
2065 * fix + numeric => numeric_result
2067 * Performs addition: the class of the resulting object depends on
2068 * the class of <code>numeric</code> and on the magnitude of the
2069 * result.
2072 static VALUE
2073 fix_plus(VALUE x, VALUE y)
2075 if (FIXNUM_P(y)) {
2076 long a, b, c;
2077 VALUE r;
2079 a = FIX2LONG(x);
2080 b = FIX2LONG(y);
2081 c = a + b;
2082 r = LONG2NUM(c);
2084 return r;
2086 switch (TYPE(y)) {
2087 case T_BIGNUM:
2088 return rb_big_plus(y, x);
2089 case T_FLOAT:
2090 return DOUBLE2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
2091 default:
2092 return rb_num_coerce_bin(x, y, '+');
2097 * call-seq:
2098 * fix - numeric => numeric_result
2100 * Performs subtraction: the class of the resulting object depends on
2101 * the class of <code>numeric</code> and on the magnitude of the
2102 * result.
2105 static VALUE
2106 fix_minus(VALUE x, VALUE y)
2108 if (FIXNUM_P(y)) {
2109 long a, b, c;
2110 VALUE r;
2112 a = FIX2LONG(x);
2113 b = FIX2LONG(y);
2114 c = a - b;
2115 r = LONG2NUM(c);
2117 return r;
2119 switch (TYPE(y)) {
2120 case T_BIGNUM:
2121 x = rb_int2big(FIX2LONG(x));
2122 return rb_big_minus(x, y);
2123 case T_FLOAT:
2124 return DOUBLE2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
2125 default:
2126 return rb_num_coerce_bin(x, y, '-');
2130 #define SQRT_LONG_MAX ((SIGNED_VALUE)1<<((SIZEOF_LONG*CHAR_BIT-1)/2))
2131 /*tests if N*N would overflow*/
2132 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
2135 * call-seq:
2136 * fix * numeric => numeric_result
2138 * Performs multiplication: the class of the resulting object depends on
2139 * the class of <code>numeric</code> and on the magnitude of the
2140 * result.
2143 static VALUE
2144 fix_mul(VALUE x, VALUE y)
2146 if (FIXNUM_P(y)) {
2147 #ifdef __HP_cc
2148 /* avoids an optimization bug of HP aC++/ANSI C B3910B A.06.05 [Jul 25 2005] */
2149 volatile
2150 #endif
2151 SIGNED_VALUE a, b;
2152 #if SIZEOF_VALUE * 2 <= SIZEOF_LONG_LONG
2153 LONG_LONG d;
2154 #else
2155 SIGNED_VALUE c;
2156 VALUE r;
2157 #endif
2159 a = FIX2LONG(x);
2160 b = FIX2LONG(y);
2162 #if SIZEOF_VALUE * 2 <= SIZEOF_LONG_LONG
2163 d = (LONG_LONG)a * b;
2164 if (FIXABLE(d)) return LONG2FIX(d);
2165 return rb_ll2inum(d);
2166 #else
2167 if (FIT_SQRT_LONG(a) && FIT_SQRT_LONG(b))
2168 return LONG2FIX(a*b);
2169 c = a * b;
2170 r = LONG2FIX(c);
2172 if (a == 0) return x;
2173 if (FIX2LONG(r) != c || c/a != b) {
2174 r = rb_big_mul(rb_int2big(a), rb_int2big(b));
2176 return r;
2177 #endif
2179 switch (TYPE(y)) {
2180 case T_BIGNUM:
2181 return rb_big_mul(y, x);
2182 case T_FLOAT:
2183 return DOUBLE2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
2184 default:
2185 return rb_num_coerce_bin(x, y, '*');
2189 static void
2190 fixdivmod(long x, long y, long *divp, long *modp)
2192 long div, mod;
2194 if (y == 0) rb_num_zerodiv();
2195 if (y < 0) {
2196 if (x < 0)
2197 div = -x / -y;
2198 else
2199 div = - (x / -y);
2201 else {
2202 if (x < 0)
2203 div = - (-x / y);
2204 else
2205 div = x / y;
2207 mod = x - div*y;
2208 if ((mod < 0 && y > 0) || (mod > 0 && y < 0)) {
2209 mod += y;
2210 div -= 1;
2212 if (divp) *divp = div;
2213 if (modp) *modp = mod;
2217 * call-seq:
2218 * fix.quo(numeric) => float
2219 * fix.fdiv(numeric) => float
2221 * Returns the floating point result of dividing <i>fix</i> by
2222 * <i>numeric</i>.
2224 * 654321.quo(13731) #=> 47.6528293642124
2225 * 654321.quo(13731.24) #=> 47.6519964693647
2229 static VALUE
2230 fix_quo(VALUE x, VALUE y)
2232 return rb_funcall(rb_rational_raw1(x), '/', 1, y);
2235 static VALUE
2236 fix_fdiv(VALUE x, VALUE y)
2238 if (FIXNUM_P(y)) {
2239 return DOUBLE2NUM((double)FIX2LONG(x) / (double)FIX2LONG(y));
2241 switch (TYPE(y)) {
2242 case T_BIGNUM:
2243 return DOUBLE2NUM((double)FIX2LONG(x) / rb_big2dbl(y));
2244 case T_FLOAT:
2245 return DOUBLE2NUM((double)FIX2LONG(x) / RFLOAT_VALUE(y));
2246 default:
2247 return rb_num_coerce_bin(x, y, rb_intern("fdiv"));
2251 static VALUE
2252 fix_divide(VALUE x, VALUE y, ID op)
2254 if (FIXNUM_P(y)) {
2255 long div;
2257 fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
2258 return LONG2NUM(div);
2260 switch (TYPE(y)) {
2261 case T_BIGNUM:
2262 x = rb_int2big(FIX2LONG(x));
2263 return rb_big_div(x, y);
2264 case T_FLOAT:
2266 double div = (double)FIX2LONG(x) / RFLOAT_VALUE(y);
2267 if (op == '/') {
2268 return DOUBLE2NUM(div);
2270 else {
2271 return rb_dbl2big(div);
2274 default:
2275 return rb_num_coerce_bin(x, y, op);
2280 * call-seq:
2281 * fix / numeric => numeric_result
2283 * Performs division: the class of the resulting object depends on
2284 * the class of <code>numeric</code> and on the magnitude of the
2285 * result.
2288 static VALUE
2289 fix_div(VALUE x, VALUE y)
2291 return fix_divide(x, y, '/');
2295 * call-seq:
2296 * fix.div(numeric) => numeric_result
2298 * Performs integer division: returns integer value.
2301 static VALUE
2302 fix_idiv(VALUE x, VALUE y)
2304 return fix_divide(x, y, rb_intern("div"));
2308 * call-seq:
2309 * fix % other => Numeric
2310 * fix.modulo(other) => Numeric
2312 * Returns <code>fix</code> modulo <code>other</code>.
2313 * See <code>Numeric.divmod</code> for more information.
2316 static VALUE
2317 fix_mod(VALUE x, VALUE y)
2319 if (FIXNUM_P(y)) {
2320 long mod;
2322 fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
2323 return LONG2NUM(mod);
2325 switch (TYPE(y)) {
2326 case T_BIGNUM:
2327 x = rb_int2big(FIX2LONG(x));
2328 return rb_big_modulo(x, y);
2329 case T_FLOAT:
2331 double mod;
2333 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), 0, &mod);
2334 return DOUBLE2NUM(mod);
2336 default:
2337 return rb_num_coerce_bin(x, y, '%');
2342 * call-seq:
2343 * fix.divmod(numeric) => array
2345 * See <code>Numeric#divmod</code>.
2347 static VALUE
2348 fix_divmod(VALUE x, VALUE y)
2350 if (FIXNUM_P(y)) {
2351 long div, mod;
2353 fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, &mod);
2355 return rb_assoc_new(LONG2NUM(div), LONG2NUM(mod));
2357 switch (TYPE(y)) {
2358 case T_BIGNUM:
2359 x = rb_int2big(FIX2LONG(x));
2360 return rb_big_divmod(x, y);
2361 case T_FLOAT:
2363 double div, mod;
2364 volatile VALUE a, b;
2366 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
2367 a = dbl2ival(div);
2368 b = DOUBLE2NUM(mod);
2369 return rb_assoc_new(a, b);
2371 default:
2372 return rb_num_coerce_bin(x, y, rb_intern("divmod"));
2376 static VALUE
2377 int_pow(long x, unsigned long y)
2379 int neg = x < 0;
2380 long z = 1;
2382 if (neg) x = -x;
2383 if (y & 1)
2384 z = x;
2385 else
2386 neg = 0;
2387 y &= ~1;
2388 do {
2389 while (y % 2 == 0) {
2390 if (!FIT_SQRT_LONG(x)) {
2391 VALUE v;
2392 bignum:
2393 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
2394 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
2395 return v;
2397 x = x * x;
2398 y >>= 1;
2401 long xz = x * z;
2402 if (!POSFIXABLE(xz) || xz / x != z) {
2403 goto bignum;
2405 z = xz;
2407 } while (--y);
2408 if (neg) z = -z;
2409 return LONG2NUM(z);
2413 * call-seq:
2414 * fix ** other => Numeric
2416 * Raises <code>fix</code> to the <code>other</code> power, which may
2417 * be negative or fractional.
2419 * 2 ** 3 #=> 8
2420 * 2 ** -1 #=> 0.5
2421 * 2 ** 0.5 #=> 1.4142135623731
2424 static VALUE
2425 fix_pow(VALUE x, VALUE y)
2427 static const double zero = 0.0;
2428 long a = FIX2LONG(x);
2430 if (FIXNUM_P(y)) {
2431 long b = FIX2LONG(y);
2433 if (b < 0)
2434 return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2436 if (b == 0) return INT2FIX(1);
2437 if (b == 1) return x;
2438 if (a == 0) {
2439 if (b > 0) return INT2FIX(0);
2440 return DOUBLE2NUM(1.0 / zero);
2442 if (a == 1) return INT2FIX(1);
2443 if (a == -1) {
2444 if (b % 2 == 0)
2445 return INT2FIX(1);
2446 else
2447 return INT2FIX(-1);
2449 return int_pow(a, b);
2451 switch (TYPE(y)) {
2452 case T_BIGNUM:
2454 if (rb_funcall(y, '<', 1, INT2FIX(0)))
2455 return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2457 if (a == 0) return INT2FIX(0);
2458 if (a == 1) return INT2FIX(1);
2459 if (a == -1) {
2460 if (int_even_p(y)) return INT2FIX(1);
2461 else return INT2FIX(-1);
2463 x = rb_int2big(FIX2LONG(x));
2464 return rb_big_pow(x, y);
2465 case T_FLOAT:
2466 if (RFLOAT_VALUE(y) == 0.0) return DOUBLE2NUM(1.0);
2467 if (a == 0) {
2468 return DOUBLE2NUM(RFLOAT_VALUE(y) < 0 ? (1.0 / zero) : 0.0);
2470 if (a == 1) return DOUBLE2NUM(1.0);
2471 return DOUBLE2NUM(pow((double)a, RFLOAT_VALUE(y)));
2472 default:
2473 return rb_num_coerce_bin(x, y, rb_intern("**"));
2478 * call-seq:
2479 * fix == other
2481 * Return <code>true</code> if <code>fix</code> equals <code>other</code>
2482 * numerically.
2484 * 1 == 2 #=> false
2485 * 1 == 1.0 #=> true
2488 static VALUE
2489 fix_equal(VALUE x, VALUE y)
2491 if (x == y) return Qtrue;
2492 if (FIXNUM_P(y)) return Qfalse;
2493 switch (TYPE(y)) {
2494 case T_BIGNUM:
2495 return rb_big_eq(y, x);
2496 case T_FLOAT:
2497 return (double)FIX2LONG(x) == RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2498 default:
2499 return num_equal(x, y);
2504 * call-seq:
2505 * fix <=> numeric => -1, 0, +1
2507 * Comparison---Returns -1, 0, or +1 depending on whether <i>fix</i> is
2508 * less than, equal to, or greater than <i>numeric</i>. This is the
2509 * basis for the tests in <code>Comparable</code>.
2512 static VALUE
2513 fix_cmp(VALUE x, VALUE y)
2515 if (x == y) return INT2FIX(0);
2516 if (FIXNUM_P(y)) {
2517 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
2518 return INT2FIX(-1);
2520 switch (TYPE(y)) {
2521 case T_BIGNUM:
2522 return rb_big_cmp(rb_int2big(FIX2LONG(x)), y);
2523 case T_FLOAT:
2524 return rb_dbl_cmp((double)FIX2LONG(x), RFLOAT_VALUE(y));
2525 default:
2526 return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
2531 * call-seq:
2532 * fix > other => true or false
2534 * Returns <code>true</code> if the value of <code>fix</code> is
2535 * greater than that of <code>other</code>.
2538 static VALUE
2539 fix_gt(VALUE x, VALUE y)
2541 if (FIXNUM_P(y)) {
2542 if (FIX2LONG(x) > FIX2LONG(y)) return Qtrue;
2543 return Qfalse;
2545 switch (TYPE(y)) {
2546 case T_BIGNUM:
2547 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) > 0 ? Qtrue : Qfalse;
2548 case T_FLOAT:
2549 return (double)FIX2LONG(x) > RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2550 default:
2551 return rb_num_coerce_relop(x, y, '>');
2556 * call-seq:
2557 * fix >= other => true or false
2559 * Returns <code>true</code> if the value of <code>fix</code> is
2560 * greater than or equal to that of <code>other</code>.
2563 static VALUE
2564 fix_ge(VALUE x, VALUE y)
2566 if (FIXNUM_P(y)) {
2567 if (FIX2LONG(x) >= FIX2LONG(y)) return Qtrue;
2568 return Qfalse;
2570 switch (TYPE(y)) {
2571 case T_BIGNUM:
2572 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) >= 0 ? Qtrue : Qfalse;
2573 case T_FLOAT:
2574 return (double)FIX2LONG(x) >= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2575 default:
2576 return rb_num_coerce_relop(x, y, rb_intern(">="));
2581 * call-seq:
2582 * fix < other => true or false
2584 * Returns <code>true</code> if the value of <code>fix</code> is
2585 * less than that of <code>other</code>.
2588 static VALUE
2589 fix_lt(VALUE x, VALUE y)
2591 if (FIXNUM_P(y)) {
2592 if (FIX2LONG(x) < FIX2LONG(y)) return Qtrue;
2593 return Qfalse;
2595 switch (TYPE(y)) {
2596 case T_BIGNUM:
2597 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) < 0 ? Qtrue : Qfalse;
2598 case T_FLOAT:
2599 return (double)FIX2LONG(x) < RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2600 default:
2601 return rb_num_coerce_relop(x, y, '<');
2606 * call-seq:
2607 * fix <= other => true or false
2609 * Returns <code>true</code> if the value of <code>fix</code> is
2610 * less than or equal to that of <code>other</code>.
2613 static VALUE
2614 fix_le(VALUE x, VALUE y)
2616 if (FIXNUM_P(y)) {
2617 if (FIX2LONG(x) <= FIX2LONG(y)) return Qtrue;
2618 return Qfalse;
2620 switch (TYPE(y)) {
2621 case T_BIGNUM:
2622 return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) <= 0 ? Qtrue : Qfalse;
2623 case T_FLOAT:
2624 return (double)FIX2LONG(x) <= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2625 default:
2626 return rb_num_coerce_relop(x, y, rb_intern("<="));
2631 * call-seq:
2632 * ~fix => integer
2634 * One's complement: returns a number where each bit is flipped.
2637 static VALUE
2638 fix_rev(VALUE num)
2640 long val = FIX2LONG(num);
2642 val = ~val;
2643 return LONG2NUM(val);
2646 static VALUE
2647 fix_coerce(VALUE x)
2649 while (!FIXNUM_P(x) && TYPE(x) != T_BIGNUM) {
2650 x = rb_to_int(x);
2652 return x;
2656 * call-seq:
2657 * fix & other => integer
2659 * Bitwise AND.
2662 static VALUE
2663 fix_and(VALUE x, VALUE y)
2665 long val;
2667 if (!FIXNUM_P(y = fix_coerce(y))) {
2668 return rb_big_and(y, x);
2670 val = FIX2LONG(x) & FIX2LONG(y);
2671 return LONG2NUM(val);
2675 * call-seq:
2676 * fix | other => integer
2678 * Bitwise OR.
2681 static VALUE
2682 fix_or(VALUE x, VALUE y)
2684 long val;
2686 if (!FIXNUM_P(y = fix_coerce(y))) {
2687 return rb_big_or(y, x);
2689 val = FIX2LONG(x) | FIX2LONG(y);
2690 return LONG2NUM(val);
2694 * call-seq:
2695 * fix ^ other => integer
2697 * Bitwise EXCLUSIVE OR.
2700 static VALUE
2701 fix_xor(VALUE x, VALUE y)
2703 long val;
2705 if (!FIXNUM_P(y = fix_coerce(y))) {
2706 return rb_big_xor(y, x);
2708 val = FIX2LONG(x) ^ FIX2LONG(y);
2709 return LONG2NUM(val);
2712 static VALUE fix_lshift(long, unsigned long);
2713 static VALUE fix_rshift(long, unsigned long);
2716 * call-seq:
2717 * fix << count => integer
2719 * Shifts _fix_ left _count_ positions (right if _count_ is negative).
2722 static VALUE
2723 rb_fix_lshift(VALUE x, VALUE y)
2725 long val, width;
2727 val = NUM2LONG(x);
2728 if (!FIXNUM_P(y))
2729 return rb_big_lshift(rb_int2big(val), y);
2730 width = FIX2LONG(y);
2731 if (width < 0)
2732 return fix_rshift(val, (unsigned long)-width);
2733 return fix_lshift(val, width);
2736 static VALUE
2737 fix_lshift(long val, unsigned long width)
2739 if (width > (SIZEOF_LONG*CHAR_BIT-1)
2740 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
2741 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
2743 val = val << width;
2744 return LONG2NUM(val);
2748 * call-seq:
2749 * fix >> count => integer
2751 * Shifts _fix_ right _count_ positions (left if _count_ is negative).
2754 static VALUE
2755 rb_fix_rshift(VALUE x, VALUE y)
2757 long i, val;
2759 val = FIX2LONG(x);
2760 if (!FIXNUM_P(y))
2761 return rb_big_rshift(rb_int2big(val), y);
2762 i = FIX2LONG(y);
2763 if (i == 0) return x;
2764 if (i < 0)
2765 return fix_lshift(val, (unsigned long)-i);
2766 return fix_rshift(val, i);
2769 static VALUE
2770 fix_rshift(long val, unsigned long i)
2772 if (i >= sizeof(long)*CHAR_BIT-1) {
2773 if (val < 0) return INT2FIX(-1);
2774 return INT2FIX(0);
2776 val = RSHIFT(val, i);
2777 return LONG2FIX(val);
2781 * call-seq:
2782 * fix[n] => 0, 1
2784 * Bit Reference---Returns the <em>n</em>th bit in the binary
2785 * representation of <i>fix</i>, where <i>fix</i>[0] is the least
2786 * significant bit.
2788 * a = 0b11001100101010
2789 * 30.downto(0) do |n| print a[n] end
2791 * <em>produces:</em>
2793 * 0000000000000000011001100101010
2796 static VALUE
2797 fix_aref(VALUE fix, VALUE idx)
2799 long val = FIX2LONG(fix);
2800 long i;
2802 if (!FIXNUM_P(idx = fix_coerce(idx))) {
2803 idx = rb_big_norm(idx);
2804 if (!FIXNUM_P(idx)) {
2805 if (!RBIGNUM_SIGN(idx) || val >= 0)
2806 return INT2FIX(0);
2807 return INT2FIX(1);
2810 i = FIX2LONG(idx);
2812 if (i < 0) return INT2FIX(0);
2813 if (SIZEOF_LONG*CHAR_BIT-1 < i) {
2814 if (val < 0) return INT2FIX(1);
2815 return INT2FIX(0);
2817 if (val & (1L<<i))
2818 return INT2FIX(1);
2819 return INT2FIX(0);
2823 * call-seq:
2824 * fix.to_f -> float
2826 * Converts <i>fix</i> to a <code>Float</code>.
2830 static VALUE
2831 fix_to_f(VALUE num)
2833 double val;
2835 val = (double)FIX2LONG(num);
2837 return DOUBLE2NUM(val);
2841 * call-seq:
2842 * fix.abs -> aFixnum
2844 * Returns the absolute value of <i>fix</i>.
2846 * -12345.abs #=> 12345
2847 * 12345.abs #=> 12345
2851 static VALUE
2852 fix_abs(VALUE fix)
2854 long i = FIX2LONG(fix);
2856 if (i < 0) i = -i;
2858 return LONG2NUM(i);
2862 * call-seq:
2863 * fix.id2name -> string or nil
2865 * Returns the name of the object whose symbol id is <i>fix</i>. If
2866 * there is no symbol in the symbol table with this value, returns
2867 * <code>nil</code>. <code>id2name</code> has nothing to do with the
2868 * <code>Object.id</code> method. See also <code>Fixnum#to_sym</code>,
2869 * <code>String#intern</code>, and class <code>Symbol</code>.
2871 * symbol = :@inst_var #=> :@inst_var
2872 * id = symbol.to_i #=> 9818
2873 * id.id2name #=> "@inst_var"
2876 static VALUE
2877 fix_id2name(VALUE fix)
2879 VALUE name = rb_id2str(FIX2UINT(fix));
2880 if (name) return rb_str_dup(name);
2881 return Qnil;
2886 * call-seq:
2887 * fix.to_sym -> aSymbol
2889 * Returns the symbol whose integer value is <i>fix</i>. See also
2890 * <code>Fixnum#id2name</code>.
2892 * fred = :fred.to_i
2893 * fred.id2name #=> "fred"
2894 * fred.to_sym #=> :fred
2897 static VALUE
2898 fix_to_sym(VALUE fix)
2900 ID id = FIX2UINT(fix);
2902 if (rb_id2name(id)) {
2903 return ID2SYM(id);
2905 return Qnil;
2910 * call-seq:
2911 * fix.size -> fixnum
2913 * Returns the number of <em>bytes</em> in the machine representation
2914 * of a <code>Fixnum</code>.
2916 * 1.size #=> 4
2917 * -1.size #=> 4
2918 * 2147483647.size #=> 4
2921 static VALUE
2922 fix_size(VALUE fix)
2924 return INT2FIX(sizeof(long));
2928 * call-seq:
2929 * int.upto(limit) {|i| block } => int
2931 * Iterates <em>block</em>, passing in integer values from <i>int</i>
2932 * up to and including <i>limit</i>.
2934 * 5.upto(10) { |i| print i, " " }
2936 * <em>produces:</em>
2938 * 5 6 7 8 9 10
2941 static VALUE
2942 int_upto(VALUE from, VALUE to)
2944 RETURN_ENUMERATOR(from, 1, &to);
2945 if (FIXNUM_P(from) && FIXNUM_P(to)) {
2946 long i, end;
2948 end = FIX2LONG(to);
2949 for (i = FIX2LONG(from); i <= end; i++) {
2950 rb_yield(LONG2FIX(i));
2953 else {
2954 VALUE i = from, c;
2956 while (!(c = rb_funcall(i, '>', 1, to))) {
2957 rb_yield(i);
2958 i = rb_funcall(i, '+', 1, INT2FIX(1));
2960 if (NIL_P(c)) rb_cmperr(i, to);
2962 return from;
2966 * call-seq:
2967 * int.downto(limit) {|i| block } => int
2969 * Iterates <em>block</em>, passing decreasing values from <i>int</i>
2970 * down to and including <i>limit</i>.
2972 * 5.downto(1) { |n| print n, ".. " }
2973 * print " Liftoff!\n"
2975 * <em>produces:</em>
2977 * 5.. 4.. 3.. 2.. 1.. Liftoff!
2980 static VALUE
2981 int_downto(VALUE from, VALUE to)
2983 RETURN_ENUMERATOR(from, 1, &to);
2984 if (FIXNUM_P(from) && FIXNUM_P(to)) {
2985 long i, end;
2987 end = FIX2LONG(to);
2988 for (i=FIX2LONG(from); i >= end; i--) {
2989 rb_yield(LONG2FIX(i));
2992 else {
2993 VALUE i = from, c;
2995 while (!(c = rb_funcall(i, '<', 1, to))) {
2996 rb_yield(i);
2997 i = rb_funcall(i, '-', 1, INT2FIX(1));
2999 if (NIL_P(c)) rb_cmperr(i, to);
3001 return from;
3005 * call-seq:
3006 * int.times {|i| block } => int
3008 * Iterates block <i>int</i> times, passing in values from zero to
3009 * <i>int</i> - 1.
3011 * 5.times do |i|
3012 * print i, " "
3013 * end
3015 * <em>produces:</em>
3017 * 0 1 2 3 4
3020 static VALUE
3021 int_dotimes(VALUE num)
3023 RETURN_ENUMERATOR(num, 0, 0);
3025 if (FIXNUM_P(num)) {
3026 long i, end;
3028 end = FIX2LONG(num);
3029 for (i=0; i<end; i++) {
3030 rb_yield(LONG2FIX(i));
3033 else {
3034 VALUE i = INT2FIX(0);
3036 for (;;) {
3037 if (!RTEST(rb_funcall(i, '<', 1, num))) break;
3038 rb_yield(i);
3039 i = rb_funcall(i, '+', 1, INT2FIX(1));
3042 return num;
3045 static VALUE
3046 int_round(int argc, VALUE* argv, VALUE num)
3048 VALUE n, f, h, r;
3049 int ndigits;
3051 if (argc == 0) return num;
3052 rb_scan_args(argc, argv, "1", &n);
3053 ndigits = NUM2INT(n);
3054 if (ndigits > 0) {
3055 return rb_Float(num);
3057 if (ndigits == 0) {
3058 return num;
3060 ndigits = -ndigits;
3061 if (ndigits < 0) {
3062 rb_raise(rb_eArgError, "ndigits out of range");
3064 f = int_pow(10, ndigits);
3065 if (FIXNUM_P(num) && FIXNUM_P(f)) {
3066 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
3067 int neg = x < 0;
3068 if (neg) x = -x;
3069 x = (x + y / 2) / y * y;
3070 if (neg) x = -x;
3071 return LONG2NUM(x);
3073 h = rb_funcall(f, '/', 1, INT2FIX(2));
3074 r = rb_funcall(num, '%', 1, f);
3075 n = rb_funcall(num, '-', 1, r);
3076 if (!RTEST(rb_funcall(r, '<', 1, h))) {
3077 n = rb_funcall(n, '+', 1, f);
3079 return n;
3083 * call-seq:
3084 * fix.zero? => true or false
3086 * Returns <code>true</code> if <i>fix</i> is zero.
3090 static VALUE
3091 fix_zero_p(VALUE num)
3093 if (FIX2LONG(num) == 0) {
3094 return Qtrue;
3096 return Qfalse;
3100 * call-seq:
3101 * fix.odd? -> true or false
3103 * Returns <code>true</code> if <i>fix</i> is an odd number.
3106 static VALUE
3107 fix_odd_p(VALUE num)
3109 if (num & 2) {
3110 return Qtrue;
3112 return Qfalse;
3116 * call-seq:
3117 * fix.even? -> true or false
3119 * Returns <code>true</code> if <i>fix</i> is an even number.
3122 static VALUE
3123 fix_even_p(VALUE num)
3125 if (num & 2) {
3126 return Qfalse;
3128 return Qtrue;
3131 void
3132 Init_Numeric(void)
3134 #if defined(__FreeBSD__) && __FreeBSD__ < 4
3135 /* allow divide by zero -- Inf */
3136 fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV|FP_X_OFL));
3137 #elif defined(_UNICOSMP)
3138 /* Turn off floating point exceptions for divide by zero, etc. */
3139 _set_Creg(0, 0);
3140 #elif defined(__BORLANDC__)
3141 /* Turn off floating point exceptions for overflow, etc. */
3142 _control87(MCW_EM, MCW_EM);
3143 #endif
3144 id_coerce = rb_intern("coerce");
3145 id_to_i = rb_intern("to_i");
3146 id_eq = rb_intern("==");
3148 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
3149 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
3150 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
3152 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
3153 rb_include_module(rb_cNumeric, rb_mComparable);
3154 rb_define_method(rb_cNumeric, "initialize_copy", num_init_copy, 1);
3155 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
3157 rb_define_method(rb_cNumeric, "+@", num_uplus, 0);
3158 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
3159 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
3160 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
3161 rb_define_method(rb_cNumeric, "quo", num_quo, 1);
3162 rb_define_method(rb_cNumeric, "fdiv", num_quo, 1);
3163 rb_define_method(rb_cNumeric, "div", num_div, 1);
3164 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
3165 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
3166 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
3167 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
3168 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
3170 rb_define_method(rb_cNumeric, "scalar?", num_scalar_p, 0);
3171 rb_define_method(rb_cNumeric, "integer?", num_int_p, 0);
3172 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
3173 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
3175 rb_define_method(rb_cNumeric, "floor", num_floor, 0);
3176 rb_define_method(rb_cNumeric, "ceil", num_ceil, 0);
3177 rb_define_method(rb_cNumeric, "round", num_round, -1);
3178 rb_define_method(rb_cNumeric, "truncate", num_truncate, 0);
3179 rb_define_method(rb_cNumeric, "step", num_step, -1);
3181 rb_define_method(rb_cNumeric, "numerator", num_numerator, 0);
3182 rb_define_method(rb_cNumeric, "denominator", num_denominator, 0);
3184 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
3185 rb_undef_alloc_func(rb_cInteger);
3186 rb_undef_method(CLASS_OF(rb_cInteger), "new");
3188 rb_define_method(rb_cInteger, "integer?", int_int_p, 0);
3189 rb_define_method(rb_cInteger, "odd?", int_odd_p, 0);
3190 rb_define_method(rb_cInteger, "even?", int_even_p, 0);
3191 rb_define_method(rb_cInteger, "upto", int_upto, 1);
3192 rb_define_method(rb_cInteger, "downto", int_downto, 1);
3193 rb_define_method(rb_cInteger, "times", int_dotimes, 0);
3194 rb_include_module(rb_cInteger, rb_mPrecision);
3195 rb_define_method(rb_cInteger, "succ", int_succ, 0);
3196 rb_define_method(rb_cInteger, "next", int_succ, 0);
3197 rb_define_method(rb_cInteger, "pred", int_pred, 0);
3198 rb_define_method(rb_cInteger, "chr", int_chr, -1);
3199 rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
3200 rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
3201 rb_define_method(rb_cInteger, "floor", int_to_i, 0);
3202 rb_define_method(rb_cInteger, "ceil", int_to_i, 0);
3203 rb_define_method(rb_cInteger, "truncate", int_to_i, 0);
3204 rb_define_method(rb_cInteger, "round", int_round, -1);
3206 rb_cFixnum = rb_define_class("Fixnum", rb_cInteger);
3207 rb_include_module(rb_cFixnum, rb_mPrecision);
3208 rb_define_singleton_method(rb_cFixnum, "induced_from", rb_fix_induced_from, 1);
3209 rb_define_singleton_method(rb_cInteger, "induced_from", rb_int_induced_from, 1);
3211 rb_define_method(rb_cInteger, "numerator", int_numerator, 0);
3212 rb_define_method(rb_cInteger, "denominator", int_denominator, 0);
3214 rb_define_method(rb_cFixnum, "to_s", fix_to_s, -1);
3216 rb_define_method(rb_cFixnum, "id2name", fix_id2name, 0);
3217 rb_define_method(rb_cFixnum, "to_sym", fix_to_sym, 0);
3219 rb_define_method(rb_cFixnum, "-@", fix_uminus, 0);
3220 rb_define_method(rb_cFixnum, "+", fix_plus, 1);
3221 rb_define_method(rb_cFixnum, "-", fix_minus, 1);
3222 rb_define_method(rb_cFixnum, "*", fix_mul, 1);
3223 rb_define_method(rb_cFixnum, "/", fix_div, 1);
3224 rb_define_method(rb_cFixnum, "div", fix_idiv, 1);
3225 rb_define_method(rb_cFixnum, "%", fix_mod, 1);
3226 rb_define_method(rb_cFixnum, "modulo", fix_mod, 1);
3227 rb_define_method(rb_cFixnum, "divmod", fix_divmod, 1);
3228 rb_define_method(rb_cFixnum, "quo", fix_quo, 1);
3229 rb_define_method(rb_cFixnum, "fdiv", fix_fdiv, 1);
3230 rb_define_method(rb_cFixnum, "**", fix_pow, 1);
3232 rb_define_method(rb_cFixnum, "abs", fix_abs, 0);
3234 rb_define_method(rb_cFixnum, "==", fix_equal, 1);
3235 rb_define_method(rb_cFixnum, "<=>", fix_cmp, 1);
3236 rb_define_method(rb_cFixnum, ">", fix_gt, 1);
3237 rb_define_method(rb_cFixnum, ">=", fix_ge, 1);
3238 rb_define_method(rb_cFixnum, "<", fix_lt, 1);
3239 rb_define_method(rb_cFixnum, "<=", fix_le, 1);
3241 rb_define_method(rb_cFixnum, "~", fix_rev, 0);
3242 rb_define_method(rb_cFixnum, "&", fix_and, 1);
3243 rb_define_method(rb_cFixnum, "|", fix_or, 1);
3244 rb_define_method(rb_cFixnum, "^", fix_xor, 1);
3245 rb_define_method(rb_cFixnum, "[]", fix_aref, 1);
3247 rb_define_method(rb_cFixnum, "<<", rb_fix_lshift, 1);
3248 rb_define_method(rb_cFixnum, ">>", rb_fix_rshift, 1);
3250 rb_define_method(rb_cFixnum, "to_f", fix_to_f, 0);
3251 rb_define_method(rb_cFixnum, "size", fix_size, 0);
3252 rb_define_method(rb_cFixnum, "zero?", fix_zero_p, 0);
3253 rb_define_method(rb_cFixnum, "odd?", fix_odd_p, 0);
3254 rb_define_method(rb_cFixnum, "even?", fix_even_p, 0);
3255 rb_define_method(rb_cFixnum, "succ", fix_succ, 0);
3257 rb_cFloat = rb_define_class("Float", rb_cNumeric);
3259 rb_undef_alloc_func(rb_cFloat);
3260 rb_undef_method(CLASS_OF(rb_cFloat), "new");
3262 rb_define_singleton_method(rb_cFloat, "induced_from", rb_flo_induced_from, 1);
3263 rb_include_module(rb_cFloat, rb_mPrecision);
3265 rb_define_const(rb_cFloat, "ROUNDS", INT2FIX(FLT_ROUNDS));
3266 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
3267 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
3268 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
3269 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
3270 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
3271 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
3272 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
3273 rb_define_const(rb_cFloat, "MIN", DOUBLE2NUM(DBL_MIN));
3274 rb_define_const(rb_cFloat, "MAX", DOUBLE2NUM(DBL_MAX));
3275 rb_define_const(rb_cFloat, "EPSILON", DOUBLE2NUM(DBL_EPSILON));
3277 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
3278 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
3279 rb_define_method(rb_cFloat, "-@", flo_uminus, 0);
3280 rb_define_method(rb_cFloat, "+", flo_plus, 1);
3281 rb_define_method(rb_cFloat, "-", flo_minus, 1);
3282 rb_define_method(rb_cFloat, "*", flo_mul, 1);
3283 rb_define_method(rb_cFloat, "/", flo_div, 1);
3284 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
3285 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
3286 rb_define_method(rb_cFloat, "%", flo_mod, 1);
3287 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
3288 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
3289 rb_define_method(rb_cFloat, "**", flo_pow, 1);
3290 rb_define_method(rb_cFloat, "==", flo_eq, 1);
3291 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
3292 rb_define_method(rb_cFloat, ">", flo_gt, 1);
3293 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
3294 rb_define_method(rb_cFloat, "<", flo_lt, 1);
3295 rb_define_method(rb_cFloat, "<=", flo_le, 1);
3296 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
3297 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
3298 rb_define_method(rb_cFloat, "to_f", flo_to_f, 0);
3299 rb_define_method(rb_cFloat, "abs", flo_abs, 0);
3300 rb_define_method(rb_cFloat, "zero?", flo_zero_p, 0);
3302 rb_define_method(rb_cFloat, "to_i", flo_truncate, 0);
3303 rb_define_method(rb_cFloat, "to_int", flo_truncate, 0);
3304 rb_define_method(rb_cFloat, "floor", flo_floor, 0);
3305 rb_define_method(rb_cFloat, "ceil", flo_ceil, 0);
3306 rb_define_method(rb_cFloat, "round", flo_round, -1);
3307 rb_define_method(rb_cFloat, "truncate", flo_truncate, 0);
3309 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
3310 rb_define_method(rb_cFloat, "infinite?", flo_is_infinite_p, 0);
3311 rb_define_method(rb_cFloat, "finite?", flo_is_finite_p, 0);