Ruby  1.9.3p551(2014-11-13revision48407)
numeric.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  numeric.c -
4 
5  $Author: usa $
6  created at: Fri Aug 13 18:33:09 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 #include "ruby/ruby.h"
13 #include "ruby/encoding.h"
14 #include "ruby/util.h"
15 #include "internal.h"
16 #include <ctype.h>
17 #include <math.h>
18 #include <stdio.h>
19 
20 #if defined(__FreeBSD__) && __FreeBSD__ < 4
21 #include <floatingpoint.h>
22 #endif
23 
24 #ifdef HAVE_FLOAT_H
25 #include <float.h>
26 #endif
27 
28 #ifdef HAVE_IEEEFP_H
29 #include <ieeefp.h>
30 #endif
31 
32 /* use IEEE 64bit values if not defined */
33 #ifndef FLT_RADIX
34 #define FLT_RADIX 2
35 #endif
36 #ifndef FLT_ROUNDS
37 #define FLT_ROUNDS 1
38 #endif
39 #ifndef DBL_MIN
40 #define DBL_MIN 2.2250738585072014e-308
41 #endif
42 #ifndef DBL_MAX
43 #define DBL_MAX 1.7976931348623157e+308
44 #endif
45 #ifndef DBL_MIN_EXP
46 #define DBL_MIN_EXP (-1021)
47 #endif
48 #ifndef DBL_MAX_EXP
49 #define DBL_MAX_EXP 1024
50 #endif
51 #ifndef DBL_MIN_10_EXP
52 #define DBL_MIN_10_EXP (-307)
53 #endif
54 #ifndef DBL_MAX_10_EXP
55 #define DBL_MAX_10_EXP 308
56 #endif
57 #ifndef DBL_DIG
58 #define DBL_DIG 15
59 #endif
60 #ifndef DBL_MANT_DIG
61 #define DBL_MANT_DIG 53
62 #endif
63 #ifndef DBL_EPSILON
64 #define DBL_EPSILON 2.2204460492503131e-16
65 #endif
66 
67 #ifdef HAVE_INFINITY
68 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
69 const unsigned char rb_infinity[] = "\x00\x00\x80\x7f";
70 #else
71 const unsigned char rb_infinity[] = "\x7f\x80\x00\x00";
72 #endif
73 
74 #ifdef HAVE_NAN
75 #elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
76 const unsigned char rb_nan[] = "\x00\x00\xc0\x7f";
77 #else
78 const unsigned char rb_nan[] = "\x7f\xc0\x00\x00";
79 #endif
80 
81 #ifndef HAVE_ROUND
82 double
83 round(double x)
84 {
85  double f;
86 
87  if (x > 0.0) {
88  f = floor(x);
89  x = f + (x - f >= 0.5);
90  }
91  else if (x < 0.0) {
92  f = ceil(x);
93  x = f - (f - x >= 0.5);
94  }
95  return x;
96 }
97 #endif
98 
99 static VALUE fix_uminus(VALUE num);
100 static VALUE fix_mul(VALUE x, VALUE y);
101 static VALUE int_pow(long x, unsigned long y);
102 
104 
109 
112 
113 void
115 {
116  rb_raise(rb_eZeroDivError, "divided by 0");
117 }
118 
119 /* experimental API */
120 int
121 rb_num_to_uint(VALUE val, unsigned int *ret)
122 {
123 #define NUMERR_TYPE 1
124 #define NUMERR_NEGATIVE 2
125 #define NUMERR_TOOLARGE 3
126  if (FIXNUM_P(val)) {
127  long v = FIX2LONG(val);
128 #if SIZEOF_INT < SIZEOF_LONG
129  if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
130 #endif
131  if (v < 0) return NUMERR_NEGATIVE;
132  *ret = (unsigned int)v;
133  return 0;
134  }
135 
136  switch (TYPE(val)) {
137  case T_BIGNUM:
138  if (RBIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
139 #if SIZEOF_INT < SIZEOF_LONG
140  /* long is 64bit */
141  return NUMERR_TOOLARGE;
142 #else
143  /* long is 32bit */
144 #define DIGSPERLONG (SIZEOF_LONG/SIZEOF_BDIGITS)
145  if (RBIGNUM_LEN(val) > DIGSPERLONG) return NUMERR_TOOLARGE;
146  *ret = (unsigned int)rb_big2ulong((VALUE)val);
147  return 0;
148 #endif
149  }
150  return NUMERR_TYPE;
151 }
152 
153 /*
154  * call-seq:
155  * num.coerce(numeric) -> array
156  *
157  * If <i>aNumeric</i> is the same type as <i>num</i>, returns an array
158  * containing <i>aNumeric</i> and <i>num</i>. Otherwise, returns an
159  * array with both <i>aNumeric</i> and <i>num</i> represented as
160  * <code>Float</code> objects. This coercion mechanism is used by
161  * Ruby to handle mixed-type numeric operations: it is intended to
162  * find a compatible common type between the two operands of the operator.
163  *
164  * 1.coerce(2.5) #=> [2.5, 1.0]
165  * 1.2.coerce(3) #=> [3.0, 1.2]
166  * 1.coerce(2) #=> [2, 1]
167  */
168 
169 static VALUE
171 {
172  if (CLASS_OF(x) == CLASS_OF(y))
173  return rb_assoc_new(y, x);
174  x = rb_Float(x);
175  y = rb_Float(y);
176  return rb_assoc_new(y, x);
177 }
178 
179 static VALUE
181 {
182  return rb_funcall(x[1], id_coerce, 1, x[0]);
183 }
184 
185 static VALUE
187 {
188  volatile VALUE v = rb_inspect(x[1]);
189 
190  rb_raise(rb_eTypeError, "%s can't be coerced into %s",
191  rb_special_const_p(x[1])?
192  RSTRING_PTR(v):
193  rb_obj_classname(x[1]),
194  rb_obj_classname(x[0]));
195  return Qnil; /* dummy */
196 }
197 
198 static int
199 do_coerce(VALUE *x, VALUE *y, int err)
200 {
201  VALUE ary;
202  VALUE a[2];
203 
204  a[0] = *x; a[1] = *y;
205 
206  ary = rb_rescue(coerce_body, (VALUE)a, err?coerce_rescue:0, (VALUE)a);
207  if (TYPE(ary) != T_ARRAY || RARRAY_LEN(ary) != 2) {
208  if (err) {
209  rb_raise(rb_eTypeError, "coerce must return [x, y]");
210  }
211  return FALSE;
212  }
213 
214  *x = RARRAY_PTR(ary)[0];
215  *y = RARRAY_PTR(ary)[1];
216  return TRUE;
217 }
218 
219 VALUE
221 {
222  do_coerce(&x, &y, TRUE);
223  return rb_funcall(x, func, 1, y);
224 }
225 
226 VALUE
228 {
229  if (do_coerce(&x, &y, FALSE))
230  return rb_funcall(x, func, 1, y);
231  return Qnil;
232 }
233 
234 VALUE
236 {
237  VALUE c, x0 = x, y0 = y;
238 
239  if (!do_coerce(&x, &y, FALSE) ||
240  NIL_P(c = rb_funcall(x, func, 1, y))) {
241  rb_cmperr(x0, y0);
242  return Qnil; /* not reached */
243  }
244  return c;
245 }
246 
247 /*
248  * Trap attempts to add methods to <code>Numeric</code> objects. Always
249  * raises a <code>TypeError</code>
250  */
251 
252 static VALUE
254 {
255  ID mid = rb_to_id(name);
256  /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
257  /* Numerics should be values; singleton_methods should not be added to them */
260  "can't define singleton method \"%s\" for %s",
261  rb_id2name(mid),
262  rb_obj_classname(x));
263  return Qnil; /* not reached */
264 }
265 
266 /* :nodoc: */
267 static VALUE
269 {
270  /* Numerics are immutable values, which should not be copied */
271  rb_raise(rb_eTypeError, "can't copy %s", rb_obj_classname(x));
272  return Qnil; /* not reached */
273 }
274 
275 /*
276  * call-seq:
277  * +num -> num
278  *
279  * Unary Plus---Returns the receiver's value.
280  */
281 
282 static VALUE
284 {
285  return num;
286 }
287 
288 /*
289  * call-seq:
290  * num.i -> Complex(0,num)
291  *
292  * Returns the corresponding imaginary number.
293  * Not available for complex numbers.
294  */
295 
296 static VALUE
298 {
299  return rb_complex_new(INT2FIX(0), num);
300 }
301 
302 
303 /*
304  * call-seq:
305  * -num -> numeric
306  *
307  * Unary Minus---Returns the receiver's value, negated.
308  */
309 
310 static VALUE
312 {
313  VALUE zero;
314 
315  zero = INT2FIX(0);
316  do_coerce(&zero, &num, TRUE);
317 
318  return rb_funcall(zero, '-', 1, num);
319 }
320 
321 /*
322  * call-seq:
323  * num.quo(numeric) -> real
324  *
325  * Returns most exact division (rational for integers, float for floats).
326  */
327 
328 static VALUE
330 {
331  return rb_funcall(rb_rational_raw1(x), '/', 1, y);
332 }
333 
334 
335 /*
336  * call-seq:
337  * num.fdiv(numeric) -> float
338  *
339  * Returns float division.
340  */
341 
342 static VALUE
344 {
345  return rb_funcall(rb_Float(x), '/', 1, y);
346 }
347 
348 
349 /*
350  * call-seq:
351  * num.div(numeric) -> integer
352  *
353  * Uses <code>/</code> to perform division, then converts the result to
354  * an integer. <code>numeric</code> does not define the <code>/</code>
355  * operator; this is left to subclasses.
356  *
357  * Equivalent to
358  * <i>num</i>.<code>divmod(</code><i>aNumeric</i><code>)[0]</code>.
359  *
360  * See <code>Numeric#divmod</code>.
361  */
362 
363 static VALUE
365 {
366  if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
367  return rb_funcall(rb_funcall(x, '/', 1, y), rb_intern("floor"), 0);
368 }
369 
370 
371 /*
372  * call-seq:
373  * num.modulo(numeric) -> real
374  *
375  * x.modulo(y) means x-y*(x/y).floor
376  *
377  * Equivalent to
378  * <i>num</i>.<code>divmod(</code><i>aNumeric</i><code>)[1]</code>.
379  *
380  * See <code>Numeric#divmod</code>.
381  */
382 
383 static VALUE
385 {
386  return rb_funcall(x, '-', 1,
387  rb_funcall(y, '*', 1,
388  rb_funcall(x, rb_intern("div"), 1, y)));
389 }
390 
391 /*
392  * call-seq:
393  * num.remainder(numeric) -> real
394  *
395  * x.remainder(y) means x-y*(x/y).truncate
396  *
397  * See <code>Numeric#divmod</code>.
398  */
399 
400 static VALUE
402 {
403  VALUE z = rb_funcall(x, '%', 1, y);
404 
405  if ((!rb_equal(z, INT2FIX(0))) &&
406  ((RTEST(rb_funcall(x, '<', 1, INT2FIX(0))) &&
407  RTEST(rb_funcall(y, '>', 1, INT2FIX(0)))) ||
408  (RTEST(rb_funcall(x, '>', 1, INT2FIX(0))) &&
409  RTEST(rb_funcall(y, '<', 1, INT2FIX(0)))))) {
410  return rb_funcall(z, '-', 1, y);
411  }
412  return z;
413 }
414 
415 /*
416  * call-seq:
417  * num.divmod(numeric) -> array
418  *
419  * Returns an array containing the quotient and modulus obtained by
420  * dividing <i>num</i> by <i>numeric</i>. If <code>q, r =
421  * x.divmod(y)</code>, then
422  *
423  * q = floor(x/y)
424  * x = q*y+r
425  *
426  * The quotient is rounded toward -infinity, as shown in the following table:
427  *
428  * a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b)
429  * ------+-----+---------------+---------+-------------+---------------
430  * 13 | 4 | 3, 1 | 3 | 1 | 1
431  * ------+-----+---------------+---------+-------------+---------------
432  * 13 | -4 | -4, -3 | -4 | -3 | 1
433  * ------+-----+---------------+---------+-------------+---------------
434  * -13 | 4 | -4, 3 | -4 | 3 | -1
435  * ------+-----+---------------+---------+-------------+---------------
436  * -13 | -4 | 3, -1 | 3 | -1 | -1
437  * ------+-----+---------------+---------+-------------+---------------
438  * 11.5 | 4 | 2, 3.5 | 2.875 | 3.5 | 3.5
439  * ------+-----+---------------+---------+-------------+---------------
440  * 11.5 | -4 | -3, -0.5 | -2.875 | -0.5 | 3.5
441  * ------+-----+---------------+---------+-------------+---------------
442  * -11.5 | 4 | -3, 0.5 | -2.875 | 0.5 | -3.5
443  * ------+-----+---------------+---------+-------------+---------------
444  * -11.5 | -4 | 2, -3.5 | 2.875 | -3.5 | -3.5
445  *
446  *
447  * Examples
448  *
449  * 11.divmod(3) #=> [3, 2]
450  * 11.divmod(-3) #=> [-4, -1]
451  * 11.divmod(3.5) #=> [3, 0.5]
452  * (-11).divmod(3.5) #=> [-4, 3.0]
453  * (11.5).divmod(3.5) #=> [3, 1.0]
454  */
455 
456 static VALUE
458 {
459  return rb_assoc_new(num_div(x, y), num_modulo(x, y));
460 }
461 
462 /*
463  * call-seq:
464  * num.real? -> true or false
465  *
466  * Returns <code>true</code> if <i>num</i> is a <code>Real</code>
467  * (i.e. non <code>Complex</code>).
468  */
469 
470 static VALUE
472 {
473  return Qtrue;
474 }
475 
476 /*
477  * call-seq:
478  * num.integer? -> true or false
479  *
480  * Returns <code>true</code> if <i>num</i> is an <code>Integer</code>
481  * (including <code>Fixnum</code> and <code>Bignum</code>).
482  */
483 
484 static VALUE
486 {
487  return Qfalse;
488 }
489 
490 /*
491  * call-seq:
492  * num.abs -> numeric
493  * num.magnitude -> numeric
494  *
495  * Returns the absolute value of <i>num</i>.
496  *
497  * 12.abs #=> 12
498  * (-34.56).abs #=> 34.56
499  * -34.56.abs #=> 34.56
500  */
501 
502 static VALUE
504 {
505  if (RTEST(rb_funcall(num, '<', 1, INT2FIX(0)))) {
506  return rb_funcall(num, rb_intern("-@"), 0);
507  }
508  return num;
509 }
510 
511 
512 /*
513  * call-seq:
514  * num.zero? -> true or false
515  *
516  * Returns <code>true</code> if <i>num</i> has a zero value.
517  */
518 
519 static VALUE
521 {
522  if (rb_equal(num, INT2FIX(0))) {
523  return Qtrue;
524  }
525  return Qfalse;
526 }
527 
528 
529 /*
530  * call-seq:
531  * num.nonzero? -> self or nil
532  *
533  * Returns +self+ if <i>num</i> is not zero, <code>nil</code>
534  * otherwise. This behavior is useful when chaining comparisons:
535  *
536  * a = %w( z Bb bB bb BB a aA Aa AA A )
537  * b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
538  * b #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
539  */
540 
541 static VALUE
543 {
544  if (RTEST(rb_funcall(num, rb_intern("zero?"), 0, 0))) {
545  return Qnil;
546  }
547  return num;
548 }
549 
550 /*
551  * call-seq:
552  * num.to_int -> integer
553  *
554  * Invokes the child class's <code>to_i</code> method to convert
555  * <i>num</i> to an integer.
556  */
557 
558 static VALUE
560 {
561  return rb_funcall(num, id_to_i, 0, 0);
562 }
563 
564 
565 /********************************************************************
566  *
567  * Document-class: Float
568  *
569  * <code>Float</code> objects represent inexact real numbers using
570  * the native architecture's double-precision floating point
571  * representation.
572  *
573  * Floating point has a different arithmetic and is a inexact number.
574  * So you should know its esoteric system. see following:
575  *
576  * - http://docs.sun.com/source/806-3568/ncg_goldberg.html
577  * - http://wiki.github.com/rdp/ruby_tutorials_core/ruby-talk-faq#floats_imprecise
578  * - http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
579  */
580 
581 VALUE
582 rb_float_new(double d)
583 {
584  NEWOBJ(flt, struct RFloat);
585  OBJSETUP(flt, rb_cFloat, T_FLOAT);
586 
587  flt->float_value = d;
588  return (VALUE)flt;
589 }
590 
591 /*
592  * call-seq:
593  * flt.to_s -> string
594  *
595  * Returns a string containing a representation of self. As well as a
596  * fixed or exponential form of the number, the call may return
597  * ``<code>NaN</code>'', ``<code>Infinity</code>'', and
598  * ``<code>-Infinity</code>''.
599  */
600 
601 static VALUE
603 {
604  char *ruby_dtoa(double d_, int mode, int ndigits, int *decpt, int *sign, char **rve);
605  enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
606  enum {float_dig = DBL_DIG+1};
607  char buf[float_dig + (decimal_mant + CHAR_BIT - 1) / CHAR_BIT + 10];
608  double value = RFLOAT_VALUE(flt);
609  VALUE s;
610  char *p, *e;
611  int sign, decpt, digs;
612 
613  if (isinf(value))
614  return rb_usascii_str_new2(value < 0 ? "-Infinity" : "Infinity");
615  else if (isnan(value))
616  return rb_usascii_str_new2("NaN");
617 
618  p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
619  s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
620  if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
621  memcpy(buf, p, digs);
622  xfree(p);
623  if (decpt > 0) {
624  if (decpt < digs) {
625  memmove(buf + decpt + 1, buf + decpt, digs - decpt);
626  buf[decpt] = '.';
627  rb_str_cat(s, buf, digs + 1);
628  }
629  else if (decpt - digs < float_dig) {
630  long len;
631  char *ptr;
632  rb_str_cat(s, buf, digs);
633  rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
634  ptr = RSTRING_PTR(s) + len;
635  if (decpt > digs) {
636  memset(ptr, '0', decpt - digs);
637  ptr += decpt - digs;
638  }
639  memcpy(ptr, ".0", 2);
640  }
641  else {
642  goto exp;
643  }
644  }
645  else if (decpt > -4) {
646  long len;
647  char *ptr;
648  rb_str_cat(s, "0.", 2);
649  rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
650  ptr = RSTRING_PTR(s);
651  memset(ptr += len, '0', -decpt);
652  memcpy(ptr -= decpt, buf, digs);
653  }
654  else {
655  exp:
656  if (digs > 1) {
657  memmove(buf + 2, buf + 1, digs - 1);
658  }
659  else {
660  buf[2] = '0';
661  digs++;
662  }
663  buf[1] = '.';
664  rb_str_cat(s, buf, digs + 1);
665  rb_str_catf(s, "e%+03d", decpt - 1);
666  }
667  return s;
668 }
669 
670 /*
671  * call-seq:
672  * flt.coerce(numeric) -> array
673  *
674  * Returns an array with both <i>aNumeric</i> and <i>flt</i> represented
675  * as <code>Float</code> objects.
676  * This is achieved by converting <i>aNumeric</i> to a <code>Float</code>.
677  *
678  * 1.2.coerce(3) #=> [3.0, 1.2]
679  * 2.5.coerce(1.1) #=> [1.1, 2.5]
680  */
681 
682 static VALUE
684 {
685  return rb_assoc_new(rb_Float(y), x);
686 }
687 
688 /*
689  * call-seq:
690  * -float -> float
691  *
692  * Returns float, negated.
693  */
694 
695 static VALUE
697 {
698  return DBL2NUM(-RFLOAT_VALUE(flt));
699 }
700 
701 /*
702  * call-seq:
703  * float + other -> float
704  *
705  * Returns a new float which is the sum of <code>float</code>
706  * and <code>other</code>.
707  */
708 
709 static VALUE
711 {
712  switch (TYPE(y)) {
713  case T_FIXNUM:
714  return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
715  case T_BIGNUM:
716  return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
717  case T_FLOAT:
718  return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
719  default:
720  return rb_num_coerce_bin(x, y, '+');
721  }
722 }
723 
724 /*
725  * call-seq:
726  * float - other -> float
727  *
728  * Returns a new float which is the difference of <code>float</code>
729  * and <code>other</code>.
730  */
731 
732 static VALUE
734 {
735  switch (TYPE(y)) {
736  case T_FIXNUM:
737  return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
738  case T_BIGNUM:
739  return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
740  case T_FLOAT:
741  return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
742  default:
743  return rb_num_coerce_bin(x, y, '-');
744  }
745 }
746 
747 /*
748  * call-seq:
749  * float * other -> float
750  *
751  * Returns a new float which is the product of <code>float</code>
752  * and <code>other</code>.
753  */
754 
755 static VALUE
757 {
758  switch (TYPE(y)) {
759  case T_FIXNUM:
760  return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
761  case T_BIGNUM:
762  return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
763  case T_FLOAT:
764  return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
765  default:
766  return rb_num_coerce_bin(x, y, '*');
767  }
768 }
769 
770 /*
771  * call-seq:
772  * float / other -> float
773  *
774  * Returns a new float which is the result of dividing
775  * <code>float</code> by <code>other</code>.
776  */
777 
778 static VALUE
780 {
781  long f_y;
782  double d;
783 
784  switch (TYPE(y)) {
785  case T_FIXNUM:
786  f_y = FIX2LONG(y);
787  return DBL2NUM(RFLOAT_VALUE(x) / (double)f_y);
788  case T_BIGNUM:
789  d = rb_big2dbl(y);
790  return DBL2NUM(RFLOAT_VALUE(x) / d);
791  case T_FLOAT:
792  return DBL2NUM(RFLOAT_VALUE(x) / RFLOAT_VALUE(y));
793  default:
794  return rb_num_coerce_bin(x, y, '/');
795  }
796 }
797 
798 /*
799  * call-seq:
800  * float.quo(numeric) -> float
801  *
802  * Returns float / numeric.
803  */
804 
805 static VALUE
807 {
808  return rb_funcall(x, '/', 1, y);
809 }
810 
811 static void
812 flodivmod(double x, double y, double *divp, double *modp)
813 {
814  double div, mod;
815 
816  if (y == 0.0) rb_num_zerodiv();
817  if((x == 0.0) || (isinf(y) && !isinf(x)))
818  mod = x;
819  else {
820 #ifdef HAVE_FMOD
821  mod = fmod(x, y);
822 #else
823  double z;
824 
825  modf(x/y, &z);
826  mod = x - z * y;
827 #endif
828  }
829  if (isinf(x) && !isinf(y) && !isnan(y))
830  div = x;
831  else
832  div = (x - mod) / y;
833  if (y*mod < 0) {
834  mod += y;
835  div -= 1.0;
836  }
837  if (modp) *modp = mod;
838  if (divp) *divp = div;
839 }
840 
841 /*
842  * Returns the modulo of division of x by y.
843  * An error will be raised if y == 0.
844  */
845 
846 double ruby_float_mod(double x, double y) {
847  double mod;
848  flodivmod(x, y, 0, &mod);
849  return mod;
850 }
851 
852 
853 /*
854  * call-seq:
855  * flt % other -> float
856  * flt.modulo(other) -> float
857  *
858  * Return the modulo after division of <code>flt</code> by <code>other</code>.
859  *
860  * 6543.21.modulo(137) #=> 104.21
861  * 6543.21.modulo(137.24) #=> 92.9299999999996
862  */
863 
864 static VALUE
866 {
867  double fy;
868 
869  switch (TYPE(y)) {
870  case T_FIXNUM:
871  fy = (double)FIX2LONG(y);
872  break;
873  case T_BIGNUM:
874  fy = rb_big2dbl(y);
875  break;
876  case T_FLOAT:
877  fy = RFLOAT_VALUE(y);
878  break;
879  default:
880  return rb_num_coerce_bin(x, y, '%');
881  }
882  return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
883 }
884 
885 static VALUE
886 dbl2ival(double d)
887 {
888  d = round(d);
889  if (FIXABLE(d)) {
890  return LONG2FIX((long)d);
891  }
892  return rb_dbl2big(d);
893 }
894 
895 /*
896  * call-seq:
897  * flt.divmod(numeric) -> array
898  *
899  * See <code>Numeric#divmod</code>.
900  */
901 
902 static VALUE
904 {
905  double fy, div, mod;
906  volatile VALUE a, b;
907 
908  switch (TYPE(y)) {
909  case T_FIXNUM:
910  fy = (double)FIX2LONG(y);
911  break;
912  case T_BIGNUM:
913  fy = rb_big2dbl(y);
914  break;
915  case T_FLOAT:
916  fy = RFLOAT_VALUE(y);
917  break;
918  default:
919  return rb_num_coerce_bin(x, y, rb_intern("divmod"));
920  }
921  flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
922  a = dbl2ival(div);
923  b = DBL2NUM(mod);
924  return rb_assoc_new(a, b);
925 }
926 
927 /*
928  * call-seq:
929  *
930  * flt ** other -> float
931  *
932  * Raises <code>float</code> the <code>other</code> power.
933  *
934  * 2.0**3 #=> 8.0
935  */
936 
937 static VALUE
939 {
940  switch (TYPE(y)) {
941  case T_FIXNUM:
942  return DBL2NUM(pow(RFLOAT_VALUE(x), (double)FIX2LONG(y)));
943  case T_BIGNUM:
944  return DBL2NUM(pow(RFLOAT_VALUE(x), rb_big2dbl(y)));
945  case T_FLOAT:
946  {
947  double dx = RFLOAT_VALUE(x);
948  double dy = RFLOAT_VALUE(y);
949  if (dx < 0 && dy != round(dy))
950  return rb_funcall(rb_complex_raw1(x), rb_intern("**"), 1, y);
951  return DBL2NUM(pow(dx, dy));
952  }
953  default:
954  return rb_num_coerce_bin(x, y, rb_intern("**"));
955  }
956 }
957 
958 /*
959  * call-seq:
960  * num.eql?(numeric) -> true or false
961  *
962  * Returns <code>true</code> if <i>num</i> and <i>numeric</i> are the
963  * same type and have equal values.
964  *
965  * 1 == 1.0 #=> true
966  * 1.eql?(1.0) #=> false
967  * (1.0).eql?(1.0) #=> true
968  */
969 
970 static VALUE
972 {
973  if (TYPE(x) != TYPE(y)) return Qfalse;
974 
975  return rb_equal(x, y);
976 }
977 
978 /*
979  * call-seq:
980  * num <=> other -> 0 or nil
981  *
982  * Returns zero if <i>num</i> equals <i>other</i>, <code>nil</code>
983  * otherwise.
984  */
985 
986 static VALUE
988 {
989  if (x == y) return INT2FIX(0);
990  return Qnil;
991 }
992 
993 static VALUE
995 {
996  if (x == y) return Qtrue;
997  return rb_funcall(y, id_eq, 1, x);
998 }
999 
1000 /*
1001  * call-seq:
1002  * flt == obj -> true or false
1003  *
1004  * Returns <code>true</code> only if <i>obj</i> has the same value
1005  * as <i>flt</i>. Contrast this with <code>Float#eql?</code>, which
1006  * requires <i>obj</i> to be a <code>Float</code>.
1007  *
1008  * 1.0 == 1 #=> true
1009  *
1010  */
1011 
1012 static VALUE
1014 {
1015  volatile double a, b;
1016 
1017  switch (TYPE(y)) {
1018  case T_FIXNUM:
1019  b = (double)FIX2LONG(y);
1020  break;
1021  case T_BIGNUM:
1022  b = rb_big2dbl(y);
1023  break;
1024  case T_FLOAT:
1025  b = RFLOAT_VALUE(y);
1026 #if defined(_MSC_VER) && _MSC_VER < 1300
1027  if (isnan(b)) return Qfalse;
1028 #endif
1029  break;
1030  default:
1031  return num_equal(x, y);
1032  }
1033  a = RFLOAT_VALUE(x);
1034 #if defined(_MSC_VER) && _MSC_VER < 1300
1035  if (isnan(a)) return Qfalse;
1036 #endif
1037  return (a == b)?Qtrue:Qfalse;
1038 }
1039 
1040 /*
1041  * call-seq:
1042  * flt.hash -> integer
1043  *
1044  * Returns a hash code for this float.
1045  */
1046 
1047 static VALUE
1049 {
1050  double d;
1051  st_index_t hash;
1052 
1053  d = RFLOAT_VALUE(num);
1054  /* normalize -0.0 to 0.0 */
1055  if (d == 0.0) d = 0.0;
1056  hash = rb_memhash(&d, sizeof(d));
1057  return LONG2FIX(hash);
1058 }
1059 
1060 VALUE
1061 rb_dbl_cmp(double a, double b)
1062 {
1063  if (isnan(a) || isnan(b)) return Qnil;
1064  if (a == b) return INT2FIX(0);
1065  if (a > b) return INT2FIX(1);
1066  if (a < b) return INT2FIX(-1);
1067  return Qnil;
1068 }
1069 
1070 /*
1071  * call-seq:
1072  * flt <=> real -> -1, 0, +1 or nil
1073  *
1074  * Returns -1, 0, +1 or nil depending on whether <i>flt</i> is less
1075  * than, equal to, or greater than <i>real</i>. This is the basis for
1076  * the tests in <code>Comparable</code>.
1077  */
1078 
1079 static VALUE
1081 {
1082  double a, b;
1083  VALUE i;
1084 
1085  a = RFLOAT_VALUE(x);
1086  if (isnan(a)) return Qnil;
1087  switch (TYPE(y)) {
1088  case T_FIXNUM:
1089  b = (double)FIX2LONG(y);
1090  break;
1091 
1092  case T_BIGNUM:
1093  if (isinf(a)) {
1094  if (a > 0.0) return INT2FIX(1);
1095  else return INT2FIX(-1);
1096  }
1097  b = rb_big2dbl(y);
1098  break;
1099 
1100  case T_FLOAT:
1101  b = RFLOAT_VALUE(y);
1102  break;
1103 
1104  default:
1105  if (isinf(a) && (i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0)) != Qundef) {
1106  if (RTEST(i)) {
1107  int j = rb_cmpint(i, x, y);
1108  j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1109  return INT2FIX(j);
1110  }
1111  if (a > 0.0) return INT2FIX(1);
1112  return INT2FIX(-1);
1113  }
1114  return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
1115  }
1116  return rb_dbl_cmp(a, b);
1117 }
1118 
1119 /*
1120  * call-seq:
1121  * flt > real -> true or false
1122  *
1123  * <code>true</code> if <code>flt</code> is greater than <code>real</code>.
1124  */
1125 
1126 static VALUE
1128 {
1129  double a, b;
1130 
1131  a = RFLOAT_VALUE(x);
1132  switch (TYPE(y)) {
1133  case T_FIXNUM:
1134  b = (double)FIX2LONG(y);
1135  break;
1136 
1137  case T_BIGNUM:
1138  b = rb_big2dbl(y);
1139  break;
1140 
1141  case T_FLOAT:
1142  b = RFLOAT_VALUE(y);
1143 #if defined(_MSC_VER) && _MSC_VER < 1300
1144  if (isnan(b)) return Qfalse;
1145 #endif
1146  break;
1147 
1148  default:
1149  return rb_num_coerce_relop(x, y, '>');
1150  }
1151 #if defined(_MSC_VER) && _MSC_VER < 1300
1152  if (isnan(a)) return Qfalse;
1153 #endif
1154  return (a > b)?Qtrue:Qfalse;
1155 }
1156 
1157 /*
1158  * call-seq:
1159  * flt >= real -> true or false
1160  *
1161  * <code>true</code> if <code>flt</code> is greater than
1162  * or equal to <code>real</code>.
1163  */
1164 
1165 static VALUE
1167 {
1168  double a, b;
1169 
1170  a = RFLOAT_VALUE(x);
1171  switch (TYPE(y)) {
1172  case T_FIXNUM:
1173  b = (double)FIX2LONG(y);
1174  break;
1175 
1176  case T_BIGNUM:
1177  b = rb_big2dbl(y);
1178  break;
1179 
1180  case T_FLOAT:
1181  b = RFLOAT_VALUE(y);
1182 #if defined(_MSC_VER) && _MSC_VER < 1300
1183  if (isnan(b)) return Qfalse;
1184 #endif
1185  break;
1186 
1187  default:
1188  return rb_num_coerce_relop(x, y, rb_intern(">="));
1189  }
1190 #if defined(_MSC_VER) && _MSC_VER < 1300
1191  if (isnan(a)) return Qfalse;
1192 #endif
1193  return (a >= b)?Qtrue:Qfalse;
1194 }
1195 
1196 /*
1197  * call-seq:
1198  * flt < real -> true or false
1199  *
1200  * <code>true</code> if <code>flt</code> is less than <code>real</code>.
1201  */
1202 
1203 static VALUE
1205 {
1206  double a, b;
1207 
1208  a = RFLOAT_VALUE(x);
1209  switch (TYPE(y)) {
1210  case T_FIXNUM:
1211  b = (double)FIX2LONG(y);
1212  break;
1213 
1214  case T_BIGNUM:
1215  b = rb_big2dbl(y);
1216  break;
1217 
1218  case T_FLOAT:
1219  b = RFLOAT_VALUE(y);
1220 #if defined(_MSC_VER) && _MSC_VER < 1300
1221  if (isnan(b)) return Qfalse;
1222 #endif
1223  break;
1224 
1225  default:
1226  return rb_num_coerce_relop(x, y, '<');
1227  }
1228 #if defined(_MSC_VER) && _MSC_VER < 1300
1229  if (isnan(a)) return Qfalse;
1230 #endif
1231  return (a < b)?Qtrue:Qfalse;
1232 }
1233 
1234 /*
1235  * call-seq:
1236  * flt <= real -> true or false
1237  *
1238  * <code>true</code> if <code>flt</code> is less than
1239  * or equal to <code>real</code>.
1240  */
1241 
1242 static VALUE
1244 {
1245  double a, b;
1246 
1247  a = RFLOAT_VALUE(x);
1248  switch (TYPE(y)) {
1249  case T_FIXNUM:
1250  b = (double)FIX2LONG(y);
1251  break;
1252 
1253  case T_BIGNUM:
1254  b = rb_big2dbl(y);
1255  break;
1256 
1257  case T_FLOAT:
1258  b = RFLOAT_VALUE(y);
1259 #if defined(_MSC_VER) && _MSC_VER < 1300
1260  if (isnan(b)) return Qfalse;
1261 #endif
1262  break;
1263 
1264  default:
1265  return rb_num_coerce_relop(x, y, rb_intern("<="));
1266  }
1267 #if defined(_MSC_VER) && _MSC_VER < 1300
1268  if (isnan(a)) return Qfalse;
1269 #endif
1270  return (a <= b)?Qtrue:Qfalse;
1271 }
1272 
1273 /*
1274  * call-seq:
1275  * flt.eql?(obj) -> true or false
1276  *
1277  * Returns <code>true</code> only if <i>obj</i> is a
1278  * <code>Float</code> with the same value as <i>flt</i>. Contrast this
1279  * with <code>Float#==</code>, which performs type conversions.
1280  *
1281  * 1.0.eql?(1) #=> false
1282  */
1283 
1284 static VALUE
1286 {
1287  if (TYPE(y) == T_FLOAT) {
1288  double a = RFLOAT_VALUE(x);
1289  double b = RFLOAT_VALUE(y);
1290 #if defined(_MSC_VER) && _MSC_VER < 1300
1291  if (isnan(a) || isnan(b)) return Qfalse;
1292 #endif
1293  if (a == b)
1294  return Qtrue;
1295  }
1296  return Qfalse;
1297 }
1298 
1299 /*
1300  * call-seq:
1301  * flt.to_f -> self
1302  *
1303  * As <code>flt</code> is already a float, returns +self+.
1304  */
1305 
1306 static VALUE
1308 {
1309  return num;
1310 }
1311 
1312 /*
1313  * call-seq:
1314  * flt.abs -> float
1315  * flt.magnitude -> float
1316  *
1317  * Returns the absolute value of <i>flt</i>.
1318  *
1319  * (-34.56).abs #=> 34.56
1320  * -34.56.abs #=> 34.56
1321  *
1322  */
1323 
1324 static VALUE
1326 {
1327  double val = fabs(RFLOAT_VALUE(flt));
1328  return DBL2NUM(val);
1329 }
1330 
1331 /*
1332  * call-seq:
1333  * flt.zero? -> true or false
1334  *
1335  * Returns <code>true</code> if <i>flt</i> is 0.0.
1336  *
1337  */
1338 
1339 static VALUE
1341 {
1342  if (RFLOAT_VALUE(num) == 0.0) {
1343  return Qtrue;
1344  }
1345  return Qfalse;
1346 }
1347 
1348 /*
1349  * call-seq:
1350  * flt.nan? -> true or false
1351  *
1352  * Returns <code>true</code> if <i>flt</i> is an invalid IEEE floating
1353  * point number.
1354  *
1355  * a = -1.0 #=> -1.0
1356  * a.nan? #=> false
1357  * a = 0.0/0.0 #=> NaN
1358  * a.nan? #=> true
1359  */
1360 
1361 static VALUE
1363 {
1364  double value = RFLOAT_VALUE(num);
1365 
1366  return isnan(value) ? Qtrue : Qfalse;
1367 }
1368 
1369 /*
1370  * call-seq:
1371  * flt.infinite? -> nil, -1, +1
1372  *
1373  * Returns <code>nil</code>, -1, or +1 depending on whether <i>flt</i>
1374  * is finite, -infinity, or +infinity.
1375  *
1376  * (0.0).infinite? #=> nil
1377  * (-1.0/0.0).infinite? #=> -1
1378  * (+1.0/0.0).infinite? #=> 1
1379  */
1380 
1381 static VALUE
1383 {
1384  double value = RFLOAT_VALUE(num);
1385 
1386  if (isinf(value)) {
1387  return INT2FIX( value < 0 ? -1 : 1 );
1388  }
1389 
1390  return Qnil;
1391 }
1392 
1393 /*
1394  * call-seq:
1395  * flt.finite? -> true or false
1396  *
1397  * Returns <code>true</code> if <i>flt</i> is a valid IEEE floating
1398  * point number (it is not infinite, and <code>nan?</code> is
1399  * <code>false</code>).
1400  *
1401  */
1402 
1403 static VALUE
1405 {
1406  double value = RFLOAT_VALUE(num);
1407 
1408 #if HAVE_FINITE
1409  if (!finite(value))
1410  return Qfalse;
1411 #else
1412  if (isinf(value) || isnan(value))
1413  return Qfalse;
1414 #endif
1415 
1416  return Qtrue;
1417 }
1418 
1419 /*
1420  * call-seq:
1421  * flt.floor -> integer
1422  *
1423  * Returns the largest integer less than or equal to <i>flt</i>.
1424  *
1425  * 1.2.floor #=> 1
1426  * 2.0.floor #=> 2
1427  * (-1.2).floor #=> -2
1428  * (-2.0).floor #=> -2
1429  */
1430 
1431 static VALUE
1433 {
1434  double f = floor(RFLOAT_VALUE(num));
1435  long val;
1436 
1437  if (!FIXABLE(f)) {
1438  return rb_dbl2big(f);
1439  }
1440  val = (long)f;
1441  return LONG2FIX(val);
1442 }
1443 
1444 /*
1445  * call-seq:
1446  * flt.ceil -> integer
1447  *
1448  * Returns the smallest <code>Integer</code> greater than or equal to
1449  * <i>flt</i>.
1450  *
1451  * 1.2.ceil #=> 2
1452  * 2.0.ceil #=> 2
1453  * (-1.2).ceil #=> -1
1454  * (-2.0).ceil #=> -2
1455  */
1456 
1457 static VALUE
1459 {
1460  double f = ceil(RFLOAT_VALUE(num));
1461  long val;
1462 
1463  if (!FIXABLE(f)) {
1464  return rb_dbl2big(f);
1465  }
1466  val = (long)f;
1467  return LONG2FIX(val);
1468 }
1469 
1470 /*
1471  * Assumes num is an Integer, ndigits <= 0
1472  */
1473 static VALUE
1474 int_round_0(VALUE num, int ndigits)
1475 {
1476  VALUE n, f, h, r;
1477  long bytes;
1478  ID op;
1479  /* If 10**N / 2 > num, then return 0 */
1480  /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
1481  bytes = FIXNUM_P(num) ? sizeof(long) : rb_funcall(num, rb_intern("size"), 0);
1482  if (-0.415241 * ndigits - 0.125 > bytes ) {
1483  return INT2FIX(0);
1484  }
1485 
1486  f = int_pow(10, -ndigits);
1487  if (FIXNUM_P(num) && FIXNUM_P(f)) {
1488  SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
1489  int neg = x < 0;
1490  if (neg) x = -x;
1491  x = (x + y / 2) / y * y;
1492  if (neg) x = -x;
1493  return LONG2NUM(x);
1494  }
1495  if (TYPE(f) == T_FLOAT) {
1496  /* then int_pow overflow */
1497  return INT2FIX(0);
1498  }
1499  h = rb_funcall(f, '/', 1, INT2FIX(2));
1500  r = rb_funcall(num, '%', 1, f);
1501  n = rb_funcall(num, '-', 1, r);
1502  op = RTEST(rb_funcall(num, '<', 1, INT2FIX(0))) ? rb_intern("<=") : '<';
1503  if (!RTEST(rb_funcall(r, op, 1, h))) {
1504  n = rb_funcall(n, '+', 1, f);
1505  }
1506  return n;
1507 }
1508 
1509 static VALUE
1510 flo_truncate(VALUE num);
1511 
1512 /*
1513  * call-seq:
1514  * flt.round([ndigits]) -> integer or float
1515  *
1516  * Rounds <i>flt</i> to a given precision in decimal digits (default 0 digits).
1517  * Precision may be negative. Returns a floating point number when ndigits
1518  * is more than zero.
1519  *
1520  * 1.4.round #=> 1
1521  * 1.5.round #=> 2
1522  * 1.6.round #=> 2
1523  * (-1.5).round #=> -2
1524  *
1525  * 1.234567.round(2) #=> 1.23
1526  * 1.234567.round(3) #=> 1.235
1527  * 1.234567.round(4) #=> 1.2346
1528  * 1.234567.round(5) #=> 1.23457
1529  *
1530  * 34567.89.round(-5) #=> 0
1531  * 34567.89.round(-4) #=> 30000
1532  * 34567.89.round(-3) #=> 35000
1533  * 34567.89.round(-2) #=> 34600
1534  * 34567.89.round(-1) #=> 34570
1535  * 34567.89.round(0) #=> 34568
1536  * 34567.89.round(1) #=> 34567.9
1537  * 34567.89.round(2) #=> 34567.89
1538  * 34567.89.round(3) #=> 34567.89
1539  *
1540  */
1541 
1542 static VALUE
1544 {
1545  VALUE nd;
1546  double number, f;
1547  int ndigits = 0;
1548  int binexp;
1549  enum {float_dig = DBL_DIG+2};
1550 
1551  if (argc > 0 && rb_scan_args(argc, argv, "01", &nd) == 1) {
1552  ndigits = NUM2INT(nd);
1553  }
1554  if (ndigits < 0) {
1555  return int_round_0(flo_truncate(num), ndigits);
1556  }
1557  number = RFLOAT_VALUE(num);
1558  if (ndigits == 0) {
1559  return dbl2ival(number);
1560  }
1561  frexp(number, &binexp);
1562 
1563 /* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
1564  i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
1565  Recall that up to float_dig digits can be needed to represent a double,
1566  so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
1567  will be an integer and thus the result is the original number.
1568  If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
1569  if ndigits + exp < 0, the result is 0.
1570  We have:
1571  2 ** (binexp-1) <= |number| < 2 ** binexp
1572  10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
1573  If binexp >= 0, and since log_2(10) = 3.322259:
1574  10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
1575  floor(binexp/4) <= exp <= ceil(binexp/3)
1576  If binexp <= 0, swap the /4 and the /3
1577  So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
1578  If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
1579 */
1580  if (isinf(number) || isnan(number) ||
1581  (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1))) {
1582  return num;
1583  }
1584  if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
1585  return DBL2NUM(0);
1586  }
1587  f = pow(10, ndigits);
1588  return DBL2NUM(round(number * f) / f);
1589 }
1590 
1591 /*
1592  * call-seq:
1593  * flt.to_i -> integer
1594  * flt.to_int -> integer
1595  * flt.truncate -> integer
1596  *
1597  * Returns <i>flt</i> truncated to an <code>Integer</code>.
1598  */
1599 
1600 static VALUE
1602 {
1603  double f = RFLOAT_VALUE(num);
1604  long val;
1605 
1606  if (f > 0.0) f = floor(f);
1607  if (f < 0.0) f = ceil(f);
1608 
1609  if (!FIXABLE(f)) {
1610  return rb_dbl2big(f);
1611  }
1612  val = (long)f;
1613  return LONG2FIX(val);
1614 }
1615 
1616 /*
1617  * call-seq:
1618  * num.floor -> integer
1619  *
1620  * Returns the largest integer less than or equal to <i>num</i>.
1621  * <code>Numeric</code> implements this by converting <i>anInteger</i>
1622  * to a <code>Float</code> and invoking <code>Float#floor</code>.
1623  *
1624  * 1.floor #=> 1
1625  * (-1).floor #=> -1
1626  */
1627 
1628 static VALUE
1630 {
1631  return flo_floor(rb_Float(num));
1632 }
1633 
1634 
1635 /*
1636  * call-seq:
1637  * num.ceil -> integer
1638  *
1639  * Returns the smallest <code>Integer</code> greater than or equal to
1640  * <i>num</i>. Class <code>Numeric</code> achieves this by converting
1641  * itself to a <code>Float</code> then invoking
1642  * <code>Float#ceil</code>.
1643  *
1644  * 1.ceil #=> 1
1645  * 1.2.ceil #=> 2
1646  * (-1.2).ceil #=> -1
1647  * (-1.0).ceil #=> -1
1648  */
1649 
1650 static VALUE
1652 {
1653  return flo_ceil(rb_Float(num));
1654 }
1655 
1656 /*
1657  * call-seq:
1658  * num.round([ndigits]) -> integer or float
1659  *
1660  * Rounds <i>num</i> to a given precision in decimal digits (default 0 digits).
1661  * Precision may be negative. Returns a floating point number when <i>ndigits</i>
1662  * is more than zero. <code>Numeric</code> implements this by converting itself
1663  * to a <code>Float</code> and invoking <code>Float#round</code>.
1664  */
1665 
1666 static VALUE
1668 {
1669  return flo_round(argc, argv, rb_Float(num));
1670 }
1671 
1672 /*
1673  * call-seq:
1674  * num.truncate -> integer
1675  *
1676  * Returns <i>num</i> truncated to an integer. <code>Numeric</code>
1677  * implements this by converting its value to a float and invoking
1678  * <code>Float#truncate</code>.
1679  */
1680 
1681 static VALUE
1683 {
1684  return flo_truncate(rb_Float(num));
1685 }
1686 
1687 
1688 int
1689 ruby_float_step(VALUE from, VALUE to, VALUE step, int excl)
1690 {
1691  if (TYPE(from) == T_FLOAT || TYPE(to) == T_FLOAT || TYPE(step) == T_FLOAT) {
1692  const double epsilon = DBL_EPSILON;
1693  double beg = NUM2DBL(from);
1694  double end = NUM2DBL(to);
1695  double unit = NUM2DBL(step);
1696  double n = (end - beg)/unit;
1697  double err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
1698  long i;
1699 
1700  if (isinf(unit)) {
1701  if (unit > 0 ? beg <= end : beg >= end) rb_yield(DBL2NUM(beg));
1702  }
1703  else {
1704  if (err>0.5) err=0.5;
1705  n = floor(n + err);
1706  if (!excl || ((long)n)*unit+beg < end) n++;
1707  for (i=0; i<n; i++) {
1708  rb_yield(DBL2NUM(i*unit+beg));
1709  }
1710  }
1711  return TRUE;
1712  }
1713  return FALSE;
1714 }
1715 
1716 /*
1717  * call-seq:
1718  * num.step(limit[, step]) {|i| block } -> self
1719  * num.step(limit[, step]) -> an_enumerator
1720  *
1721  * Invokes <em>block</em> with the sequence of numbers starting at
1722  * <i>num</i>, incremented by <i>step</i> (default 1) on each
1723  * call. The loop finishes when the value to be passed to the block
1724  * is greater than <i>limit</i> (if <i>step</i> is positive) or less
1725  * than <i>limit</i> (if <i>step</i> is negative). If all the
1726  * arguments are integers, the loop operates using an integer
1727  * counter. If any of the arguments are floating point numbers, all
1728  * are converted to floats, and the loop is executed <i>floor(n +
1729  * n*epsilon)+ 1</i> times, where <i>n = (limit -
1730  * num)/step</i>. Otherwise, the loop starts at <i>num</i>, uses
1731  * either the <code><</code> or <code>></code> operator to compare
1732  * the counter against <i>limit</i>, and increments itself using the
1733  * <code>+</code> operator.
1734  *
1735  * If no block is given, an enumerator is returned instead.
1736  *
1737  * 1.step(10, 2) { |i| print i, " " }
1738  * Math::E.step(Math::PI, 0.2) { |f| print f, " " }
1739  *
1740  * <em>produces:</em>
1741  *
1742  * 1 3 5 7 9
1743  * 2.71828182845905 2.91828182845905 3.11828182845905
1744  */
1745 
1746 static VALUE
1748 {
1749  VALUE to, step;
1750 
1751  RETURN_ENUMERATOR(from, argc, argv);
1752  if (argc == 1) {
1753  to = argv[0];
1754  step = INT2FIX(1);
1755  }
1756  else {
1757  if (argc == 2) {
1758  to = argv[0];
1759  step = argv[1];
1760  }
1761  else {
1762  rb_raise(rb_eArgError, "wrong number of arguments (%d for 1..2)", argc);
1763  }
1764  if (rb_equal(step, INT2FIX(0))) {
1765  rb_raise(rb_eArgError, "step can't be 0");
1766  }
1767  }
1768 
1769  if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
1770  long i, end, diff;
1771 
1772  i = FIX2LONG(from);
1773  end = FIX2LONG(to);
1774  diff = FIX2LONG(step);
1775 
1776  if (diff > 0) {
1777  while (i <= end) {
1778  rb_yield(LONG2FIX(i));
1779  i += diff;
1780  }
1781  }
1782  else {
1783  while (i >= end) {
1784  rb_yield(LONG2FIX(i));
1785  i += diff;
1786  }
1787  }
1788  }
1789  else if (!ruby_float_step(from, to, step, FALSE)) {
1790  VALUE i = from;
1791  ID cmp;
1792 
1793  if (RTEST(rb_funcall(step, '>', 1, INT2FIX(0)))) {
1794  cmp = '>';
1795  }
1796  else {
1797  cmp = '<';
1798  }
1799  for (;;) {
1800  if (RTEST(rb_funcall(i, cmp, 1, to))) break;
1801  rb_yield(i);
1802  i = rb_funcall(i, '+', 1, step);
1803  }
1804  }
1805  return from;
1806 }
1807 
1808 #define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
1809 #define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
1810 #define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
1811 
1814 {
1815  again:
1816  if (NIL_P(val)) {
1817  rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
1818  }
1819 
1820  if (FIXNUM_P(val)) return FIX2LONG(val);
1821 
1822  switch (TYPE(val)) {
1823  case T_FLOAT:
1824  if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
1825  && RFLOAT_VALUE(val) > LONG_MIN_MINUS_ONE) {
1826  return (SIGNED_VALUE)(RFLOAT_VALUE(val));
1827  }
1828  else {
1829  char buf[24];
1830  char *s;
1831 
1832  snprintf(buf, sizeof(buf), "%-.10g", RFLOAT_VALUE(val));
1833  if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1834  rb_raise(rb_eRangeError, "float %s out of range of integer", buf);
1835  }
1836 
1837  case T_BIGNUM:
1838  return rb_big2long(val);
1839 
1840  default:
1841  val = rb_to_int(val);
1842  goto again;
1843  }
1844 }
1845 
1846 VALUE
1848 {
1849  again:
1850  if (NIL_P(val)) {
1851  rb_raise(rb_eTypeError, "no implicit conversion from nil to integer");
1852  }
1853 
1854  if (FIXNUM_P(val)) return FIX2LONG(val); /* this is FIX2LONG, inteneded */
1855 
1856  switch (TYPE(val)) {
1857  case T_FLOAT:
1858  if (RFLOAT_VALUE(val) < ULONG_MAX_PLUS_ONE
1859  && RFLOAT_VALUE(val) > LONG_MIN_MINUS_ONE) {
1860  return (VALUE)RFLOAT_VALUE(val);
1861  }
1862  else {
1863  char buf[24];
1864  char *s;
1865 
1866  snprintf(buf, sizeof(buf), "%-.10g", RFLOAT_VALUE(val));
1867  if ((s = strchr(buf, ' ')) != 0) *s = '\0';
1868  rb_raise(rb_eRangeError, "float %s out of range of integer", buf);
1869  }
1870 
1871  case T_BIGNUM:
1872  return rb_big2ulong(val);
1873 
1874  default:
1875  val = rb_to_int(val);
1876  goto again;
1877  }
1878 }
1879 
1880 #if SIZEOF_INT < SIZEOF_VALUE
1881 void
1882 rb_out_of_int(SIGNED_VALUE num)
1883 {
1884  rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to `int'",
1885  num, num < 0 ? "small" : "big");
1886 }
1887 
1888 static void
1889 check_int(SIGNED_VALUE num)
1890 {
1891  if ((SIGNED_VALUE)(int)num != num) {
1892  rb_out_of_int(num);
1893  }
1894 }
1895 
1896 static void
1897 check_uint(VALUE num, VALUE sign)
1898 {
1899  static const VALUE mask = ~(VALUE)UINT_MAX;
1900 
1901  if (RTEST(sign)) {
1902  /* minus */
1903  if ((num & mask) != mask || (num & ~mask) <= INT_MAX + 1UL)
1904 #define VALUE_MSBMASK ((VALUE)1 << ((sizeof(VALUE) * CHAR_BIT) - 1))
1905  rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too small to convert to `unsigned int'", num|VALUE_MSBMASK);
1906  }
1907  else {
1908  /* plus */
1909  if ((num & mask) != 0)
1910  rb_raise(rb_eRangeError, "integer %"PRIuVALUE " too big to convert to `unsigned int'", num);
1911  }
1912 }
1913 
1914 long
1915 rb_num2int(VALUE val)
1916 {
1917  long num = rb_num2long(val);
1918 
1919  check_int(num);
1920  return num;
1921 }
1922 
1923 long
1924 rb_fix2int(VALUE val)
1925 {
1926  long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
1927 
1928  check_int(num);
1929  return num;
1930 }
1931 
1932 unsigned long
1933 rb_num2uint(VALUE val)
1934 {
1935  VALUE num = rb_num2ulong(val);
1936 
1937  check_uint(num, rb_funcall(val, '<', 1, INT2FIX(0)));
1938  return (unsigned long)num;
1939 }
1940 
1941 unsigned long
1942 rb_fix2uint(VALUE val)
1943 {
1944  unsigned long num;
1945 
1946  if (!FIXNUM_P(val)) {
1947  return rb_num2uint(val);
1948  }
1949  num = FIX2ULONG(val);
1950 
1951  check_uint(num, rb_funcall(val, '<', 1, INT2FIX(0)));
1952  return num;
1953 }
1954 #else
1955 long
1957 {
1958  return rb_num2long(val);
1959 }
1960 
1961 long
1963 {
1964  return FIX2INT(val);
1965 }
1966 #endif
1967 
1968 VALUE
1970 {
1971  SIGNED_VALUE v;
1972 
1973  if (FIXNUM_P(val)) return val;
1974 
1975  v = rb_num2long(val);
1976  if (!FIXABLE(v))
1977  rb_raise(rb_eRangeError, "integer %"PRIdVALUE " out of range of fixnum", v);
1978  return LONG2FIX(v);
1979 }
1980 
1981 #if HAVE_LONG_LONG
1982 
1983 #define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
1984 #define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
1985 #define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
1986 #ifndef ULLONG_MAX
1987 #define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
1988 #endif
1989 
1990 LONG_LONG
1991 rb_num2ll(VALUE val)
1992 {
1993  if (NIL_P(val)) {
1994  rb_raise(rb_eTypeError, "no implicit conversion from nil");
1995  }
1996 
1997  if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
1998 
1999  switch (TYPE(val)) {
2000  case T_FLOAT:
2001  if (RFLOAT_VALUE(val) < LLONG_MAX_PLUS_ONE
2002  && RFLOAT_VALUE(val) > LLONG_MIN_MINUS_ONE) {
2003  return (LONG_LONG)(RFLOAT_VALUE(val));
2004  }
2005  else {
2006  char buf[24];
2007  char *s;
2008 
2009  snprintf(buf, sizeof(buf), "%-.10g", RFLOAT_VALUE(val));
2010  if ((s = strchr(buf, ' ')) != 0) *s = '\0';
2011  rb_raise(rb_eRangeError, "float %s out of range of long long", buf);
2012  }
2013 
2014  case T_BIGNUM:
2015  return rb_big2ll(val);
2016 
2017  case T_STRING:
2018  rb_raise(rb_eTypeError, "no implicit conversion from string");
2019  return Qnil; /* not reached */
2020 
2021  case T_TRUE:
2022  case T_FALSE:
2023  rb_raise(rb_eTypeError, "no implicit conversion from boolean");
2024  return Qnil; /* not reached */
2025 
2026  default:
2027  val = rb_to_int(val);
2028  return NUM2LL(val);
2029  }
2030 }
2031 
2032 unsigned LONG_LONG
2033 rb_num2ull(VALUE val)
2034 {
2035  switch (TYPE(val)) {
2036  case T_NIL:
2037  rb_raise(rb_eTypeError, "no implicit conversion from nil");
2038 
2039  case T_FIXNUM:
2040  return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, inteneded */
2041 
2042  case T_FLOAT:
2043  if (RFLOAT_VALUE(val) < ULLONG_MAX_PLUS_ONE
2044  && RFLOAT_VALUE(val) > 0) {
2045  return (unsigned LONG_LONG)(RFLOAT_VALUE(val));
2046  }
2047  else {
2048  char buf[24];
2049  char *s;
2050 
2051  snprintf(buf, sizeof(buf), "%-.10g", RFLOAT_VALUE(val));
2052  if ((s = strchr(buf, ' ')) != 0) *s = '\0';
2053  rb_raise(rb_eRangeError, "float %s out of range of unsgined long long", buf);
2054  }
2055 
2056  case T_BIGNUM:
2057  return rb_big2ull(val);
2058 
2059  case T_STRING:
2060  rb_raise(rb_eTypeError, "no implicit conversion from string");
2061  return Qnil; /* not reached */
2062 
2063  case T_TRUE:
2064  case T_FALSE:
2065  rb_raise(rb_eTypeError, "no implicit conversion from boolean");
2066  return Qnil; /* not reached */
2067 
2068  default:
2069  val = rb_to_int(val);
2070  return NUM2ULL(val);
2071  }
2072 }
2073 
2074 #endif /* HAVE_LONG_LONG */
2075 
2076 /*
2077  * Document-class: Integer
2078  *
2079  * <code>Integer</code> is the basis for the two concrete classes that
2080  * hold whole numbers, <code>Bignum</code> and <code>Fixnum</code>.
2081  *
2082  */
2083 
2084 /*
2085  * call-seq:
2086  * int.to_i -> integer
2087  * int.to_int -> integer
2088  * int.floor -> integer
2089  * int.ceil -> integer
2090  * int.truncate -> integer
2091  *
2092  * As <i>int</i> is already an <code>Integer</code>, all these
2093  * methods simply return the receiver.
2094  */
2095 
2096 static VALUE
2098 {
2099  return num;
2100 }
2101 
2102 /*
2103  * call-seq:
2104  * int.integer? -> true
2105  *
2106  * Always returns <code>true</code>.
2107  */
2108 
2109 static VALUE
2111 {
2112  return Qtrue;
2113 }
2114 
2115 /*
2116  * call-seq:
2117  * int.odd? -> true or false
2118  *
2119  * Returns <code>true</code> if <i>int</i> is an odd number.
2120  */
2121 
2122 static VALUE
2124 {
2125  if (rb_funcall(num, '%', 1, INT2FIX(2)) != INT2FIX(0)) {
2126  return Qtrue;
2127  }
2128  return Qfalse;
2129 }
2130 
2131 /*
2132  * call-seq:
2133  * int.even? -> true or false
2134  *
2135  * Returns <code>true</code> if <i>int</i> is an even number.
2136  */
2137 
2138 static VALUE
2140 {
2141  if (rb_funcall(num, '%', 1, INT2FIX(2)) == INT2FIX(0)) {
2142  return Qtrue;
2143  }
2144  return Qfalse;
2145 }
2146 
2147 /*
2148  * call-seq:
2149  * fixnum.next -> integer
2150  * fixnum.succ -> integer
2151  *
2152  * Returns the <code>Integer</code> equal to <i>int</i> + 1.
2153  *
2154  * 1.next #=> 2
2155  * (-1).next #=> 0
2156  */
2157 
2158 static VALUE
2160 {
2161  long i = FIX2LONG(num) + 1;
2162  return LONG2NUM(i);
2163 }
2164 
2165 /*
2166  * call-seq:
2167  * int.next -> integer
2168  * int.succ -> integer
2169  *
2170  * Returns the <code>Integer</code> equal to <i>int</i> + 1.
2171  *
2172  * 1.next #=> 2
2173  * (-1).next #=> 0
2174  */
2175 
2176 VALUE
2178 {
2179  if (FIXNUM_P(num)) {
2180  long i = FIX2LONG(num) + 1;
2181  return LONG2NUM(i);
2182  }
2183  return rb_funcall(num, '+', 1, INT2FIX(1));
2184 }
2185 
2186 #define int_succ rb_int_succ
2187 
2188 /*
2189  * call-seq:
2190  * int.pred -> integer
2191  *
2192  * Returns the <code>Integer</code> equal to <i>int</i> - 1.
2193  *
2194  * 1.pred #=> 0
2195  * (-1).pred #=> -2
2196  */
2197 
2198 VALUE
2200 {
2201  if (FIXNUM_P(num)) {
2202  long i = FIX2LONG(num) - 1;
2203  return LONG2NUM(i);
2204  }
2205  return rb_funcall(num, '-', 1, INT2FIX(1));
2206 }
2207 
2208 #define int_pred rb_int_pred
2209 
2210 VALUE
2211 rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
2212 {
2213  int n;
2214  VALUE str;
2215  switch (n = rb_enc_codelen(code, enc)) {
2217  rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
2218  break;
2220  case 0:
2221  rb_raise(rb_eRangeError, "%u out of char range", code);
2222  break;
2223  }
2224  str = rb_enc_str_new(0, n, enc);
2225  rb_enc_mbcput(code, RSTRING_PTR(str), enc);
2226  if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
2227  rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
2228  }
2229  return str;
2230 }
2231 
2232 /*
2233  * call-seq:
2234  * int.chr([encoding]) -> string
2235  *
2236  * Returns a string containing the character represented by the
2237  * receiver's value according to +encoding+.
2238  *
2239  * 65.chr #=> "A"
2240  * 230.chr #=> "\346"
2241  * 255.chr(Encoding::UTF_8) #=> "\303\277"
2242  */
2243 
2244 static VALUE
2246 {
2247  char c;
2248  unsigned int i;
2249  rb_encoding *enc;
2250 
2251  if (rb_num_to_uint(num, &i) == 0) {
2252  }
2253  else if (FIXNUM_P(num)) {
2254  rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
2255  }
2256  else {
2257  rb_raise(rb_eRangeError, "bignum out of char range");
2258  }
2259 
2260  switch (argc) {
2261  case 0:
2262  if (0xff < i) {
2264  if (!enc) {
2265  rb_raise(rb_eRangeError, "%d out of char range", i);
2266  }
2267  goto decode;
2268  }
2269  c = (char)i;
2270  if (i < 0x80) {
2271  return rb_usascii_str_new(&c, 1);
2272  }
2273  else {
2274  return rb_str_new(&c, 1);
2275  }
2276  case 1:
2277  break;
2278  default:
2279  rb_raise(rb_eArgError, "wrong number of arguments (%d for 0..1)", argc);
2280  break;
2281  }
2282  enc = rb_to_encoding(argv[0]);
2283  if (!enc) enc = rb_ascii8bit_encoding();
2284  decode:
2285  return rb_enc_uint_chr(i, enc);
2286 }
2287 
2288 /*
2289  * call-seq:
2290  * int.ord -> self
2291  *
2292  * Returns the int itself.
2293  *
2294  * ?a.ord #=> 97
2295  *
2296  * This method is intended for compatibility to
2297  * character constant in Ruby 1.9.
2298  * For example, ?a.ord returns 97 both in 1.8 and 1.9.
2299  */
2300 
2301 static VALUE
2303 {
2304  return num;
2305 }
2306 
2307 /********************************************************************
2308  *
2309  * Document-class: Fixnum
2310  *
2311  * A <code>Fixnum</code> holds <code>Integer</code> values that can be
2312  * represented in a native machine word (minus 1 bit). If any operation
2313  * on a <code>Fixnum</code> exceeds this range, the value is
2314  * automatically converted to a <code>Bignum</code>.
2315  *
2316  * <code>Fixnum</code> objects have immediate value. This means that
2317  * when they are assigned or passed as parameters, the actual object is
2318  * passed, rather than a reference to that object. Assignment does not
2319  * alias <code>Fixnum</code> objects. There is effectively only one
2320  * <code>Fixnum</code> object instance for any given integer value, so,
2321  * for example, you cannot add a singleton method to a
2322  * <code>Fixnum</code>.
2323  */
2324 
2325 
2326 /*
2327  * call-seq:
2328  * -fix -> integer
2329  *
2330  * Negates <code>fix</code> (which might return a Bignum).
2331  */
2332 
2333 static VALUE
2335 {
2336  return LONG2NUM(-FIX2LONG(num));
2337 }
2338 
2339 VALUE
2340 rb_fix2str(VALUE x, int base)
2341 {
2342  extern const char ruby_digitmap[];
2343  char buf[SIZEOF_VALUE*CHAR_BIT + 2], *b = buf + sizeof buf;
2344  long val = FIX2LONG(x);
2345  int neg = 0;
2346 
2347  if (base < 2 || 36 < base) {
2348  rb_raise(rb_eArgError, "invalid radix %d", base);
2349  }
2350  if (val == 0) {
2351  return rb_usascii_str_new2("0");
2352  }
2353  if (val < 0) {
2354  val = -val;
2355  neg = 1;
2356  }
2357  *--b = '\0';
2358  do {
2359  *--b = ruby_digitmap[(int)(val % base)];
2360  } while (val /= base);
2361  if (neg) {
2362  *--b = '-';
2363  }
2364 
2365  return rb_usascii_str_new2(b);
2366 }
2367 
2368 /*
2369  * call-seq:
2370  * fix.to_s(base=10) -> string
2371  *
2372  * Returns a string containing the representation of <i>fix</i> radix
2373  * <i>base</i> (between 2 and 36).
2374  *
2375  * 12345.to_s #=> "12345"
2376  * 12345.to_s(2) #=> "11000000111001"
2377  * 12345.to_s(8) #=> "30071"
2378  * 12345.to_s(10) #=> "12345"
2379  * 12345.to_s(16) #=> "3039"
2380  * 12345.to_s(36) #=> "9ix"
2381  *
2382  */
2383 static VALUE
2385 {
2386  int base;
2387 
2388  if (argc == 0) base = 10;
2389  else {
2390  VALUE b;
2391 
2392  rb_scan_args(argc, argv, "01", &b);
2393  base = NUM2INT(b);
2394  }
2395 
2396  return rb_fix2str(x, base);
2397 }
2398 
2399 /*
2400  * call-seq:
2401  * fix + numeric -> numeric_result
2402  *
2403  * Performs addition: the class of the resulting object depends on
2404  * the class of <code>numeric</code> and on the magnitude of the
2405  * result.
2406  */
2407 
2408 static VALUE
2410 {
2411  if (FIXNUM_P(y)) {
2412  long a, b, c;
2413  VALUE r;
2414 
2415  a = FIX2LONG(x);
2416  b = FIX2LONG(y);
2417  c = a + b;
2418  r = LONG2NUM(c);
2419 
2420  return r;
2421  }
2422  switch (TYPE(y)) {
2423  case T_BIGNUM:
2424  return rb_big_plus(y, x);
2425  case T_FLOAT:
2426  return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
2427  default:
2428  return rb_num_coerce_bin(x, y, '+');
2429  }
2430 }
2431 
2432 /*
2433  * call-seq:
2434  * fix - numeric -> numeric_result
2435  *
2436  * Performs subtraction: the class of the resulting object depends on
2437  * the class of <code>numeric</code> and on the magnitude of the
2438  * result.
2439  */
2440 
2441 static VALUE
2443 {
2444  if (FIXNUM_P(y)) {
2445  long a, b, c;
2446  VALUE r;
2447 
2448  a = FIX2LONG(x);
2449  b = FIX2LONG(y);
2450  c = a - b;
2451  r = LONG2NUM(c);
2452 
2453  return r;
2454  }
2455  switch (TYPE(y)) {
2456  case T_BIGNUM:
2457  x = rb_int2big(FIX2LONG(x));
2458  return rb_big_minus(x, y);
2459  case T_FLOAT:
2460  return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
2461  default:
2462  return rb_num_coerce_bin(x, y, '-');
2463  }
2464 }
2465 
2466 #define SQRT_LONG_MAX ((SIGNED_VALUE)1<<((SIZEOF_LONG*CHAR_BIT-1)/2))
2467 /*tests if N*N would overflow*/
2468 #define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
2469 
2470 /*
2471  * call-seq:
2472  * fix * numeric -> numeric_result
2473  *
2474  * Performs multiplication: the class of the resulting object depends on
2475  * the class of <code>numeric</code> and on the magnitude of the
2476  * result.
2477  */
2478 
2479 static VALUE
2481 {
2482  if (FIXNUM_P(y)) {
2483 #ifdef __HP_cc
2484 /* avoids an optimization bug of HP aC++/ANSI C B3910B A.06.05 [Jul 25 2005] */
2485  volatile
2486 #endif
2487  long a, b;
2488 #if SIZEOF_LONG * 2 <= SIZEOF_LONG_LONG
2489  LONG_LONG d;
2490 #else
2491  volatile long c;
2492  VALUE r;
2493 #endif
2494 
2495  a = FIX2LONG(x);
2496  b = FIX2LONG(y);
2497 
2498 #if SIZEOF_LONG * 2 <= SIZEOF_LONG_LONG
2499  d = (LONG_LONG)a * b;
2500  if (FIXABLE(d)) return LONG2FIX(d);
2501  return rb_ll2inum(d);
2502 #else
2503  if (FIT_SQRT_LONG(a) && FIT_SQRT_LONG(b))
2504  return LONG2FIX(a*b);
2505  c = a * b;
2506  r = LONG2FIX(c);
2507 
2508  if (a == 0) return x;
2509  if (FIX2LONG(r) != c || c/a != b) {
2510  r = rb_big_mul(rb_int2big(a), rb_int2big(b));
2511  }
2512  return r;
2513 #endif
2514  }
2515  switch (TYPE(y)) {
2516  case T_BIGNUM:
2517  return rb_big_mul(y, x);
2518  case T_FLOAT:
2519  return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
2520  default:
2521  return rb_num_coerce_bin(x, y, '*');
2522  }
2523 }
2524 
2525 static void
2526 fixdivmod(long x, long y, long *divp, long *modp)
2527 {
2528  long div, mod;
2529 
2530  if (y == 0) rb_num_zerodiv();
2531  if (y < 0) {
2532  if (x < 0)
2533  div = -x / -y;
2534  else
2535  div = - (x / -y);
2536  }
2537  else {
2538  if (x < 0)
2539  div = - (-x / y);
2540  else
2541  div = x / y;
2542  }
2543  mod = x - div*y;
2544  if ((mod < 0 && y > 0) || (mod > 0 && y < 0)) {
2545  mod += y;
2546  div -= 1;
2547  }
2548  if (divp) *divp = div;
2549  if (modp) *modp = mod;
2550 }
2551 
2552 /*
2553  * call-seq:
2554  * fix.fdiv(numeric) -> float
2555  *
2556  * Returns the floating point result of dividing <i>fix</i> by
2557  * <i>numeric</i>.
2558  *
2559  * 654321.fdiv(13731) #=> 47.6528293642124
2560  * 654321.fdiv(13731.24) #=> 47.6519964693647
2561  *
2562  */
2563 
2564 static VALUE
2566 {
2567  if (FIXNUM_P(y)) {
2568  return DBL2NUM((double)FIX2LONG(x) / (double)FIX2LONG(y));
2569  }
2570  switch (TYPE(y)) {
2571  case T_BIGNUM:
2572  return rb_big_fdiv(rb_int2big(FIX2LONG(x)), y);
2573  case T_FLOAT:
2574  return DBL2NUM((double)FIX2LONG(x) / RFLOAT_VALUE(y));
2575  default:
2576  return rb_num_coerce_bin(x, y, rb_intern("fdiv"));
2577  }
2578 }
2579 
2580 static VALUE
2582 {
2583  if (FIXNUM_P(y)) {
2584  long div;
2585 
2586  fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, 0);
2587  return LONG2NUM(div);
2588  }
2589  switch (TYPE(y)) {
2590  case T_BIGNUM:
2591  x = rb_int2big(FIX2LONG(x));
2592  return rb_big_div(x, y);
2593  case T_FLOAT:
2594  {
2595  double div;
2596 
2597  if (op == '/') {
2598  div = (double)FIX2LONG(x) / RFLOAT_VALUE(y);
2599  return DBL2NUM(div);
2600  }
2601  else {
2602  if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
2603  div = (double)FIX2LONG(x) / RFLOAT_VALUE(y);
2604  return rb_dbl2big(floor(div));
2605  }
2606  }
2607  case T_RATIONAL:
2608  if (op == '/' && FIX2LONG(x) == 1)
2609  return rb_rational_reciprocal(y);
2610  /* fall through */
2611  default:
2612  return rb_num_coerce_bin(x, y, op);
2613  }
2614 }
2615 
2616 /*
2617  * call-seq:
2618  * fix / numeric -> numeric_result
2619  *
2620  * Performs division: the class of the resulting object depends on
2621  * the class of <code>numeric</code> and on the magnitude of the
2622  * result.
2623  */
2624 
2625 static VALUE
2627 {
2628  return fix_divide(x, y, '/');
2629 }
2630 
2631 /*
2632  * call-seq:
2633  * fix.div(numeric) -> integer
2634  *
2635  * Performs integer division: returns integer value.
2636  */
2637 
2638 static VALUE
2640 {
2641  return fix_divide(x, y, rb_intern("div"));
2642 }
2643 
2644 /*
2645  * call-seq:
2646  * fix % other -> real
2647  * fix.modulo(other) -> real
2648  *
2649  * Returns <code>fix</code> modulo <code>other</code>.
2650  * See <code>numeric.divmod</code> for more information.
2651  */
2652 
2653 static VALUE
2655 {
2656  if (FIXNUM_P(y)) {
2657  long mod;
2658 
2659  fixdivmod(FIX2LONG(x), FIX2LONG(y), 0, &mod);
2660  return LONG2NUM(mod);
2661  }
2662  switch (TYPE(y)) {
2663  case T_BIGNUM:
2664  x = rb_int2big(FIX2LONG(x));
2665  return rb_big_modulo(x, y);
2666  case T_FLOAT:
2667  return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
2668  default:
2669  return rb_num_coerce_bin(x, y, '%');
2670  }
2671 }
2672 
2673 /*
2674  * call-seq:
2675  * fix.divmod(numeric) -> array
2676  *
2677  * See <code>Numeric#divmod</code>.
2678  */
2679 static VALUE
2681 {
2682  if (FIXNUM_P(y)) {
2683  long div, mod;
2684 
2685  fixdivmod(FIX2LONG(x), FIX2LONG(y), &div, &mod);
2686 
2687  return rb_assoc_new(LONG2NUM(div), LONG2NUM(mod));
2688  }
2689  switch (TYPE(y)) {
2690  case T_BIGNUM:
2691  x = rb_int2big(FIX2LONG(x));
2692  return rb_big_divmod(x, y);
2693  case T_FLOAT:
2694  {
2695  double div, mod;
2696  volatile VALUE a, b;
2697 
2698  flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
2699  a = dbl2ival(div);
2700  b = DBL2NUM(mod);
2701  return rb_assoc_new(a, b);
2702  }
2703  default:
2704  return rb_num_coerce_bin(x, y, rb_intern("divmod"));
2705  }
2706 }
2707 
2708 static VALUE
2709 int_pow(long x, unsigned long y)
2710 {
2711  int neg = x < 0;
2712  long z = 1;
2713 
2714  if (neg) x = -x;
2715  if (y & 1)
2716  z = x;
2717  else
2718  neg = 0;
2719  y &= ~1;
2720  do {
2721  while (y % 2 == 0) {
2722  if (!FIT_SQRT_LONG(x)) {
2723  VALUE v;
2724  bignum:
2725  v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
2726  if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
2727  return v;
2728  }
2729  x = x * x;
2730  y >>= 1;
2731  }
2732  {
2733  volatile long xz = x * z;
2734  if (!POSFIXABLE(xz) || xz / x != z) {
2735  goto bignum;
2736  }
2737  z = xz;
2738  }
2739  } while (--y);
2740  if (neg) z = -z;
2741  return LONG2NUM(z);
2742 }
2743 
2744 /*
2745  * call-seq:
2746  * fix ** numeric -> numeric_result
2747  *
2748  * Raises <code>fix</code> to the <code>numeric</code> power, which may
2749  * be negative or fractional.
2750  *
2751  * 2 ** 3 #=> 8
2752  * 2 ** -1 #=> 0.5
2753  * 2 ** 0.5 #=> 1.4142135623731
2754  */
2755 
2756 static VALUE
2758 {
2759  long a = FIX2LONG(x);
2760 
2761  if (FIXNUM_P(y)) {
2762  long b = FIX2LONG(y);
2763 
2764  if (b < 0)
2765  return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2766 
2767  if (b == 0) return INT2FIX(1);
2768  if (b == 1) return x;
2769  if (a == 0) {
2770  if (b > 0) return INT2FIX(0);
2771  return DBL2NUM(INFINITY);
2772  }
2773  if (a == 1) return INT2FIX(1);
2774  if (a == -1) {
2775  if (b % 2 == 0)
2776  return INT2FIX(1);
2777  else
2778  return INT2FIX(-1);
2779  }
2780  return int_pow(a, b);
2781  }
2782  switch (TYPE(y)) {
2783  case T_BIGNUM:
2784 
2785  if (rb_funcall(y, '<', 1, INT2FIX(0)))
2786  return rb_funcall(rb_rational_raw1(x), rb_intern("**"), 1, y);
2787 
2788  if (a == 0) return INT2FIX(0);
2789  if (a == 1) return INT2FIX(1);
2790  if (a == -1) {
2791  if (int_even_p(y)) return INT2FIX(1);
2792  else return INT2FIX(-1);
2793  }
2794  x = rb_int2big(FIX2LONG(x));
2795  return rb_big_pow(x, y);
2796  case T_FLOAT:
2797  if (RFLOAT_VALUE(y) == 0.0) return DBL2NUM(1.0);
2798  if (a == 0) {
2799  return DBL2NUM(RFLOAT_VALUE(y) < 0 ? INFINITY : 0.0);
2800  }
2801  if (a == 1) return DBL2NUM(1.0);
2802  {
2803  double dy = RFLOAT_VALUE(y);
2804  if (a < 0 && dy != round(dy))
2805  return rb_funcall(rb_complex_raw1(x), rb_intern("**"), 1, y);
2806  return DBL2NUM(pow((double)a, dy));
2807  }
2808  default:
2809  return rb_num_coerce_bin(x, y, rb_intern("**"));
2810  }
2811 }
2812 
2813 /*
2814  * call-seq:
2815  * fix == other -> true or false
2816  *
2817  * Return <code>true</code> if <code>fix</code> equals <code>other</code>
2818  * numerically.
2819  *
2820  * 1 == 2 #=> false
2821  * 1 == 1.0 #=> true
2822  */
2823 
2824 static VALUE
2826 {
2827  if (x == y) return Qtrue;
2828  if (FIXNUM_P(y)) return Qfalse;
2829  switch (TYPE(y)) {
2830  case T_BIGNUM:
2831  return rb_big_eq(y, x);
2832  case T_FLOAT:
2833  return (double)FIX2LONG(x) == RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2834  default:
2835  return num_equal(x, y);
2836  }
2837 }
2838 
2839 /*
2840  * call-seq:
2841  * fix <=> numeric -> -1, 0, +1 or nil
2842  *
2843  * Comparison---Returns -1, 0, +1 or nil depending on whether
2844  * <i>fix</i> is less than, equal to, or greater than
2845  * <i>numeric</i>. This is the basis for the tests in
2846  * <code>Comparable</code>.
2847  */
2848 
2849 static VALUE
2851 {
2852  if (x == y) return INT2FIX(0);
2853  if (FIXNUM_P(y)) {
2854  if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
2855  return INT2FIX(-1);
2856  }
2857  switch (TYPE(y)) {
2858  case T_BIGNUM:
2859  return rb_big_cmp(rb_int2big(FIX2LONG(x)), y);
2860  case T_FLOAT:
2861  return rb_dbl_cmp((double)FIX2LONG(x), RFLOAT_VALUE(y));
2862  default:
2863  return rb_num_coerce_cmp(x, y, rb_intern("<=>"));
2864  }
2865 }
2866 
2867 /*
2868  * call-seq:
2869  * fix > real -> true or false
2870  *
2871  * Returns <code>true</code> if the value of <code>fix</code> is
2872  * greater than that of <code>real</code>.
2873  */
2874 
2875 static VALUE
2877 {
2878  if (FIXNUM_P(y)) {
2879  if (FIX2LONG(x) > FIX2LONG(y)) return Qtrue;
2880  return Qfalse;
2881  }
2882  switch (TYPE(y)) {
2883  case T_BIGNUM:
2884  return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) > 0 ? Qtrue : Qfalse;
2885  case T_FLOAT:
2886  return (double)FIX2LONG(x) > RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2887  default:
2888  return rb_num_coerce_relop(x, y, '>');
2889  }
2890 }
2891 
2892 /*
2893  * call-seq:
2894  * fix >= real -> true or false
2895  *
2896  * Returns <code>true</code> if the value of <code>fix</code> is
2897  * greater than or equal to that of <code>real</code>.
2898  */
2899 
2900 static VALUE
2902 {
2903  if (FIXNUM_P(y)) {
2904  if (FIX2LONG(x) >= FIX2LONG(y)) return Qtrue;
2905  return Qfalse;
2906  }
2907  switch (TYPE(y)) {
2908  case T_BIGNUM:
2909  return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) >= 0 ? Qtrue : Qfalse;
2910  case T_FLOAT:
2911  return (double)FIX2LONG(x) >= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2912  default:
2913  return rb_num_coerce_relop(x, y, rb_intern(">="));
2914  }
2915 }
2916 
2917 /*
2918  * call-seq:
2919  * fix < real -> true or false
2920  *
2921  * Returns <code>true</code> if the value of <code>fix</code> is
2922  * less than that of <code>real</code>.
2923  */
2924 
2925 static VALUE
2927 {
2928  if (FIXNUM_P(y)) {
2929  if (FIX2LONG(x) < FIX2LONG(y)) return Qtrue;
2930  return Qfalse;
2931  }
2932  switch (TYPE(y)) {
2933  case T_BIGNUM:
2934  return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) < 0 ? Qtrue : Qfalse;
2935  case T_FLOAT:
2936  return (double)FIX2LONG(x) < RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2937  default:
2938  return rb_num_coerce_relop(x, y, '<');
2939  }
2940 }
2941 
2942 /*
2943  * call-seq:
2944  * fix <= real -> true or false
2945  *
2946  * Returns <code>true</code> if the value of <code>fix</code> is
2947  * less than or equal to that of <code>real</code>.
2948  */
2949 
2950 static VALUE
2952 {
2953  if (FIXNUM_P(y)) {
2954  if (FIX2LONG(x) <= FIX2LONG(y)) return Qtrue;
2955  return Qfalse;
2956  }
2957  switch (TYPE(y)) {
2958  case T_BIGNUM:
2959  return FIX2INT(rb_big_cmp(rb_int2big(FIX2LONG(x)), y)) <= 0 ? Qtrue : Qfalse;
2960  case T_FLOAT:
2961  return (double)FIX2LONG(x) <= RFLOAT_VALUE(y) ? Qtrue : Qfalse;
2962  default:
2963  return rb_num_coerce_relop(x, y, rb_intern("<="));
2964  }
2965 }
2966 
2967 /*
2968  * call-seq:
2969  * ~fix -> integer
2970  *
2971  * One's complement: returns a number where each bit is flipped.
2972  */
2973 
2974 static VALUE
2976 {
2977  return ~num | FIXNUM_FLAG;
2978 }
2979 
2980 static VALUE
2982 {
2983  while (!FIXNUM_P(x) && TYPE(x) != T_BIGNUM) {
2984  if (TYPE(x) == T_FLOAT) {
2985  rb_raise(rb_eTypeError, "can't convert Float into Integer");
2986  }
2987  x = rb_to_int(x);
2988  }
2989  return x;
2990 }
2991 
2992 /*
2993  * call-seq:
2994  * fix & integer -> integer_result
2995  *
2996  * Bitwise AND.
2997  */
2998 
2999 static VALUE
3001 {
3002  long val;
3003 
3004  if (!FIXNUM_P(y = bit_coerce(y))) {
3005  return rb_big_and(y, x);
3006  }
3007  val = FIX2LONG(x) & FIX2LONG(y);
3008  return LONG2NUM(val);
3009 }
3010 
3011 /*
3012  * call-seq:
3013  * fix | integer -> integer_result
3014  *
3015  * Bitwise OR.
3016  */
3017 
3018 static VALUE
3020 {
3021  long val;
3022 
3023  if (!FIXNUM_P(y = bit_coerce(y))) {
3024  return rb_big_or(y, x);
3025  }
3026  val = FIX2LONG(x) | FIX2LONG(y);
3027  return LONG2NUM(val);
3028 }
3029 
3030 /*
3031  * call-seq:
3032  * fix ^ integer -> integer_result
3033  *
3034  * Bitwise EXCLUSIVE OR.
3035  */
3036 
3037 static VALUE
3039 {
3040  long val;
3041 
3042  if (!FIXNUM_P(y = bit_coerce(y))) {
3043  return rb_big_xor(y, x);
3044  }
3045  val = FIX2LONG(x) ^ FIX2LONG(y);
3046  return LONG2NUM(val);
3047 }
3048 
3049 static VALUE fix_lshift(long, unsigned long);
3050 static VALUE fix_rshift(long, unsigned long);
3051 
3052 /*
3053  * call-seq:
3054  * fix << count -> integer
3055  *
3056  * Shifts _fix_ left _count_ positions (right if _count_ is negative).
3057  */
3058 
3059 static VALUE
3061 {
3062  long val, width;
3063 
3064  val = NUM2LONG(x);
3065  if (!FIXNUM_P(y))
3066  return rb_big_lshift(rb_int2big(val), y);
3067  width = FIX2LONG(y);
3068  if (width < 0)
3069  return fix_rshift(val, (unsigned long)-width);
3070  return fix_lshift(val, width);
3071 }
3072 
3073 static VALUE
3074 fix_lshift(long val, unsigned long width)
3075 {
3076  if (width > (SIZEOF_LONG*CHAR_BIT-1)
3077  || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
3078  return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
3079  }
3080  val = val << width;
3081  return LONG2NUM(val);
3082 }
3083 
3084 /*
3085  * call-seq:
3086  * fix >> count -> integer
3087  *
3088  * Shifts _fix_ right _count_ positions (left if _count_ is negative).
3089  */
3090 
3091 static VALUE
3093 {
3094  long i, val;
3095 
3096  val = FIX2LONG(x);
3097  if (!FIXNUM_P(y))
3098  return rb_big_rshift(rb_int2big(val), y);
3099  i = FIX2LONG(y);
3100  if (i == 0) return x;
3101  if (i < 0)
3102  return fix_lshift(val, (unsigned long)-i);
3103  return fix_rshift(val, i);
3104 }
3105 
3106 static VALUE
3107 fix_rshift(long val, unsigned long i)
3108 {
3109  if (i >= sizeof(long)*CHAR_BIT-1) {
3110  if (val < 0) return INT2FIX(-1);
3111  return INT2FIX(0);
3112  }
3113  val = RSHIFT(val, i);
3114  return LONG2FIX(val);
3115 }
3116 
3117 /*
3118  * call-seq:
3119  * fix[n] -> 0, 1
3120  *
3121  * Bit Reference---Returns the <em>n</em>th bit in the binary
3122  * representation of <i>fix</i>, where <i>fix</i>[0] is the least
3123  * significant bit.
3124  *
3125  * a = 0b11001100101010
3126  * 30.downto(0) do |n| print a[n] end
3127  *
3128  * <em>produces:</em>
3129  *
3130  * 0000000000000000011001100101010
3131  */
3132 
3133 static VALUE
3135 {
3136  long val = FIX2LONG(fix);
3137  long i;
3138 
3139  idx = rb_to_int(idx);
3140  if (!FIXNUM_P(idx)) {
3141  idx = rb_big_norm(idx);
3142  if (!FIXNUM_P(idx)) {
3143  if (!RBIGNUM_SIGN(idx) || val >= 0)
3144  return INT2FIX(0);
3145  return INT2FIX(1);
3146  }
3147  }
3148  i = FIX2LONG(idx);
3149 
3150  if (i < 0) return INT2FIX(0);
3151  if (SIZEOF_LONG*CHAR_BIT-1 < i) {
3152  if (val < 0) return INT2FIX(1);
3153  return INT2FIX(0);
3154  }
3155  if (val & (1L<<i))
3156  return INT2FIX(1);
3157  return INT2FIX(0);
3158 }
3159 
3160 /*
3161  * call-seq:
3162  * fix.to_f -> float
3163  *
3164  * Converts <i>fix</i> to a <code>Float</code>.
3165  *
3166  */
3167 
3168 static VALUE
3170 {
3171  double val;
3172 
3173  val = (double)FIX2LONG(num);
3174 
3175  return DBL2NUM(val);
3176 }
3177 
3178 /*
3179  * call-seq:
3180  * fix.abs -> integer
3181  * fix.magnitude -> integer
3182  *
3183  * Returns the absolute value of <i>fix</i>.
3184  *
3185  * -12345.abs #=> 12345
3186  * 12345.abs #=> 12345
3187  *
3188  */
3189 
3190 static VALUE
3192 {
3193  long i = FIX2LONG(fix);
3194 
3195  if (i < 0) i = -i;
3196 
3197  return LONG2NUM(i);
3198 }
3199 
3200 
3201 
3202 /*
3203  * call-seq:
3204  * fix.size -> fixnum
3205  *
3206  * Returns the number of <em>bytes</em> in the machine representation
3207  * of a <code>Fixnum</code>.
3208  *
3209  * 1.size #=> 4
3210  * -1.size #=> 4
3211  * 2147483647.size #=> 4
3212  */
3213 
3214 static VALUE
3216 {
3217  return INT2FIX(sizeof(long));
3218 }
3219 
3220 /*
3221  * call-seq:
3222  * int.upto(limit) {|i| block } -> self
3223  * int.upto(limit) -> an_enumerator
3224  *
3225  * Iterates <em>block</em>, passing in integer values from <i>int</i>
3226  * up to and including <i>limit</i>.
3227  *
3228  * If no block is given, an enumerator is returned instead.
3229  *
3230  * 5.upto(10) { |i| print i, " " }
3231  *
3232  * <em>produces:</em>
3233  *
3234  * 5 6 7 8 9 10
3235  */
3236 
3237 static VALUE
3239 {
3240  RETURN_ENUMERATOR(from, 1, &to);
3241  if (FIXNUM_P(from) && FIXNUM_P(to)) {
3242  long i, end;
3243 
3244  end = FIX2LONG(to);
3245  for (i = FIX2LONG(from); i <= end; i++) {
3246  rb_yield(LONG2FIX(i));
3247  }
3248  }
3249  else {
3250  VALUE i = from, c;
3251 
3252  while (!(c = rb_funcall(i, '>', 1, to))) {
3253  rb_yield(i);
3254  i = rb_funcall(i, '+', 1, INT2FIX(1));
3255  }
3256  if (NIL_P(c)) rb_cmperr(i, to);
3257  }
3258  return from;
3259 }
3260 
3261 /*
3262  * call-seq:
3263  * int.downto(limit) {|i| block } -> self
3264  * int.downto(limit) -> an_enumerator
3265  *
3266  * Iterates <em>block</em>, passing decreasing values from <i>int</i>
3267  * down to and including <i>limit</i>.
3268  *
3269  * If no block is given, an enumerator is returned instead.
3270  *
3271  * 5.downto(1) { |n| print n, ".. " }
3272  * print " Liftoff!\n"
3273  *
3274  * <em>produces:</em>
3275  *
3276  * 5.. 4.. 3.. 2.. 1.. Liftoff!
3277  */
3278 
3279 static VALUE
3281 {
3282  RETURN_ENUMERATOR(from, 1, &to);
3283  if (FIXNUM_P(from) && FIXNUM_P(to)) {
3284  long i, end;
3285 
3286  end = FIX2LONG(to);
3287  for (i=FIX2LONG(from); i >= end; i--) {
3288  rb_yield(LONG2FIX(i));
3289  }
3290  }
3291  else {
3292  VALUE i = from, c;
3293 
3294  while (!(c = rb_funcall(i, '<', 1, to))) {
3295  rb_yield(i);
3296  i = rb_funcall(i, '-', 1, INT2FIX(1));
3297  }
3298  if (NIL_P(c)) rb_cmperr(i, to);
3299  }
3300  return from;
3301 }
3302 
3303 /*
3304  * call-seq:
3305  * int.times {|i| block } -> self
3306  * int.times -> an_enumerator
3307  *
3308  * Iterates block <i>int</i> times, passing in values from zero to
3309  * <i>int</i> - 1.
3310  *
3311  * If no block is given, an enumerator is returned instead.
3312  *
3313  * 5.times do |i|
3314  * print i, " "
3315  * end
3316  *
3317  * <em>produces:</em>
3318  *
3319  * 0 1 2 3 4
3320  */
3321 
3322 static VALUE
3324 {
3325  RETURN_ENUMERATOR(num, 0, 0);
3326 
3327  if (FIXNUM_P(num)) {
3328  long i, end;
3329 
3330  end = FIX2LONG(num);
3331  for (i=0; i<end; i++) {
3332  rb_yield(LONG2FIX(i));
3333  }
3334  }
3335  else {
3336  VALUE i = INT2FIX(0);
3337 
3338  for (;;) {
3339  if (!RTEST(rb_funcall(i, '<', 1, num))) break;
3340  rb_yield(i);
3341  i = rb_funcall(i, '+', 1, INT2FIX(1));
3342  }
3343  }
3344  return num;
3345 }
3346 
3347 /*
3348  * call-seq:
3349  * int.round([ndigits]) -> integer or float
3350  *
3351  * Rounds <i>flt</i> to a given precision in decimal digits (default 0 digits).
3352  * Precision may be negative. Returns a floating point number when +ndigits+
3353  * is positive, +self+ for zero, and round down for negative.
3354  *
3355  * 1.round #=> 1
3356  * 1.round(2) #=> 1.0
3357  * 15.round(-1) #=> 20
3358  */
3359 
3360 static VALUE
3362 {
3363  VALUE n;
3364  int ndigits;
3365 
3366  if (argc == 0) return num;
3367  rb_scan_args(argc, argv, "1", &n);
3368  ndigits = NUM2INT(n);
3369  if (ndigits > 0) {
3370  return rb_Float(num);
3371  }
3372  if (ndigits == 0) {
3373  return num;
3374  }
3375  return int_round_0(num, ndigits);
3376 }
3377 
3378 /*
3379  * call-seq:
3380  * fix.zero? -> true or false
3381  *
3382  * Returns <code>true</code> if <i>fix</i> is zero.
3383  *
3384  */
3385 
3386 static VALUE
3388 {
3389  if (FIX2LONG(num) == 0) {
3390  return Qtrue;
3391  }
3392  return Qfalse;
3393 }
3394 
3395 /*
3396  * call-seq:
3397  * fix.odd? -> true or false
3398  *
3399  * Returns <code>true</code> if <i>fix</i> is an odd number.
3400  */
3401 
3402 static VALUE
3404 {
3405  if (num & 2) {
3406  return Qtrue;
3407  }
3408  return Qfalse;
3409 }
3410 
3411 /*
3412  * call-seq:
3413  * fix.even? -> true or false
3414  *
3415  * Returns <code>true</code> if <i>fix</i> is an even number.
3416  */
3417 
3418 static VALUE
3420 {
3421  if (num & 2) {
3422  return Qfalse;
3423  }
3424  return Qtrue;
3425 }
3426 
3427 /*
3428  * Document-class: ZeroDivisionError
3429  *
3430  * Raised when attempting to divide an integer by 0.
3431  *
3432  * 42 / 0
3433  *
3434  * <em>raises the exception:</em>
3435  *
3436  * ZeroDivisionError: divided by 0
3437  *
3438  * Note that only division by an exact 0 will raise that exception:
3439  *
3440  * 42 / 0.0 #=> Float::INFINITY
3441  * 42 / -0.0 #=> -Float::INFINITY
3442  * 0 / 0.0 #=> NaN
3443  */
3444 
3445 /*
3446  * Document-class: FloatDomainError
3447  *
3448  * Raised when attempting to convert special float values
3449  * (in particular infinite or NaN)
3450  * to numerical classes which don't support them.
3451  *
3452  * Float::INFINITY.to_r
3453  *
3454  * <em>raises the exception:</em>
3455  *
3456  * FloatDomainError: Infinity
3457  */
3458 
3459 void
3461 {
3462 #undef rb_intern
3463 #define rb_intern(str) rb_intern_const(str)
3464 
3465 #if defined(__FreeBSD__) && __FreeBSD__ < 4
3466  /* allow divide by zero -- Inf */
3467  fpsetmask(fpgetmask() & ~(FP_X_DZ|FP_X_INV|FP_X_OFL));
3468 #elif defined(_UNICOSMP)
3469  /* Turn off floating point exceptions for divide by zero, etc. */
3470  _set_Creg(0, 0);
3471 #elif defined(__BORLANDC__)
3472  /* Turn off floating point exceptions for overflow, etc. */
3473  _control87(MCW_EM, MCW_EM);
3474  _control87(_control87(0,0),0x1FFF);
3475 #endif
3476  id_coerce = rb_intern("coerce");
3477  id_to_i = rb_intern("to_i");
3478  id_eq = rb_intern("==");
3479 
3480  rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
3481  rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
3482  rb_cNumeric = rb_define_class("Numeric", rb_cObject);
3483 
3484  rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
3486  rb_define_method(rb_cNumeric, "initialize_copy", num_init_copy, 1);
3487  rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
3488 
3492  rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
3493  rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
3494  rb_define_method(rb_cNumeric, "quo", num_quo, 1);
3495  rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
3496  rb_define_method(rb_cNumeric, "div", num_div, 1);
3497  rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
3499  rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
3500  rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
3501  rb_define_method(rb_cNumeric, "abs", num_abs, 0);
3502  rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
3503  rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
3504 
3505  rb_define_method(rb_cNumeric, "real?", num_real_p, 0);
3506  rb_define_method(rb_cNumeric, "integer?", num_int_p, 0);
3507  rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
3508  rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
3509 
3510  rb_define_method(rb_cNumeric, "floor", num_floor, 0);
3511  rb_define_method(rb_cNumeric, "ceil", num_ceil, 0);
3512  rb_define_method(rb_cNumeric, "round", num_round, -1);
3513  rb_define_method(rb_cNumeric, "truncate", num_truncate, 0);
3514  rb_define_method(rb_cNumeric, "step", num_step, -1);
3515 
3516  rb_cInteger = rb_define_class("Integer", rb_cNumeric);
3519 
3520  rb_define_method(rb_cInteger, "integer?", int_int_p, 0);
3521  rb_define_method(rb_cInteger, "odd?", int_odd_p, 0);
3522  rb_define_method(rb_cInteger, "even?", int_even_p, 0);
3523  rb_define_method(rb_cInteger, "upto", int_upto, 1);
3524  rb_define_method(rb_cInteger, "downto", int_downto, 1);
3526  rb_define_method(rb_cInteger, "succ", int_succ, 0);
3527  rb_define_method(rb_cInteger, "next", int_succ, 0);
3528  rb_define_method(rb_cInteger, "pred", int_pred, 0);
3529  rb_define_method(rb_cInteger, "chr", int_chr, -1);
3530  rb_define_method(rb_cInteger, "ord", int_ord, 0);
3531  rb_define_method(rb_cInteger, "to_i", int_to_i, 0);
3532  rb_define_method(rb_cInteger, "to_int", int_to_i, 0);
3533  rb_define_method(rb_cInteger, "floor", int_to_i, 0);
3534  rb_define_method(rb_cInteger, "ceil", int_to_i, 0);
3535  rb_define_method(rb_cInteger, "truncate", int_to_i, 0);
3536  rb_define_method(rb_cInteger, "round", int_round, -1);
3537 
3538  rb_cFixnum = rb_define_class("Fixnum", rb_cInteger);
3539 
3540  rb_define_method(rb_cFixnum, "to_s", fix_to_s, -1);
3541 
3547  rb_define_method(rb_cFixnum, "div", fix_idiv, 1);
3549  rb_define_method(rb_cFixnum, "modulo", fix_mod, 1);
3550  rb_define_method(rb_cFixnum, "divmod", fix_divmod, 1);
3551  rb_define_method(rb_cFixnum, "fdiv", fix_fdiv, 1);
3552  rb_define_method(rb_cFixnum, "**", fix_pow, 1);
3553 
3554  rb_define_method(rb_cFixnum, "abs", fix_abs, 0);
3555  rb_define_method(rb_cFixnum, "magnitude", fix_abs, 0);
3556 
3559  rb_define_method(rb_cFixnum, "<=>", fix_cmp, 1);
3561  rb_define_method(rb_cFixnum, ">=", fix_ge, 1);
3563  rb_define_method(rb_cFixnum, "<=", fix_le, 1);
3564 
3570 
3573 
3574  rb_define_method(rb_cFixnum, "to_f", fix_to_f, 0);
3575  rb_define_method(rb_cFixnum, "size", fix_size, 0);
3576  rb_define_method(rb_cFixnum, "zero?", fix_zero_p, 0);
3577  rb_define_method(rb_cFixnum, "odd?", fix_odd_p, 0);
3578  rb_define_method(rb_cFixnum, "even?", fix_even_p, 0);
3579  rb_define_method(rb_cFixnum, "succ", fix_succ, 0);
3580 
3582 
3585 
3597  rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(INFINITY));
3599 
3600  rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
3601  rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
3607  rb_define_method(rb_cFloat, "quo", flo_quo, 1);
3608  rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
3610  rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
3611  rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
3612  rb_define_method(rb_cFloat, "**", flo_pow, 1);
3613  rb_define_method(rb_cFloat, "==", flo_eq, 1);
3614  rb_define_method(rb_cFloat, "===", flo_eq, 1);
3615  rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
3616  rb_define_method(rb_cFloat, ">", flo_gt, 1);
3617  rb_define_method(rb_cFloat, ">=", flo_ge, 1);
3618  rb_define_method(rb_cFloat, "<", flo_lt, 1);
3619  rb_define_method(rb_cFloat, "<=", flo_le, 1);
3620  rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
3621  rb_define_method(rb_cFloat, "hash", flo_hash, 0);
3622  rb_define_method(rb_cFloat, "to_f", flo_to_f, 0);
3623  rb_define_method(rb_cFloat, "abs", flo_abs, 0);
3624  rb_define_method(rb_cFloat, "magnitude", flo_abs, 0);
3625  rb_define_method(rb_cFloat, "zero?", flo_zero_p, 0);
3626 
3628  rb_define_method(rb_cFloat, "to_int", flo_truncate, 0);
3629  rb_define_method(rb_cFloat, "floor", flo_floor, 0);
3630  rb_define_method(rb_cFloat, "ceil", flo_ceil, 0);
3631  rb_define_method(rb_cFloat, "round", flo_round, -1);
3632  rb_define_method(rb_cFloat, "truncate", flo_truncate, 0);
3633 
3635  rb_define_method(rb_cFloat, "infinite?", flo_is_infinite_p, 0);
3636  rb_define_method(rb_cFloat, "finite?", flo_is_finite_p, 0);
3637 }
3638