Debian Codegraph @

src/number.c

raw
1 /*
2 * number.c - numeric functions
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 #define LIBGAUCHE_BODY
34 #include "gauche.h"
35 #include "gauche/priv/configP.h"
36 #include "gauche/scmconst.h"
37 #include "gauche/bits.h"
38 #include "gauche/bits_inline.h"
39 #include "gauche/priv/bignumP.h"
40 #include "gauche/priv/builtin-syms.h"
41 #include "gauche/priv/arith.h"
42 #include "gauche/priv/bytesP.h"
43
44 #include <limits.h>
45 #include <float.h>
46 #include <math.h>
47 #include <ctype.h>
48
49 /*================================================================
50 * Some macros
51 */
52
53 #ifdef HAVE_SUNMATH_H
54 #include "sunmath.h" /* for isinf() on Solaris */
55 #endif /* HAVE_SUNMATH_H */
56
57 #ifndef M_PI
58 #define M_PI 3.14159265358979323846
59 #endif
60
61 #ifndef HAVE_ISINF
62 /* NB: If we inline this, some version of gcc incorrectly assumes
63 the condition would never be satisfied and optimize it away. */
64 int Scm_IsInf(double x)
65 {
66 volatile double xx = x; /* suppress gcc to be too clever */
67 return ((xx) != 0 && (xx) == (xx)/2.0);
68 }
69 #endif
70
71 /* Maximum allowable range of exponent in the number litereal.
72 For flonums, IEEE double can support [-324..308]. For exact
73 numbers we can go further, but it would easily consume huge
74 memory. So I assume it is reasonable to limit its range. */
75 #define MAX_EXPONENT 325
76
77 /* Linux gcc have those, but the declarations aren't included unless
78 __USE_ISOC9X is defined. Just in case. */
79 #ifdef HAVE_TRUNC
80 extern double trunc(double);
81 #endif
82
83 #ifdef HAVE_RINT
84 extern double rint(double);
85 #define roundeven rint
86 #else
87 static double roundeven(double);
88 #endif
89
90 /* Many built-in arithmetic routines come with VM* variants, which
91 are used when the resulting flonum is directly returned to the VM.
92 Such routines share the body with their variants, with an extra
93 flag 'vmp' that indicates whether the call is 'VM' variant or not.
94 RETURN_FLONUM and RETURN_FLOBJ macros are used to hide the different
95 flonum generation in such routines.
96 RETURN_FLONUM takes double arg and returns ScmObj.
97 RETURN_FLOBJ takes ScmObj (ScmFlonum*) and returns ScmObj.
98 */
99 #if GAUCHE_FFX
100 #define RETURN_FLONUM(z) \
101 do { \
102 if (vmp) return Scm_VMReturnFlonum(z); \
103 else return Scm_MakeFlonum(z); \
104 } while (0)
105 #else /*!GAUCHE_FFX*/
106 #define RETURN_FLONUM(z) return Scm_MakeFlonum(z)
107 #endif /*!GAUCHE_FFX*/
108
109 #define DEFINE_DUAL_API1(a, b, kernel) \
110 ScmObj a(ScmObj obj) { return kernel(obj, FALSE); } \
111 ScmObj b(ScmObj obj) { return kernel(obj, TRUE); }
112
113 #define DEFINE_DUAL_API2(a, b, kernel) \
114 ScmObj a(ScmObj obj1, ScmObj obj2) { return kernel(obj1, obj2, FALSE); } \
115 ScmObj b(ScmObj obj1, ScmObj obj2) { return kernel(obj1, obj2, TRUE); }
116
117 /*================================================================
118 * Classes of Numeric Tower
119 */
120
121 static ScmClass *numeric_cpl[] = {
122 SCM_CLASS_STATIC_PTR(Scm_RationalClass),
123 SCM_CLASS_STATIC_PTR(Scm_RealClass),
124 SCM_CLASS_STATIC_PTR(Scm_ComplexClass),
125 SCM_CLASS_STATIC_PTR(Scm_NumberClass),
126 SCM_CLASS_STATIC_PTR(Scm_TopClass),
127 NULL
128 };
129
130 static void number_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx);
131
132 SCM_DEFINE_BUILTIN_CLASS(Scm_NumberClass, number_print, NULL, NULL, NULL,
133 numeric_cpl+4);
134 SCM_DEFINE_BUILTIN_CLASS(Scm_ComplexClass, number_print, NULL, NULL, NULL,
135 numeric_cpl+3);
136 SCM_DEFINE_BUILTIN_CLASS(Scm_RealClass, number_print, NULL, NULL, NULL,
137 numeric_cpl+2);
138 SCM_DEFINE_BUILTIN_CLASS(Scm_RationalClass, number_print, NULL, NULL, NULL,
139 numeric_cpl+1);
140 SCM_DEFINE_BUILTIN_CLASS(Scm_IntegerClass, number_print, NULL, NULL, NULL,
141 numeric_cpl);
142
143 /*=====================================================================
144 * Generic Arithmetic
145 */
146
147 /* Some arithmetic operations calls the corresponding generic function
148 * if the operand is not a number.
149 */
150
151 /* Fallback Gf */
152 static ScmObj bad_number_method(ScmObj *args, int nargs, ScmGeneric *gf)
153 {
154 const char *fn = (const char *)SCM_GENERIC_DATA(gf);
155 if (nargs == 1) {
156 Scm_Error("operation %s is not defined on object %S", fn, args[0]);
157 } else if (nargs == 2) {
158 Scm_Error("operation %s is not defined between %S and %S",
159 fn, args[0], args[1]);
160 } else {
161 Scm_Error("generic function for %s is called with args %S",
162 fn, Scm_ArrayToList(args, nargs));
163 }
164 return SCM_UNDEFINED;
165 }
166 static SCM_DEFINE_GENERIC(generic_add, bad_number_method, "+");
167 static SCM_DEFINE_GENERIC(generic_sub, bad_number_method, "-");
168 static SCM_DEFINE_GENERIC(generic_mul, bad_number_method, "*");
169 static SCM_DEFINE_GENERIC(generic_div, bad_number_method, "/");
170
171 /*=====================================================================
172 * IEEE754 double and Endianness
173 */
174
175 /* Structure to extract bits from a double. This info may be provided
176 * by a system header (e.g. ieee754.h) but for the portability we
177 * define by ourselves.
178 */
179 typedef union {
180 double d;
181 struct {
182 #ifdef WORDS_BIGENDIAN
183 #if SIZEOF_LONG >= 8
184 unsigned int sign:1;
185 unsigned int exp:11;
186 unsigned long mant:52;
187 #else /*SIZEOF_LONG < 8*/
188 unsigned int sign:1;
189 unsigned int exp:11;
190 unsigned long mant0:20;
191 unsigned long mant1:32;
192 #endif /*SIZEOF_LONG < 8*/
193 #else /*!WORDS_BIGENDIAN*/
194 #if SIZEOF_LONG >= 8
195 unsigned long mant:52;
196 unsigned int exp:11;
197 unsigned int sign:1;
198 #else /*SIZEOF_LONG < 8*/
199 unsigned long mant1:32;
200 unsigned long mant0:20;
201 unsigned int exp:11;
202 unsigned int sign:1;
203 #endif /*SIZEOF_LONG < 8*/
204 #endif /*!WORDS_BIGENDIAN*/
205 } components;
206 } ScmIEEEDouble;
207
208 #ifdef DOUBLE_ARMENDIAN
209 /* ARM processor may be configured to use a special mixed endian.
210 We check at runtime. */
211 typedef union {
212 double d;
213 struct {
214 unsigned long mant0:20;
215 unsigned int exp:11;
216 unsigned int sign:1;
217 unsigned long mant1:32;
218 } components;
219 } ScmIEEEDoubleARM;
220 #endif /*DOUBLE_ARMENDIAN*/
221
222 /* ARM special handling */
223 #ifdef DOUBLE_ARMENDIAN
224 static int armendian_p = FALSE;
225
226 #define TEST_DBL 1.9999999999999998 /* all '1' bits for mantissa */
227
228 void check_armendian()
229 {
230 ScmIEEEDouble z;
231 z.d = TEST_DBL;
232 if (z.components.exp != 1023) {
233 ScmIEEEDoubleARM z2;
234 z2.d = TEST_DBL;
235 if (z2.components.exp != 1023) {
236 Scm_Panic("Initiaization failed: Cannot determine double's endian "
237 "on this ARM processor.");
238 }
239 armendian_p = TRUE;
240 } else {
241 armendian_p = FALSE;
242 }
243 }
244 #endif /*DOUBLE_ARMENDIAN*/
245
246 /* This is lazyily initialized, for at the time number.c is initialized,
247 not sufficient infrastructure is booted to initialize a parameter.
248 */
249 static ScmPrimitiveParameter *default_endian = NULL;
250 static ScmInternalMutex default_endian_mutex;
251
252 static void init_default_endian()
253 {
254 if (default_endian == NULL) {
255 SCM_INTERNAL_MUTEX_LOCK(default_endian_mutex);
256 if (default_endian == NULL) {
257 default_endian =
258 Scm_BindPrimitiveParameter(Scm_GaucheModule(), "default-endian",
259 SCM_OBJ(Scm_NativeEndian()), 0);
260
261 }
262 SCM_INTERNAL_MUTEX_UNLOCK(default_endian_mutex);
263 }
264 }
265
266 ScmObj Scm_NativeEndian()
267 {
268 #ifdef DOUBLE_ARMENDIAN
269 if (armendian_p) return SCM_SYM_ARM_LITTLE_ENDIAN;
270 #endif /*DOUBLE_ARMENDIAN*/
271 #if WORDS_BIGENDIAN
272 return SCM_SYM_BIG_ENDIAN;
273 #else
274 return SCM_SYM_LITTLE_ENDIAN;
275 #endif
276 }
277
278 ScmObj Scm_DefaultEndian(void)
279 {
280 init_default_endian();
281 return Scm_PrimitiveParameterRef(Scm_VM(), default_endian);
282 }
283
284 void Scm_SetDefaultEndian(ScmObj endian)
285 {
286 /* We trust the caller passes one of symbols big-endian, little-endian
287 or arm-little-endian. */
288 init_default_endian();
289 Scm_PrimitiveParameterSet(Scm_VM(), default_endian, endian);
290 }
291
292 int Scm_IsBE(ScmObj endian)
293 {
294 return SCM_IS_BE(endian);
295 }
296
297 int Scm_IsLE(ScmObj endian)
298 {
299 return SCM_IS_LE(endian);
300 }
301
302 int Scm_IsArmLE(ScmObj endian)
303 {
304 return SCM_IS_ARM_LE(endian);
305 }
306
307
308 /*=====================================================================
309 * Flonums
310 */
311
312 #undef COUNT_FLONUM_ALLOC
313
314 #ifdef COUNT_FLONUM_ALLOC /* for benchmarks. usually this should be off. */
315 static u_long flonum_count = 0;
316
317 static void report_flonum_count(void *data)
318 {
319 fprintf(stderr, "allocated flonums = %8d\n", flonum_count);
320 }
321 #endif /*COUNT_FLONUM_ALLOC*/
322
323 ScmObj Scm_MakeFlonum(double d)
324 {
325 ScmFlonum *f = SCM_NEW(ScmFlonum);
326 SCM_FLONUM_VALUE(f) = d;
327 #ifdef COUNT_FLONUM_ALLOC
328 flonum_count++;
329 #endif
330 return SCM_MAKE_FLONUM_MEM(f);
331 }
332
333 ScmObj Scm_FlonumIntegerToExact(double d) /* d mustn't have fractional part */
334 {
335 #if SIZEOF_LONG >= 8
336 /* On 64bit machine, double can't exactly represent SCM_SMALL_INT_MIN and
337 SCM_SMALL_INT_MAX, and comparing d with them could pass through
338 out-of-range value, so we convert d to long first. */
339 if (LONG_MIN <= d && d <= LONG_MAX) {
340 long n = (long)d;
341 if (SCM_SMALL_INT_MIN <= n && n <= SCM_SMALL_INT_MAX) {
342 return SCM_MAKE_INT(n);
343 }
344 }
345 /* FALLTHROUGH */
346 #else
347 /* On 32bit machine, double has enough precision to cover small int
348 range. */
349 if (SCM_SMALL_INT_MIN <= d && d <= SCM_SMALL_INT_MAX) {
350 return SCM_MAKE_INT((long)d);
351 }
352 #endif
353 return Scm_MakeBignumFromDouble(d);
354 }
355
356 ScmObj Scm_MakeFlonumToNumber(double d, int exact)
357 {
358 if (exact && !SCM_IS_INF(d)) {
359 /* see if d can be demoted to integer */
360 double i, f;
361 f = modf(d, &i);
362 if (f == 0.0) return Scm_FlonumIntegerToExact(i);
363 /*FALLTHROUGH*/
364 }
365 return Scm_MakeFlonum(d);
366 }
367
368 /*
369 * Flonum decomposition
370 */
371
372 static inline void decode_double(double d,
373 u_long *mant1 SCM_UNUSED,
374 u_long *mant0,
375 int *exp, int *sign)
376 {
377 ScmIEEEDouble dd;
378 #ifdef DOUBLE_ARMENDIAN /* ARM-specific handling */
379 ScmIEEEDoubleARM dd2;
380 if (armendian_p) {
381 dd2.d = d;
382 *mant1 = (u_int)dd2.components.mant1;
383 *mant0 = (u_int)dd2.components.mant0;
384 *exp = dd2.components.exp;
385 *sign = dd2.components.sign;
386 return;
387 }
388 #endif /*DOUBLE_ARMENDIAN*/
389
390 dd.d = d;
391 #if SIZEOF_LONG >= 8
392 *mant0 = dd.components.mant;
393 *exp = dd.components.exp;
394 *sign = dd.components.sign;
395 #else /* SIZEOF_LONG == 4 */
396 *mant1 = (u_int)dd.components.mant1;
397 *mant0 = (u_int)dd.components.mant0;
398 *exp = dd.components.exp;
399 *sign = dd.components.sign;
400 #endif /* SIZEOF_LONG == 4 */
401 }
402
403 /* Decompose flonum D into an integer mantissa F and exponent E, where
404 * -1074 <= E <= 971
405 * 0 <= abs(F) < 2^53
406 * D = F * 2^E
407 * Some special cases:
408 * F = 0, E = 0 if D = 0.0 or -0.0
409 * F = #t if D is infinity (positive or negative)
410 * F = #f if D is NaN.
411 * If D is normalized number (e.g. E > -1074), F >= 2^52.
412 * If D is denormalized number, E == -1074 and F < 2^52
413 * Cf. IEEE 754 Reference
414 * http://babbage.cs.qc.edu/courses/cs341/IEEE-754references.html
415 */
416 ScmObj Scm_DecodeFlonum(double d, int *exp, int *sign)
417 {
418 ScmObj f;
419 u_long mant1, mant0;
420 int exp0, sign0;
421
422 decode_double(d, &mant1, &mant0, &exp0, &sign0);
423
424 *sign = (sign0? -1 : 1);
425
426 /* Check exceptional cases */
427 if (exp0 == 0x7ff) {
428 *exp = 0;
429 if (
430 #if SIZEOF_LONG >= 8
431 mant0 == 0
432 #else /*SIZEOF_LONG < 8*/
433 mant0 == 0 && mant1 == 0
434 #endif /*SIZEOF_LONG < 8*/
435 ) {
436 return SCM_TRUE; /* infinity */
437 } else {
438 return SCM_FALSE; /* NaN */
439 }
440 }
441
442 *exp = (exp0? exp0 - 0x3ff - 52 : -0x3fe - 52);
443
444 #if SIZEOF_LONG >= 8
445 {
446 if (exp0 > 0) mant0 += (1L<<52); /* hidden bit */
447 f = Scm_MakeInteger(mant0);
448 }
449 #else /*SIZEOF_LONG < 8*/
450 {
451 u_long values[2];
452 values[0] = mant1;
453 values[1] = mant0;
454 if (exp0 > 0) values[1] += (1L<<20); /* hidden bit */
455 f = Scm_NormalizeBignum(SCM_BIGNUM(Scm_MakeBignumFromUIArray(1, values, 2)));
456 }
457 #endif /*SIZEOF_LONG < 8*/
458 return f;
459 }
460
461 /* returns -1 or 1. Scm_Sign cannot distinguish 0.0 and -0.0. This one can.
462 signbit(3) is in C99. */
463 int Scm_FlonumSign(double d)
464 {
465 return signbit(d)? -1 : 1;
466 }
467
468 /* Half float support */
469
470 double Scm_HalfToDouble(ScmHalfFloat v)
471 {
472 int e = SCM_HALF_FLOAT_EXPONENT(v);
473 int m = SCM_HALF_FLOAT_MANTISSA(v);
474 int s = SCM_HALF_FLOAT_SIGN_BIT(v);
475 if (e == 31) { /* special */
476 if (m == 0) {
477 if (s) return SCM_DBL_NEGATIVE_INFINITY;
478 else return SCM_DBL_POSITIVE_INFINITY;
479 } else {
480 return SCM_DBL_NAN;
481 }
482 }
483 if (e > 0) { /* normalized */
484 double d = ldexp(1.0 + m/1024.0, e - 15);
485 return s? -d : d;
486 }
487 else { /* denormalized */
488 double d = ldexp(m/1024.0, -14);
489 return s? -d : d;
490 }
491 }
492
493 ScmHalfFloat Scm_DoubleToHalf(double v)
494 {
495 u_long mant1, mant0;
496 int exp0, sign0;
497
498 decode_double(v, &mant1, &mant0, &exp0, &sign0);
499
500 if (exp0 == 0x7ff) { /* special */
501 if (
502 #if SIZEOF_LONG >= 8
503 mant0 == 0
504 #else /*SIZEOF_LONG < 8*/
505 mant0 == 0 && mant1 == 0
506 #endif /*SIZEOF_LONG < 8*/
507 ) {
508 return sign0? 0xfc00 : 0x7c00;
509 } else {
510 return 0x7fff;
511 }
512 }
513 int e = exp0 - 1023 + 15;
514 if (e >= 31) { /* overflow */
515 return sign0? 0xfc00 : 0x7c00;
516 }
517 /* Calculate required mantissa bits. We need upper 10 bits, unless
518 e < 0, in which case we get denormalized number. */
519 int mbits = 10 + ((e <= 0)? e-1 : 0);
520 if (mbits < -1) { /* underflow (-1 for rounding, see below) */
521 return sign0? 0x8000 : 0x0000;
522 }
523 if (e < 0) e = 0;
524 /* Take the mantissa bits. We take one extra bit to perform
525 roudning. R is used to determine whether lower bits are
526 all 0 or not. */
527 #if SIZEOF_LONG >= 8
528 unsigned long m = mant0 >> (52-mbits-1);
529 unsigned long r = mant0 & ((1UL << (52-mbits-1)) - 1);
530 #else /*SIZEOF_LONG < 8*/
531 unsigned long m = mant0 >> (20-mbits-1);
532 unsigned long r = (mant0 & ((1UL << (20-mbits-1)) - 1))|mant1;
533 #endif /*SIZEOF_LONG < 8*/
534 m += 1<<(mbits+1); /* recover hidden bit */
535
536 if (m%2 == 1) {
537 if (r == 0) {
538 /* half point. we round to even */
539 if (m&2) m += 2;
540 } else {
541 m += 2;
542 }
543 }
544
545 /* drop rounding bits */
546 m >>= 1;
547 if (m >= 0x800) {
548 e += 1;
549 m >>= 1;
550 }
551 if (e == 0 && m >= 0x400) {
552 e += 1;
553 m &= ~0x400;
554 }
555 if (e >= 31) { /* overflow by rounding */
556 return sign0? 0xfc00 : 0x7c00;
557 }
558 /* at this point, normalized numbers should get
559 0x400 <= m <= 0x7ff, e > 0, and denormalized numbers should get
560 0 <= m <= 0x3ff, e == 0. So we don't need to treat denormalized
561 specially. */
562 return (ScmHalfFloat)((sign0? 0x8000 : 0x0000)|(e << 10)|(m & 0x3ff));
563 }
564
565 /* Construct a double directly from the given bit patterns. This is
566 an internal procedure; external procedure should use Scm_EncodeFlonum.
567
568 On 64bit architecture, only mant1 is used for mantissa.
569 On 32bit architecture, mant1 is for lower 32bits of mantissa, and
570 lower 20bits of mant0 is used for higher bits.
571 */
572 double Scm__EncodeDouble(u_long mant1,
573 u_long mant0 SCM_UNUSED,
574 int exp, int signbit)
575 {
576 ScmIEEEDouble dd;
577 #ifdef DOUBLE_ARMENDIAN
578 ScmIEEEDoubleARM dd2;
579 if (armendian_p) {
580 dd2.components.mant1 = mant1;
581 dd2.components.mant0 = mant0;
582 dd2.components.exp = exp;
583 dd2.components.sign = signbit;
584 return dd2.d;
585 }
586 #endif /*DOUBLE_ARMENDIAN*/
587
588 dd.components.exp = exp;
589 dd.components.sign = signbit;
590 #if SIZEOF_LONG >= 8
591 dd.components.mant = mant1;
592 #else /*SIZEOF_LONG==4*/
593 dd.components.mant1 = mant1;
594 dd.components.mant0 = mant0;
595 #endif /*SIZEOF_LONG==4*/
596 return dd.d;
597 }
598
599 /* Inverse of Scm_DecodeFlonum.
600 Returns the double representation of S * F * 2^E,
601 where S = 1 | -1,
602 -1074 <= E <= 971
603 2^52 <= F < 2^53 (if E > -1074)
604 or 0 <= F < 2^52 (if E = -1074)
605 NB: If E < -1074, we scale F accordingly until E becomes -1074.
606 */
607 double Scm_EncodeFlonum(ScmObj mant, int exp, int sign)
608 {
609 if (SCM_FALSEP(mant)) return SCM_DBL_NAN;
610 if (SCM_TRUEP(mant)) {
611 if (sign < 0) return SCM_DBL_NEGATIVE_INFINITY;
612 else return SCM_DBL_POSITIVE_INFINITY;
613 }
614
615 int signbit = sign < 0? 1 : 0;
616 if (exp < -1074) {
617 /* scale mantissa */
618 int shift = -1074 - exp;
619 mant = Scm_Ash(mant, -shift);
620 exp = -1074;
621 } else if (exp > 971) {
622 Scm_Error("flonum exponent out of range: %d", exp);
623 }
624
625 uint64_t mant64 = Scm_GetIntegerU64Clamp(mant, SCM_CLAMP_ERROR, NULL);
626 if (!Scm_NumLT(mant, SCM_2_53)) {
627 Scm_Error("flonum mantissa out of range: %S", mant);
628 }
629 if (exp == -1074 && Scm_NumLT(mant, SCM_2_52)) {
630 exp -= 1; /* denormalized range */
631 } else if (Scm_NumLT(mant, SCM_2_52)) {
632 Scm_Error("flonum mantissa out of range: %S", mant);
633 }
634
635 int expfield = exp + 0x3ff + 52;
636 #if SIZEOF_LONG >= 8
637 return Scm__EncodeDouble(mant64, 0, expfield, signbit);
638 #else
639 u_long hi = (mant64 >> 32);
640 u_long lo = (u_long)(mant64 & ULONG_MAX);
641 return Scm__EncodeDouble(lo, hi, expfield, signbit);
642 #endif
643 }
644
645 /*=====================================================================
646 * Ratnums
647 */
648
649 /* possibly returns denomalized number */
650 ScmObj Scm_MakeRatnum(ScmObj numer, ScmObj denom)
651 {
652 if (!SCM_INTEGERP(numer)) {
653 Scm_Error("numerator must be an exact integer, but got %S", numer);
654 }
655 if (!SCM_INTEGERP(denom)) {
656 Scm_Error("denominator must be an exact integer, but got %S", denom);
657 }
658 if (SCM_EXACT_ZERO_P(denom)) {
659 Scm_Error("attempt to calculate a division by zero");
660 }
661 ScmRatnum *r = SCM_NEW(ScmRatnum);
662 SCM_SET_CLASS(r, SCM_CLASS_RATIONAL);
663 r->numerator = numer;
664 r->denominator = denom;
665 return SCM_OBJ(r);
666 }
667
668 #define ENSURE_RATNUM(integer) \
669 SCM_RATNUM(Scm_MakeRatnum(integer, SCM_MAKE_INT(1)))
670
671 ScmObj Scm_MakeRational(ScmObj numer, ScmObj denom)
672 {
673 if (!SCM_INTEGERP(numer)) {
674 Scm_Error("numerator must be an exact integer, but got %S", numer);
675 }
676 if (!SCM_INTEGERP(denom)) {
677 Scm_Error("denominator must be an exact integer, but got %S", denom);
678 }
679 if (SCM_EXACT_ZERO_P(denom)) {
680 Scm_Error("attempt to calculate a division by zero");
681 }
682 if (SCM_EXACT_ONE_P(denom)) return numer;
683 if (SCM_EXACT_ZERO_P(numer)) return SCM_MAKE_INT(0);
684 else return Scm_ReduceRational(Scm_MakeRatnum(numer, denom));
685 }
686
687 ScmObj Scm_Numerator(ScmObj n)
688 {
689 if (SCM_RATNUMP(n)) return SCM_RATNUM_NUMER(n);
690 if (SCM_EXACTP(n)) return n; /* fixnum or bignum */
691 if (!SCM_REALP(n)) SCM_TYPE_ERROR(n, "real number");
692 return Scm_Inexact(Scm_Numerator(Scm_Exact(n)));
693 }
694
695 ScmObj Scm_Denominator(ScmObj n)
696 {
697 if (SCM_RATNUMP(n)) return SCM_RATNUM_DENOM(n);
698 if (SCM_INTEGERP(n)) return SCM_MAKE_INT(1);
699 if (!SCM_REALP(n)) SCM_TYPE_ERROR(n, "real number");
700 return Scm_Inexact(Scm_Denominator(Scm_Exact(n)));
701 }
702
703 ScmObj Scm_ReduceRational(ScmObj rational)
704 {
705 int negated = FALSE;
706
707 if (SCM_INTEGERP(rational)) return rational;
708 if (!SCM_RATNUMP(rational)) {
709 Scm_Error("exact rational number required, but got %S", rational);
710 }
711 ScmObj numer = SCM_RATNUM_NUMER(rational);
712 ScmObj denom = SCM_RATNUM_DENOM(rational);
713
714 if (Scm_Sign(denom) < 0) {
715 numer = Scm_Negate(numer);
716 denom = Scm_Negate(denom);
717 negated = TRUE;
718 }
719
720 /* special cases */
721 if (SCM_EXACT_ONE_P(denom)) return numer;
722 if (SCM_EXACT_ZERO_P(denom)) {
723 int s = Scm_Sign(numer);
724 if (s > 0) return SCM_POSITIVE_INFINITY;
725 if (s < 0) return SCM_NEGATIVE_INFINITY;
726 return SCM_NAN;
727 }
728
729 ScmObj common = Scm_Gcd(numer, denom);
730 if (SCM_EXACT_ONE_P(common)) {
731 if (negated) {
732 return Scm_MakeRatnum(numer, denom);
733 } else {
734 return rational;
735 }
736 } else {
737 numer = Scm_Quotient(numer, common, NULL);
738 denom = Scm_Quotient(denom, common, NULL);
739 if (SCM_EQ(denom, SCM_MAKE_INT(1))) {
740 return numer;
741 } else {
742 return Scm_MakeRatnum(numer, denom);
743 }
744 }
745 }
746
747 /* x, y must be exact numbers */
748 ScmObj Scm_RatnumAddSub(ScmObj x, ScmObj y, int subtract)
749 {
750 ScmObj nx = SCM_RATNUMP(x)? SCM_RATNUM_NUMER(x) : x;
751 ScmObj dx = SCM_RATNUMP(x)? SCM_RATNUM_DENOM(x) : SCM_MAKE_INT(1);
752 ScmObj ny = SCM_RATNUMP(y)? SCM_RATNUM_NUMER(y) : y;
753 ScmObj dy = SCM_RATNUMP(y)? SCM_RATNUM_DENOM(y) : SCM_MAKE_INT(1);
754 ScmObj gcd, dr, nr;
755
756 /* shortcut */
757 if (Scm_NumEq(dx, dy)) {
758 dr = dx;
759 goto finish;
760 }
761
762 if (SCM_EXACT_ONE_P(dx)||SCM_EXACT_ONE_P(dx)) gcd = SCM_MAKE_INT(1);
763 else gcd = Scm_Gcd(dx, dy);
764 if (Scm_NumEq(dx, gcd)) {
765 /* only factor x */
766 nx = Scm_Mul(Scm_Quotient(dy, dx, NULL), nx);
767 dr = dy;
768 goto finish;
769 }
770 if (Scm_NumEq(dy, gcd)) {
771 /* only factor y */
772 ny = Scm_Mul(Scm_Quotient(dx, dy, NULL), ny);
773 dr = dx;
774 goto finish;
775 }
776
777 /* general case */
778 ScmObj fx = Scm_Quotient(dx, gcd, NULL);
779 ScmObj fy = Scm_Quotient(dy, gcd, NULL);
780 nx = Scm_Mul(nx, fy);
781 ny = Scm_Mul(ny, fx);
782 dr = Scm_Mul(dx, fy);
783 finish:
784 nr = (subtract? Scm_Sub(nx, ny) : Scm_Add(nx, ny));
785 return Scm_MakeRational(nr, dr);
786 }
787
788 ScmObj Scm_RatnumMulDiv(ScmObj x, ScmObj y, int divide)
789 {
790 ScmObj nx = SCM_RATNUMP(x)? SCM_RATNUM_NUMER(x) : x;
791 ScmObj dx = SCM_RATNUMP(x)? SCM_RATNUM_DENOM(x) : SCM_MAKE_INT(1);
792 ScmObj ny = SCM_RATNUMP(y)? SCM_RATNUM_NUMER(y) : y;
793 ScmObj dy = SCM_RATNUMP(y)? SCM_RATNUM_DENOM(y) : SCM_MAKE_INT(1);
794
795 if (divide) {
796 ScmObj t = ny; ny = dy; dy = t;
797 }
798 return Scm_MakeRational(Scm_Mul(nx, ny),
799 Scm_Mul(dx, dy));
800 }
801
802 #define Scm_RatnumAdd(x, y) Scm_RatnumAddSub(x, y, FALSE)
803 #define Scm_RatnumSub(x, y) Scm_RatnumAddSub(x, y, TRUE)
804 #define Scm_RatnumMul(x, y) Scm_RatnumMulDiv(x, y, FALSE)
805 #define Scm_RatnumDiv(x, y) Scm_RatnumMulDiv(x, y, TRUE)
806
807
808 /*=======================================================================
809 * Compnums
810 */
811
812 ScmObj Scm_MakeCompnum(double r, double i)
813 {
814 ScmCompnum *c = SCM_NEW_ATOMIC(ScmCompnum);
815 SCM_SET_CLASS(c, SCM_CLASS_COMPLEX);
816 c->real = r;
817 c->imag = i;
818 return SCM_OBJ(c);
819 }
820
821 ScmObj Scm_MakeComplex(double r, double i)
822 {
823 if (i == 0.0) return Scm_MakeFlonum(r);
824 else return Scm_MakeCompnum(r, i);
825 }
826
827 ScmObj Scm_MakeComplexPolar(double mag, double angle)
828 {
829 double real = mag * cos(angle);
830 double imag = mag * sin(angle);
831 if (imag == 0.0) return Scm_MakeFlonum(real);
832 else return Scm_MakeCompnum(real, imag);
833 }
834
835 ScmObj Scm_MakeComplexPolarPI(double mag, double pi_angle)
836 {
837 double real = mag * Scm_CosPi(pi_angle);
838 double imag = mag * Scm_SinPi(pi_angle);
839 if (imag == 0.0) return Scm_MakeFlonum(real);
840 else return Scm_MakeCompnum(real, imag);
841 }
842
843 /* NB: This isn't called by Scheme's real-part; see libnum.scm */
844 double Scm_RealPart(ScmObj z)
845 {
846 if (SCM_REALP(z)) {
847 return Scm_GetDouble(z);
848 }
849 if (!SCM_COMPNUMP(z)) {
850 Scm_Error("number required, but got %S", z);
851 return 0.0; /* dummy */
852 }
853 return SCM_COMPNUM_REAL(z);
854 }
855
856 /* NB: This isn't called by Scheme's imag-part; see libnum.scm */
857 double Scm_ImagPart(ScmObj z)
858 {
859 if (SCM_COMPNUMP(z)) {
860 return SCM_COMPNUM_IMAG(z);
861 }
862 if (!SCM_REALP(z)) {
863 Scm_Error("number required, but got %S", z);
864 }
865 return 0.0;
866 }
867
868 ScmHalfComplex Scm_GetHalfComplex(ScmObj z)
869 {
870 ScmHalfComplex c = {0, 0};
871 if (SCM_COMPNUMP(z)) {
872 c.r = Scm_DoubleToHalf(SCM_COMPNUM_REAL(z));
873 c.i = Scm_DoubleToHalf(SCM_COMPNUM_IMAG(z));
874 } else if (SCM_REALP(z)) {
875 c.r = Scm_DoubleToHalf(Scm_GetDouble(z));
876 c.i = 0;
877 } else {
878 Scm_Error("number required, but got %S", z);
879 }
880 return c;
881 }
882
883 ScmFloatComplex Scm_GetFloatComplex(ScmObj z)
884 {
885 ScmFloatComplex c = 0.0f;
886 if (SCM_COMPNUMP(z)) {
887 c = (float)SCM_COMPNUM_REAL(z)
888 + (float)SCM_COMPNUM_IMAG(z) * _Complex_I;
889 } else if (SCM_REALP(z)) {
890 c = (float)Scm_GetDouble(z);
891 } else {
892 Scm_Error("number required, but got %S", z);
893 }
894 return c;
895 }
896
897 ScmDoubleComplex Scm_GetDoubleComplex(ScmObj z)
898 {
899 ScmDoubleComplex c = 0.0f;
900 if (SCM_COMPNUMP(z)) {
901 c = SCM_COMPNUM_REAL(z)
902 + SCM_COMPNUM_IMAG(z) * _Complex_I;
903 } else if (SCM_REALP(z)) {
904 c = Scm_GetDouble(z);
905 } else {
906 Scm_Error("number required, but got %S", z);
907 }
908 return c;
909 }
910
911 ScmObj Scm_HalfComplexToComplex(ScmHalfComplex z)
912 {
913 return Scm_MakeComplex(Scm_HalfToDouble(z.r),
914 Scm_HalfToDouble(z.i));
915 }
916
917 ScmObj Scm_FloatComplexToComplex(ScmFloatComplex z)
918 {
919 return Scm_MakeComplex((double)crealf(z), (double)cimagf(z));
920 }
921
922 ScmObj Scm_DoubleComplexToComplex(ScmDoubleComplex z)
923 {
924 return Scm_MakeComplex(creal(z), cimag(z));
925 }
926
927
928 /* NB: This isn't called by Scheme's magnitude; see libnum.scm */
929 double Scm_Magnitude(ScmObj z)
930 {
931 if (SCM_REALP(z)) {
932 return fabs(Scm_GetDouble(z));
933 }
934 if (!SCM_COMPNUMP(z)) {
935 Scm_Error("number required, but got %S", z);
936 return 0.0; /* dummy */
937 }
938 double r = SCM_COMPNUM_REAL(z);
939 double i = SCM_COMPNUM_IMAG(z);
940 return sqrt(r*r+i*i);
941 }
942
943 double Scm_Angle(ScmObj z)
944 {
945 if (SCM_REALP(z)) {
946 return (Scm_Sign(z) < 0)? M_PI : 0.0;
947 }
948 if (!SCM_COMPNUMP(z)) {
949 Scm_Error("number required, but got %S", z);
950 return 0.0; /* dummy */
951 }
952 double r = SCM_COMPNUM_REAL(z);
953 double i = SCM_COMPNUM_IMAG(z);
954 return atan2(i, r);
955 }
956
957 /*=======================================================================
958 * Coertion
959 */
960
961 ScmObj Scm_MakeInteger(long i)
962 {
963 if (i >= SCM_SMALL_INT_MIN && i <= SCM_SMALL_INT_MAX) {
964 return SCM_MAKE_INT(i);
965 } else {
966 return Scm_MakeBignumFromSI(i);
967 }
968 }
969
970 ScmObj Scm_MakeIntegerU(u_long i)
971 {
972 if (i <= (u_long)SCM_SMALL_INT_MAX) return SCM_MAKE_INT(i);
973 else return Scm_MakeBignumFromUI(i);
974 }
975
976 ScmObj Scm_MakeIntegerFromUIArray(int sign,
977 const u_long *values,
978 int size)
979 {
980 ScmBignum *b = SCM_BIGNUM(Scm_MakeBignumFromUIArray(sign, values, size));
981 return Scm_NormalizeBignum(b);
982 }
983
984 static void range_error(ScmObj obj, int clamp, int *oor)
985 {
986 if (clamp != SCM_CLAMP_ERROR && oor != NULL) {
987 *oor = TRUE;
988 } else {
989 Scm_Error("argument out of range: %S", obj);
990 }
991 }
992
993 /* Convert scheme integer to C integer */
994 long Scm_GetIntegerClamp(ScmObj obj, int clamp, int *oor)
995 {
996 double v = 0.0;
997 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
998 if (SCM_INTP(obj)) return SCM_INT_VALUE(obj);
999 else if (SCM_BIGNUMP(obj)) {
1000 return Scm_BignumToSI(SCM_BIGNUM(obj), clamp, oor);
1001 }
1002 else if (SCM_FLONUMP(obj)) {
1003 v = SCM_FLONUM_VALUE(obj);
1004 goto flonum;
1005 }
1006 else if (SCM_RATNUMP(obj)) {
1007 v = Scm_GetDouble(obj);
1008 goto flonum;
1009 }
1010 else {
1011 goto err;
1012 }
1013 flonum:
1014 if (v > (double)LONG_MAX) {
1015 if (clamp & SCM_CLAMP_HI) return LONG_MAX;
1016 else goto err;
1017 }
1018 if (v < (double)LONG_MIN) {
1019 if (clamp & SCM_CLAMP_LO) return LONG_MIN;
1020 else goto err;
1021 }
1022 return (long)v;
1023 err:
1024 range_error(obj, clamp, oor);
1025 return 0;
1026 }
1027
1028 u_long Scm_GetIntegerUClamp(ScmObj obj, int clamp, int *oor)
1029 {
1030 double v = 0.0;
1031
1032 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
1033 if (SCM_INTP(obj)) {
1034 if (SCM_INT_VALUE(obj) < 0) {
1035 if (clamp & SCM_CLAMP_LO) return 0;
1036 else goto err;
1037 }
1038 return SCM_INT_VALUE(obj);
1039 }
1040 else if (SCM_BIGNUMP(obj)) {
1041 return Scm_BignumToUI(SCM_BIGNUM(obj), clamp, oor);
1042 }
1043 else if (SCM_FLONUMP(obj)) {
1044 v = SCM_FLONUM_VALUE(obj);
1045 goto flonum;
1046 }
1047 else if (SCM_RATNUMP(obj)) {
1048 v = Scm_GetDouble(obj);
1049 goto flonum;
1050 }
1051 else {
1052 goto err;
1053 }
1054 flonum:
1055 if (v > (double)ULONG_MAX) {
1056 if (clamp & SCM_CLAMP_HI) return ULONG_MAX;
1057 else goto err;
1058 }
1059 if (v < 0.0) {
1060 if (clamp & SCM_CLAMP_LO) return 0;
1061 else goto err;
1062 }
1063 return (u_long)v;
1064 err:
1065 range_error(obj, clamp, oor);
1066 return 0;
1067 }
1068
1069 /* 8- and 16-bit integer extraction with range check */
1070 #define SMALL_INT_XTRACT(name, upper, lower) \
1071 name(ScmObj obj, int clamp, int *oor) \
1072 { \
1073 long n = 0; \
1074 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE; \
1075 if (SCM_INTP(obj)) { \
1076 n = SCM_INT_VALUE(obj); \
1077 } else if (SCM_FLONUMP(obj)) { \
1078 n = (long)SCM_FLONUM_VALUE(obj); \
1079 } else if (SCM_RATNUMP(obj)) { \
1080 n = (long)Scm_GetDouble(obj); \
1081 } else if (SCM_BIGNUMP(obj)) { \
1082 if (Scm_Sign(obj) > 0) { \
1083 if (clamp & SCM_CLAMP_HI) return upper; \
1084 else goto err; \
1085 } else { \
1086 if (clamp & SCM_CLAMP_LO) return lower; \
1087 else goto err; \
1088 } \
1089 } else { \
1090 goto err; \
1091 } \
1092 if (n > upper) { \
1093 if (clamp & SCM_CLAMP_HI) return upper; \
1094 else goto err; \
1095 } \
1096 if (n < lower) { \
1097 if (clamp & SCM_CLAMP_LO) return lower; \
1098 else goto err; \
1099 } \
1100 return n; \
1101 err: \
1102 range_error(obj, clamp, oor); \
1103 return 0; \
1104 }
1105
1106 SMALL_INT_XTRACT(int Scm_GetInteger8Clamp, 127, -128)
1107 SMALL_INT_XTRACT(u_int Scm_GetIntegerU8Clamp, 255, 0)
1108 SMALL_INT_XTRACT(int Scm_GetInteger16Clamp, 32767, -32768)
1109 SMALL_INT_XTRACT(u_int Scm_GetIntegerU16Clamp, 65535, 0)
1110
1111
1112 /* 32bit integer specific */
1113 int32_t Scm_GetInteger32Clamp(ScmObj obj, int clamp, int *oor)
1114 {
1115 #if SIZEOF_LONG == 4
1116 return (int32_t)Scm_GetIntegerClamp(obj, clamp, oor);
1117 #else /* SIZEOF_LONG >= 8 */
1118
1119 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
1120 /* NB: we denote the constant directly here. (1L<<31) fails on
1121 Alpha machines, since the compiler somehow calculates the constant
1122 in 32bit integer even it has 'L'. We have to write (1LL<<31), but
1123 I'm afraid that it's not portable. */
1124 if (SCM_INTP(obj)) {
1125 long r = SCM_INT_VALUE(obj);
1126 if (r < -0x80000000L) {
1127 if (clamp & SCM_CLAMP_LO) return -0x80000000L;
1128 goto err;
1129 }
1130 if (r > 0x7fffffffL) {
1131 if (clamp & SCM_CLAMP_HI) return 0x7fffffffL;
1132 goto err;
1133 }
1134 return r;
1135 } else if (SCM_BIGNUMP(obj)) {
1136 if (SCM_BIGNUM_SIGN(obj) < 0) {
1137 if (clamp & SCM_CLAMP_LO) return -0x80000000L;
1138 goto err;
1139 } else {
1140 if (clamp & SCM_CLAMP_HI) return 0x7fffffffL;
1141 goto err;
1142 }
1143 }
1144 /*TODO: flonum and ratnum! */
1145 err:
1146 range_error(obj, clamp, oor);
1147 return 0;
1148 #endif /* SIZEOF_LONG >= 8 */
1149 }
1150
1151 uint32_t Scm_GetIntegerU32Clamp(ScmObj obj, int clamp, int *oor)
1152 {
1153 #if SIZEOF_LONG == 4
1154 return (uint32_t)Scm_GetIntegerUClamp(obj, clamp, oor);
1155 #else /* SIZEOF_LONG >= 8 */
1156 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
1157 if (SCM_INTP(obj)) {
1158 long r = SCM_INT_VALUE(obj);
1159 if (r < 0) {
1160 if (clamp & SCM_CLAMP_LO) return 0;
1161 goto err;
1162 }
1163 if (r > 0xffffffffL) {
1164 if (clamp & SCM_CLAMP_HI) return 0xffffffffUL;
1165 goto err;
1166 }
1167 return r;
1168 } else if (SCM_BIGNUMP(obj)) {
1169 if (SCM_BIGNUM_SIGN(obj) < 0) {
1170 if (clamp & SCM_CLAMP_LO) return 0;
1171 goto err;
1172 } else {
1173 if (clamp & SCM_CLAMP_HI) return 0xffffffffUL;
1174 goto err;
1175 }
1176 }
1177 err:
1178 range_error(obj, clamp, oor);
1179 return 0;
1180 #endif /* SIZEOF_LONG >= 8 */
1181 }
1182
1183 /* get an unsigned integer value modulo u_long range.
1184 convenient when you only concern lower bits. */
1185 u_long Scm_GetIntegerUMod(ScmObj obj)
1186 {
1187 if (SCM_INTP(obj)) return (u_long)SCM_INT_VALUE(obj);
1188 if (SCM_BIGNUMP(obj)) {
1189 if (SCM_BIGNUM_SIZE(obj) == 0) {
1190 /* this shouldn't happen in normalized bignums, but just in case */
1191 return 0;
1192 }
1193 if (SCM_BIGNUM_SIGN(obj) < 0) {
1194 u_long v = SCM_BIGNUM(obj)->values[0];
1195 return ~v + 1;
1196 } else {
1197 return SCM_BIGNUM(obj)->values[0];
1198 }
1199 }
1200 Scm_Error("Exact integer required, but got %S", obj);
1201 return 0; /* dummy */
1202 }
1203
1204 #if SIZEOF_LONG == 4
1205 /* we need special routines */
1206 ScmObj Scm_MakeInteger64(int64_t i)
1207 {
1208 u_long val[2];
1209 val[0] = (u_long)((uint64_t)i & ULONG_MAX);
1210 val[1] = (u_long)((uint64_t)i >> 32);
1211 if (val[1] == 0 && val[0] <= LONG_MAX) return Scm_MakeInteger(val[0]);
1212 return Scm_NormalizeBignum(SCM_BIGNUM(Scm_MakeBignumFromUIArray(0, val, 2)));
1213 }
1214
1215 ScmObj Scm_MakeIntegerU64(uint64_t i)
1216 {
1217 u_long val[2];
1218 val[0] = (u_long)((uint64_t)i & ULONG_MAX);
1219 val[1] = (u_long)((uint64_t)i >> 32);
1220 if (val[1] == 0) return Scm_MakeIntegerU(val[0]);
1221 return Scm_MakeBignumFromUIArray(1, val, 2);
1222 }
1223
1224 int64_t Scm_GetInteger64Clamp(ScmObj obj, int clamp, int *oor)
1225 {
1226 int64_t r = 0;
1227 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
1228 if (SCM_INTP(obj)) return (int64_t)SCM_INT_VALUE(obj);
1229 if (SCM_BIGNUMP(obj)) {
1230 return Scm_BignumToSI64(SCM_BIGNUM(obj), clamp, oor);
1231 }
1232 if (SCM_RATNUMP(obj)) {
1233 obj = Scm_Inexact(obj);
1234 /* FALLTHROUGH */
1235 }
1236 if (SCM_FLONUMP(obj)) {
1237 int64_t maxval, minval;
1238 double v;
1239
1240 maxval = INT64_MAX;
1241 minval = INT64_MIN;
1242 v = SCM_FLONUM_VALUE(obj);
1243 if (v > (double)maxval) {
1244 if (!(clamp&SCM_CLAMP_HI)) goto err;
1245 return maxval;
1246 } else if (v < (double)minval) {
1247 if (!(clamp&SCM_CLAMP_LO)) goto err;
1248 return minval;
1249 } else {
1250 return (int64_t)v;
1251 }
1252 }
1253 err:
1254 range_error(obj, clamp, oor);
1255 return r;
1256 }
1257
1258 uint64_t Scm_GetIntegerU64Clamp(ScmObj obj, int clamp, int *oor)
1259 {
1260 uint64_t r = 0;
1261 if (clamp == SCM_CLAMP_NONE && oor != NULL) *oor = FALSE;
1262 if (SCM_INTP(obj)) {
1263 long v = SCM_INT_VALUE(obj);
1264 if (v < 0) {
1265 if (!(clamp&SCM_CLAMP_LO)) goto err;
1266 return 0;
1267 } else {
1268 return (uint64_t)v;
1269 }
1270 }
1271 if (SCM_BIGNUMP(obj)) {
1272 return Scm_BignumToUI64(SCM_BIGNUM(obj), clamp, oor);
1273 }
1274 if (SCM_RATNUMP(obj)) {
1275 obj = Scm_Inexact(obj);
1276 /* FALLTHROUGH */
1277 }
1278 if (SCM_FLONUMP(obj)) {
1279 double v = SCM_FLONUM_VALUE(obj);
1280 uint64_t maxval;
1281
1282 if (v < 0) {
1283 if (!(clamp&SCM_CLAMP_LO)) goto err;
1284 return 0;
1285 }
1286 maxval = UINT64_MAX;
1287 if (v > (double)maxval) {
1288 if (!(clamp&SCM_CLAMP_HI)) goto err;
1289 return maxval;
1290 } else {
1291 return (uint64_t)v;
1292 }
1293 }
1294 err:
1295 range_error(obj, clamp, oor);
1296 return r;
1297 }
1298
1299 #endif /* SIZEOF_LONG == 4 */
1300
1301 #if GAUCHE_API_VERSION < 98
1302 /* Since we adopt C99, we can simply use cast instead of the funcitons.
1303 These are kept for ABI compatibility until 1.0 release */
1304 int64_t Scm_DoubleToInt64(double v)
1305 {
1306 return (int64_t)v;
1307 }
1308
1309 uint64_t Scm_DoubleToUInt64(double v)
1310 {
1311 return (uint64_t)v;
1312 }
1313
1314 double Scm_Int64ToDouble(int64_t v)
1315 {
1316 return (double)v;
1317 }
1318
1319 double Scm_UInt64ToDouble(uint64_t v)
1320 {
1321 return (double)v;
1322 }
1323 #endif /*GAUCHE_API_VERSION < 98*/
1324
1325 /* See if a Scheme integer si can be representable with 53bit mantissa.
1326 Also store the highest and lowest bit posisions in *hi and *lo
1327 (if they're not NULL) */
1328 static int double_precision(ScmObj si, int *phi, int *plo)
1329 {
1330 if (SCM_INTP(si)) {
1331 ScmSmallInt i = SCM_INT_VALUE(si);
1332 if (i < 0) i = -i; /* won't overflow */
1333 ScmBits bi = (ScmBits)i;
1334 int hi = Scm_BitsHighest1(&bi, 0, SCM_WORD_BITS);
1335 int lo = Scm_BitsLowest1(&bi, 0, SCM_WORD_BITS);
1336 if (phi) *phi = hi;
1337 if (plo) *plo = lo;
1338 return (hi - lo) < 53;
1339 } else {
1340 SCM_ASSERT(SCM_BIGNUMP(si));
1341 const ScmBits *bits = (ScmBits*)SCM_BIGNUM(si)->values;
1342 int hi = Scm_BitsHighest1(bits, 0, SCM_BIGNUM_SIZE(si)*SCM_WORD_BITS);
1343 int lo = Scm_BitsLowest1(bits, 0, SCM_BIGNUM_SIZE(si)*SCM_WORD_BITS);
1344 if (phi) *phi = hi;
1345 if (plo) *plo = lo;
1346 return (hi - lo) < 53;
1347 }
1348 }
1349
1350 /* Get n-th bit of absolute value of Scheme integer si */
1351 static int abs_bittest(ScmObj si, int bit)
1352 {
1353 if (SCM_INTP(si)) {
1354 ScmSmallInt i = SCM_INT_VALUE(si);
1355 if (i < 0) i = -i;
1356 return i & (1L<<bit);
1357 } else {
1358 SCM_ASSERT(SCM_BIGNUMP(si));
1359 ScmBits *bits = (ScmBits*)SCM_BIGNUM(si)->values;
1360 return SCM_BITS_TEST(bits, bit);
1361 }
1362 }
1363
1364 double Scm_GetDouble(ScmObj obj)
1365 {
1366 if (SCM_FLONUMP(obj)) return SCM_FLONUM_VALUE(obj);
1367 else if (SCM_INTP(obj)) return (double)SCM_INT_VALUE(obj);
1368 else if (SCM_BIGNUMP(obj)) return Scm_BignumToDouble(SCM_BIGNUM(obj));
1369 else if (SCM_RATNUMP(obj)) {
1370 /* This is more subtle than it appears. A naive approach is to
1371 convert numerator and denominator to double, and do flonum division.
1372 However,
1373 - Denominator and/or numerator may exceed FLT_MAX, yielding
1374 infinities in the intermediate results. However, their ratio
1375 can be in a valid flonum range.
1376 - If denominator and/or numerator requires more than 53bit precision,
1377 converting each to double causes rounding, which occurs before
1378 the final division, causing ULP-off error.
1379 E.g. (inexact (/ (+ 1 (* (exact (flonum-epsilon)) 33/100)) 1))
1380 should be 1, but would yield 1.0000000000000002 if the numerator
1381 is rounded up first.
1382 */
1383 ScmObj numer = SCM_RATNUM_NUMER(obj);
1384 ScmObj denom = SCM_RATNUM_DENOM(obj);
1385
1386 int n_hi, n_lo, d_hi, d_lo;
1387 int n_dp = double_precision(numer, &n_hi, &n_lo);
1388 int d_dp = double_precision(denom, &d_hi, &d_lo);
1389
1390 if (!(n_dp && d_dp)) goto fullpath;
1391
1392 double dnumer = Scm_GetDouble(numer);
1393 double ddenom = Scm_GetDouble(denom);
1394
1395 if (!SCM_IS_INF(dnumer) && !SCM_IS_INF(ddenom)) {
1396 /* short path */
1397 volatile double result;
1398 SCM_FP_ENSURE_DOUBLE_PRECISION_BEGIN();
1399 /* It is critical to perform this division in IEEE double (53bit
1400 mantissa) precision, _not_ in x87 extended double precision;
1401 if the latter were used, double-rounding would yield different
1402 results, which makes inexact -> exact -> inexact round-trip
1403 fail. For example, (inexact 3002399751580332/3002399751580331)
1404 should be 1.0000000000000002 (1LSB greater than 1.0), but
1405 extended double precision division yields
1406 1.0000000000000004 (2LSB greater than 1.0).
1407 */
1408 result = dnumer/ddenom;
1409 SCM_FP_ENSURE_DOUBLE_PRECISION_END();
1410 return result;
1411 }
1412 fullpath:;
1413 /* Need more precise but expensive calculation.
1414 We find K such that 2^K * numer >= 2^54 * denom, so that
1415 the integer division yields more than 53bit integral part.
1416 */
1417 int shift = 0;
1418 if (n_hi - d_hi < 54) {
1419 shift = 54 - (n_hi - d_hi);
1420 numer = Scm_Ash(numer, shift);
1421 }
1422
1423 ScmObj rem;
1424 ScmObj quo = Scm_Quotient(numer, denom, &rem);
1425
1426 /* If shift > 1076, the result would be denomarlized range.
1427 Less than 53bits of quo is used, so we have to mask out the
1428 unncessary digit. (Otherwise, it causes double-rounding.) */
1429 if (shift > 1076) {
1430 ScmObj mask =
1431 Scm_LogNot(Scm_Sub(Scm_Ash(SCM_MAKE_INT(1), shift-1076-1),
1432 SCM_MAKE_INT(1)));
1433 if (Scm_Sign(quo) < 0) {
1434 quo = Scm_Negate(Scm_LogAnd(Scm_Negate(quo), mask));
1435 } else {
1436 quo = Scm_LogAnd(quo, mask);
1437 }
1438 }
1439
1440 int q_hi, q_lo;
1441 if (double_precision(quo, &q_hi, &q_lo)) {
1442 /* Result fits in double precision. */
1443 double dquo = Scm_GetDouble(quo);
1444 return ldexp(dquo, -shift);
1445 }
1446 /* We have to look at the 54th bit and below to decide rounding.
1447 If 54-th bit is 0, we can safely convert it to double, truncating
1448 the lower bits. */
1449 if (!abs_bittest(quo, q_hi - 53)) {
1450 double dquo = Scm_GetDouble(quo);
1451 return ldexp(dquo, -shift);
1452 }
1453 /* If 54-th bit is 1, we see the lower bits. If we have at least
1454 one '1' bit, or remainder isn't zero, we can round up. */
1455 int roundup = FALSE;
1456 ScmObj mask = Scm_Ash(SCM_MAKE_INT(1), q_hi - 53);
1457 if (rem != SCM_MAKE_INT(0)) roundup = TRUE;
1458 else {
1459 ScmObj mask_1 = Scm_Sub(mask, SCM_MAKE_INT(1));
1460 ScmObj q = quo;
1461 if (Scm_Sign(q) < 0) {
1462 q = Scm_Negate(q);
1463 }
1464 if (Scm_LogAnd(q, mask_1) != SCM_MAKE_INT(0)) roundup = TRUE;
1465 }
1466 if (roundup) {
1467 if (Scm_Sign(quo) < 0) {
1468 quo = Scm_Sub(quo, mask);
1469 } else {
1470 quo = Scm_Add(quo, mask);
1471 }
1472 double dquo = Scm_GetDouble(quo);
1473 return ldexp(dquo, -shift);
1474 }
1475 /* We are half-point. See the 53-bit and round to even. */
1476 if (!abs_bittest(quo, q_hi - 52)) {
1477 if (Scm_Sign(quo) < 0) {
1478 quo = Scm_Add(quo, mask);
1479 } else {
1480 quo = Scm_Sub(quo, mask);
1481 }
1482 }
1483 double dquo = Scm_GetDouble(quo);
1484 return ldexp(dquo, -shift);
1485 }
1486 else return 0.0;
1487 }
1488
1489 /*
1490 * Generic Methods
1491 */
1492
1493 /* Predicates */
1494
1495 int Scm_IntegerP(ScmObj obj)
1496 {
1497 if (SCM_INTP(obj) || SCM_BIGNUMP(obj)) return TRUE;
1498 if (SCM_RATNUMP(obj)) return FALSE; /* normalized ratnum never be integer */
1499 if (SCM_FLONUMP(obj)) {
1500 double d = SCM_FLONUM_VALUE(obj);
1501 if (SCM_IS_INF(d) || SCM_IS_NAN(d)) return FALSE;
1502 double i;
1503 double f = modf(d, &i);
1504 if (f == 0.0) return TRUE;
1505 return FALSE;
1506 }
1507 if (SCM_COMPNUMP(obj)) return FALSE;
1508 Scm_Error("number required, but got %S", obj);
1509 return FALSE; /* dummy */
1510 }
1511
1512 int Scm_OddP(ScmObj obj)
1513 {
1514 if (SCM_INTP(obj)) {
1515 return (SCM_INT_VALUE(obj)&1);
1516 }
1517 if (SCM_BIGNUMP(obj)) {
1518 return (SCM_BIGNUM(obj)->values[0] & 1);
1519 }
1520 if (SCM_FLONUMP(obj) && Scm_IntegerP(obj)) {
1521 return (fmod(SCM_FLONUM_VALUE(obj), 2.0) != 0.0);
1522 }
1523 Scm_Error("integer required, but got %S", obj);
1524 return FALSE; /* dummy */
1525
1526 }
1527
1528 int Scm_FiniteP(ScmObj obj)
1529 {
1530 return !Scm_InfiniteP(obj) && !Scm_NanP(obj);
1531 }
1532
1533 int Scm_InfiniteP(ScmObj obj)
1534 {
1535 if (SCM_FLONUMP(obj)) {
1536 double v = SCM_FLONUM_VALUE(obj);
1537 return SCM_IS_INF(v);
1538 } else if (SCM_COMPNUMP(obj)) {
1539 double r = SCM_COMPNUM_REAL(obj);
1540 double i = SCM_COMPNUM_IMAG(obj);
1541 return SCM_IS_INF(r) || SCM_IS_INF(i);
1542 } else if (!SCM_NUMBERP(obj)) {
1543 SCM_TYPE_ERROR(obj, "number");
1544 }
1545 return FALSE;
1546 }
1547
1548 int Scm_NanP(ScmObj obj)
1549 {
1550 if (SCM_FLONUMP(obj)) {
1551 double v = SCM_FLONUM_VALUE(obj);
1552 return SCM_IS_NAN(v);
1553 } else if (SCM_COMPNUMP(obj)) {
1554 double r = SCM_COMPNUM_REAL(obj);
1555 double i = SCM_COMPNUM_IMAG(obj);
1556 return SCM_IS_NAN(r) || SCM_IS_NAN(i);
1557 } else if (!SCM_NUMBERP(obj)) {
1558 SCM_TYPE_ERROR(obj, "number");
1559 }
1560 return FALSE;
1561 }
1562
1563 /* Unary Operator */
1564
1565 static ScmObj scm_abs(ScmObj obj, int vmp)
1566 {
1567 if (SCM_INTP(obj)) {
1568 long v = SCM_INT_VALUE(obj);
1569 if (v < 0) {
1570 if (v == SCM_SMALL_INT_MIN) {
1571 obj = Scm_MakeBignumFromSI(-v);
1572 } else {
1573 obj = SCM_MAKE_INT(-v);
1574 }
1575 }
1576 } else if (SCM_BIGNUMP(obj)) {
1577 if (SCM_BIGNUM_SIGN(obj) < 0) {
1578 obj = Scm_BignumCopy(SCM_BIGNUM(obj));
1579 SCM_BIGNUM_SIGN(obj) = 1;
1580 }
1581 } else if (SCM_FLONUMP(obj)) {
1582 double v = SCM_FLONUM_VALUE(obj);
1583 if (signbit(v)) RETURN_FLONUM(-v);
1584 } else if (SCM_RATNUMP(obj)) {
1585 if (Scm_Sign(SCM_RATNUM_NUMER(obj)) < 0) {
1586 obj = Scm_MakeRational(Scm_Negate(SCM_RATNUM_NUMER(obj)),
1587 SCM_RATNUM_DENOM(obj));
1588 }
1589 } else if (SCM_COMPNUMP(obj)) {
1590 double r = SCM_COMPNUM_REAL(obj);
1591 double i = SCM_COMPNUM_IMAG(obj);
1592 double a = sqrt(r*r+i*i);
1593 RETURN_FLONUM(a);
1594 } else {
1595 Scm_Error("number required: %S", obj);
1596 }
1597 return obj;
1598 }
1599 DEFINE_DUAL_API1(Scm_Abs, Scm_VMAbs, scm_abs)
1600
1601 /* Return -1, 0 or 1 when arg is minus, zero or plus, respectively.
1602 used to implement zero?, positive? and negative?
1603 NB: This returns 0 for both positive and negative zeros. */
1604 int Scm_Sign(ScmObj obj)
1605 {
1606 if (SCM_INTP(obj)) {
1607 long r = SCM_INT_VALUE(obj);
1608 if (r == 0) return 0;
1609 return (r > 0)? 1 : -1;
1610 }
1611 if (SCM_BIGNUMP(obj)) {
1612 return SCM_BIGNUM_SIGN(obj);
1613 }
1614 if (SCM_FLONUMP(obj)) {
1615 double v = SCM_FLONUM_VALUE(obj);
1616 if (v == 0.0) return 0;
1617 return (v > 0.0)? 1 : -1;
1618 }
1619 if (SCM_RATNUMP(obj)) {
1620 return Scm_Sign(SCM_RATNUM_NUMER(obj));
1621 }
1622 /* NB: zero? can accept a complex number, but it is processed in
1623 the stub function. see libnum.scm */
1624 Scm_Error("real number required, but got %S", obj);
1625 return 0; /* dummy */
1626 }
1627
1628 static ScmObj negate(ScmObj obj, int vmp)
1629 {
1630 if (SCM_INTP(obj)) {
1631 long v = SCM_INT_VALUE(obj);
1632 if (v == SCM_SMALL_INT_MIN) {
1633 return Scm_MakeBignumFromSI(-v);
1634 } else {
1635 return SCM_MAKE_INT(-v);
1636 }
1637 } else if (SCM_BIGNUMP(obj)) {
1638 return Scm_BignumNegate(SCM_BIGNUM(obj));
1639 } else if (SCM_FLONUMP(obj)) {
1640 double r = -SCM_FLONUM_VALUE(obj);
1641 RETURN_FLONUM(r);
1642 } else if (SCM_RATNUMP(obj)) {
1643 return Scm_MakeRational(Scm_Negate(SCM_RATNUM_NUMER(obj)),
1644 SCM_RATNUM_DENOM(obj));
1645 } else if (SCM_COMPNUMP(obj)) {
1646 return Scm_MakeCompnum(-SCM_COMPNUM_REAL(obj),
1647 -SCM_COMPNUM_IMAG(obj));
1648 } else {
1649 return Scm_ApplyRec(SCM_OBJ(&generic_sub), SCM_LIST1(obj));
1650 }
1651 }
1652 DEFINE_DUAL_API1(Scm_Negate, Scm_VMNegate, negate)
1653
1654
1655 static ScmObj reciprocal(ScmObj obj, int vmp)
1656 {
1657 if (SCM_INTP(obj) || SCM_BIGNUMP(obj)) {
1658 return Scm_MakeRational(SCM_MAKE_INT(1), obj);
1659 } else if (SCM_FLONUMP(obj)) {
1660 double val = 1.0/SCM_FLONUM_VALUE(obj);
1661 RETURN_FLONUM(val);
1662 } else if (SCM_RATNUMP(obj)) {
1663 return Scm_MakeRational(SCM_RATNUM_DENOM(obj),
1664 SCM_RATNUM_NUMER(obj));
1665 } else if (SCM_COMPNUMP(obj)) {
1666 double r = SCM_COMPNUM_REAL(obj);
1667 double i = SCM_COMPNUM_IMAG(obj);
1668 double d = r*r + i*i;
1669 double r1 = r/d;
1670 double i1 = -i/d;
1671 return Scm_MakeComplex(r1, i1);
1672 } else {
1673 return Scm_ApplyRec(SCM_OBJ(&generic_div), SCM_LIST1(obj));
1674 }
1675 }
1676 DEFINE_DUAL_API1(Scm_Reciprocal, Scm_VMReciprocal, reciprocal)
1677
1678
1679 static ScmObj ireciprocal(ScmObj obj, int vmp)
1680 {
1681 if (SCM_EXACT_ZERO_P(obj)) return SCM_POSITIVE_INFINITY;
1682 if (SCM_EXACT_ONE_P(obj)) return obj;
1683 if (SCM_REALP(obj)) {
1684 double z = 1.0/Scm_GetDouble(obj);
1685 RETURN_FLONUM(z);
1686 }
1687 // delegate the rest to exact reciprocal
1688 return reciprocal(obj, vmp);
1689 }
1690 DEFINE_DUAL_API1(Scm_ReciprocalInexact, Scm_VMReciprocalInexact, ireciprocal)
1691
1692
1693 /*
1694 * Conversion operators
1695 */
1696
1697 static ScmObj inexact(ScmObj obj, int vmp)
1698 {
1699 if (SCM_INTP(obj)) {
1700 double z = (double)SCM_INT_VALUE(obj);
1701 RETURN_FLONUM(z);
1702 } else if (SCM_BIGNUMP(obj)) {
1703 double z = Scm_BignumToDouble(SCM_BIGNUM(obj));
1704 RETURN_FLONUM(z);
1705 } else if (SCM_RATNUMP(obj)) {
1706 RETURN_FLONUM(Scm_GetDouble(obj));
1707 } else if (!SCM_FLONUMP(obj) && !SCM_COMPNUMP(obj)) {
1708 Scm_Error("number required: %S", obj);
1709 }
1710 return obj;
1711 }
1712 DEFINE_DUAL_API1(Scm_Inexact, Scm_VMInexact, inexact)
1713
1714
1715 ScmObj Scm_Exact(ScmObj obj)
1716 {
1717 if (SCM_FLONUMP(obj)) {
1718 double d = SCM_FLONUM_VALUE(obj);
1719 double f, i;
1720 if (SCM_IS_NAN(d) || SCM_IS_INF(d)) {
1721 Scm_Error("Exact infinity/nan is not supported: %S", obj);
1722 }
1723 if ((f = modf(d, &i)) == 0.0) {
1724 obj = Scm_FlonumIntegerToExact(i);
1725 } else {
1726 /* We'd find out the simplest rational numebr within the precision
1727 of IEEE double floating point number. The actual code is in
1728 lib/gauche/numerical.scm. */
1729 static ScmObj real_to_rational = SCM_UNDEFINED;
1730 SCM_BIND_PROC(real_to_rational, "real->rational",
1731 Scm_GaucheModule());
1732 obj = Scm_ApplyRec1(real_to_rational, obj);
1733 }
1734 } else if (SCM_COMPNUMP(obj)) {
1735 Scm_Error("exact complex is not supported: %S", obj);
1736 } if (!SCM_EXACTP(obj)) {
1737 Scm_Error("number required: %S", obj);
1738 }
1739 return obj;
1740 }
1741
1742 /*===============================================================
1743 * Arithmetics
1744 */
1745
1746 /* NB: we used to support n-ary operations in C API, expecting
1747 them to be faster since we can carry around the intermediate
1748 results unboxed. The newer versions of compiler, however,
1749 decomposes n-ary arithmetic operations into binary ones
1750 during optimization, so n-ary API hadn't really been used much.
1751 So we dropped them, in favor of simple code. */
1752
1753 /*
1754 * Addition and subtraction
1755 */
1756
1757 static ScmObj scm_add(ScmObj arg0, ScmObj arg1, int vmp)
1758 {
1759 if (SCM_INTP(arg0)) {
1760 if (SCM_INTP(arg1)) {
1761 long r = SCM_INT_VALUE(arg0) + SCM_INT_VALUE(arg1);
1762 return Scm_MakeInteger(r);
1763 }
1764 if (SCM_BIGNUMP(arg1)) {
1765 if (SCM_EXACT_ZERO_P(arg0)) return arg1;
1766 return Scm_BignumAddSI(SCM_BIGNUM(arg1), SCM_INT_VALUE(arg0));
1767 }
1768 if (SCM_RATNUMP(arg1)) {
1769 if (SCM_EXACT_ZERO_P(arg0)) return arg1;
1770 return Scm_RatnumAdd(arg0, arg1);
1771 }
1772 if (SCM_FLONUMP(arg1)) {
1773 if (SCM_EXACT_ZERO_P(arg0)) return arg1;
1774 double z = (double)SCM_INT_VALUE(arg0) + SCM_FLONUM_VALUE(arg1);
1775 RETURN_FLONUM(z);
1776 }
1777 if (SCM_COMPNUMP(arg1)) {
1778 if (SCM_EXACT_ZERO_P(arg0)) return arg1;
1779 return Scm_MakeComplex((double)SCM_INT_VALUE(arg0)
1780 + SCM_COMPNUM_REAL(arg1),
1781 SCM_COMPNUM_IMAG(arg1));
1782 }
1783 /* fallback to generic */
1784 }
1785 else if (SCM_BIGNUMP(arg0)) {
1786 if (SCM_INTP(arg1)) {
1787 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1788 return Scm_BignumAddSI(SCM_BIGNUM(arg0), SCM_INT_VALUE(arg1));
1789 }
1790 if (SCM_BIGNUMP(arg1)) {
1791 return Scm_BignumAdd(SCM_BIGNUM(arg0), SCM_BIGNUM(arg1));
1792 }
1793 if (SCM_RATNUMP(arg1)) {
1794 return Scm_RatnumAdd(arg0, arg1);
1795 }
1796 if (SCM_FLONUMP(arg1)) {
1797 double z = Scm_GetDouble(arg0) + SCM_FLONUM_VALUE(arg1);
1798 RETURN_FLONUM(z);
1799 }
1800 if (SCM_COMPNUMP(arg1)) {
1801 return Scm_MakeComplex(Scm_GetDouble(arg0)
1802 + SCM_COMPNUM_REAL(arg1),
1803 SCM_COMPNUM_IMAG(arg1));
1804 }
1805 /* fallback to generic */
1806 }
1807 else if (SCM_RATNUMP(arg0)) {
1808 if (SCM_INTP(arg1)) {
1809 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1810 return Scm_RatnumAdd(arg0, arg1);
1811 }
1812 if (SCM_BIGNUMP(arg1)||SCM_RATNUMP(arg1)) {
1813 return Scm_RatnumAdd(arg0, arg1);
1814 }
1815 if (SCM_FLONUMP(arg1)) {
1816 double z = Scm_GetDouble(arg0) + SCM_FLONUM_VALUE(arg1);
1817 RETURN_FLONUM(z);
1818 }
1819 if (SCM_COMPNUMP(arg1)) {
1820 return Scm_MakeComplex(Scm_GetDouble(arg0)
1821 + SCM_COMPNUM_REAL(arg1),
1822 SCM_COMPNUM_IMAG(arg1));
1823 }
1824 /* fallback to generic */
1825 }
1826 else if (SCM_FLONUMP(arg0)) {
1827 if (SCM_INTP(arg1)) {
1828 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1829 double z = SCM_FLONUM_VALUE(arg0) + (double)SCM_INT_VALUE(arg1);
1830 RETURN_FLONUM(z);
1831 }
1832 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
1833 double z = SCM_FLONUM_VALUE(arg0) + Scm_GetDouble(arg1);
1834 RETURN_FLONUM(z);
1835 }
1836 if (SCM_FLONUMP(arg1)) {
1837 if (SCM_FLONUM_VALUE(arg0) == 0.0) return arg1;
1838 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg0;
1839 double z = SCM_FLONUM_VALUE(arg0) + SCM_FLONUM_VALUE(arg1);
1840 RETURN_FLONUM(z);
1841 }
1842 if (SCM_COMPNUMP(arg1)) {
1843 if (SCM_FLONUM_VALUE(arg0) == 0.0) return arg1;
1844 return Scm_MakeComplex(SCM_FLONUM_VALUE(arg0)
1845 + SCM_COMPNUM_REAL(arg1),
1846 SCM_COMPNUM_IMAG(arg1));
1847 }
1848 /* fallback to generic */
1849 }
1850 else if (SCM_COMPNUMP(arg0)) {
1851 if (SCM_INTP(arg1)) {
1852 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1853 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1854 + (double)SCM_INT_VALUE(arg1),
1855 SCM_COMPNUM_IMAG(arg0));
1856 }
1857 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
1858 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1859 + Scm_GetDouble(arg1),
1860 SCM_COMPNUM_IMAG(arg0));
1861 }
1862 if (SCM_FLONUMP(arg1)) {
1863 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg0;
1864 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1865 + SCM_FLONUM_VALUE(arg1),
1866 SCM_COMPNUM_IMAG(arg0));
1867 }
1868 if (SCM_COMPNUMP(arg1)) {
1869 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1870 + SCM_COMPNUM_REAL(arg1),
1871 SCM_COMPNUM_IMAG(arg0)
1872 + SCM_COMPNUM_IMAG(arg1));
1873 }
1874 /* fallback to generic */
1875 }
1876 /* object-+ handling */
1877 SCM_FLONUM_ENSURE_MEM(arg0);
1878 SCM_FLONUM_ENSURE_MEM(arg1);
1879 return Scm_ApplyRec(SCM_OBJ(&generic_add), SCM_LIST2(arg0, arg1));
1880 }
1881 DEFINE_DUAL_API2(Scm_Add, Scm_VMAdd, scm_add)
1882
1883
1884 static ScmObj scm_sub(ScmObj arg0, ScmObj arg1, int vmp)
1885 {
1886 if (SCM_INTP(arg0)) {
1887 if (SCM_INTP(arg1)) {
1888 long r = SCM_INT_VALUE(arg0) - SCM_INT_VALUE(arg1);
1889 return Scm_MakeInteger(r);
1890 }
1891 if (SCM_BIGNUMP(arg1)) {
1892 ScmObj big = Scm_MakeBignumFromSI(SCM_INT_VALUE(arg0));
1893 return Scm_BignumSub(SCM_BIGNUM(big), SCM_BIGNUM(arg1));
1894 }
1895 if (SCM_RATNUMP(arg1)) {
1896 return Scm_RatnumSub(arg0, arg1);
1897 }
1898 if (SCM_FLONUMP(arg1)) {
1899 double z = (double)SCM_INT_VALUE(arg0) - SCM_FLONUM_VALUE(arg1);
1900 RETURN_FLONUM(z);
1901 }
1902 if (SCM_COMPNUMP(arg1)) {
1903 return Scm_MakeComplex((double)SCM_INT_VALUE(arg0)
1904 - SCM_COMPNUM_REAL(arg1),
1905 - SCM_COMPNUM_IMAG(arg1));
1906 }
1907 /* fallback to generic */
1908 }
1909 if (SCM_BIGNUMP(arg0)) {
1910 if (SCM_INTP(arg1)) {
1911 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1912 return Scm_BignumSubSI(SCM_BIGNUM(arg0), SCM_INT_VALUE(arg1));
1913 }
1914 if (SCM_BIGNUMP(arg1)) {
1915 return Scm_BignumSub(SCM_BIGNUM(arg0), SCM_BIGNUM(arg1));
1916 }
1917 if (SCM_RATNUMP(arg1)) {
1918 return Scm_RatnumSub(arg0, arg1);
1919 }
1920 if (SCM_FLONUMP(arg1)) {
1921 double z = Scm_GetDouble(arg0) - SCM_FLONUM_VALUE(arg1);
1922 RETURN_FLONUM(z);
1923 }
1924 if (SCM_COMPNUMP(arg1)) {
1925 return Scm_MakeComplex(Scm_GetDouble(arg0)
1926 - SCM_COMPNUM_REAL(arg1),
1927 - SCM_COMPNUM_IMAG(arg1));
1928 }
1929 /* fallback to generic */
1930 }
1931 if (SCM_RATNUMP(arg0)) {
1932 if (SCM_INTP(arg1)) {
1933 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1934 return Scm_RatnumSub(arg0, arg1);
1935 }
1936 if (SCM_BIGNUMP(arg1)||SCM_RATNUMP(arg1)) {
1937 return Scm_RatnumSub(arg0, arg1);
1938 }
1939 if (SCM_FLONUMP(arg1)) {
1940 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg0;
1941 double z = Scm_GetDouble(arg0) - SCM_FLONUM_VALUE(arg1);
1942 RETURN_FLONUM(z);
1943 }
1944 if (SCM_COMPNUMP(arg1)) {
1945 return Scm_MakeComplex(Scm_GetDouble(arg0)
1946 - SCM_COMPNUM_REAL(arg1),
1947 - SCM_COMPNUM_IMAG(arg1));
1948 }
1949 /* fallback to generic */
1950 }
1951 if (SCM_FLONUMP(arg0)) {
1952 if (SCM_INTP(arg1)) {
1953 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1954 double z = SCM_FLONUM_VALUE(arg0) - (double)SCM_INT_VALUE(arg1);
1955 RETURN_FLONUM(z);
1956 }
1957 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
1958 double z = SCM_FLONUM_VALUE(arg0) - Scm_GetDouble(arg1);
1959 RETURN_FLONUM(z);
1960 }
1961 if (SCM_FLONUMP(arg1)) {
1962 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg0;
1963 double z = SCM_FLONUM_VALUE(arg0) - SCM_FLONUM_VALUE(arg1);
1964 RETURN_FLONUM(z);
1965 }
1966 if (SCM_COMPNUMP(arg1)) {
1967 return Scm_MakeComplex(SCM_FLONUM_VALUE(arg0)
1968 - SCM_COMPNUM_REAL(arg1),
1969 - SCM_COMPNUM_IMAG(arg1));
1970 }
1971 /* fallback to generic */
1972 }
1973 if (SCM_COMPNUMP(arg0)) {
1974 if (SCM_INTP(arg1)) {
1975 if (SCM_EXACT_ZERO_P(arg1)) return arg0;
1976 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1977 - (double)SCM_INT_VALUE(arg1),
1978 SCM_COMPNUM_IMAG(arg0));
1979 }
1980 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
1981 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1982 - Scm_GetDouble(arg1),
1983 SCM_COMPNUM_IMAG(arg0));
1984 }
1985 if (SCM_FLONUMP(arg1)) {
1986 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg0;
1987 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1988 - Scm_GetDouble(arg1),
1989 SCM_COMPNUM_IMAG(arg0));
1990 }
1991 if (SCM_COMPNUMP(arg1)) {
1992 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
1993 - SCM_COMPNUM_REAL(arg1),
1994 SCM_COMPNUM_IMAG(arg0)
1995 - SCM_COMPNUM_IMAG(arg1));
1996 }
1997 /* fallback to generic */
1998 }
1999 /* object-- handling */
2000 return Scm_ApplyRec(SCM_OBJ(&generic_sub), SCM_LIST2(arg0, arg1));
2001 }
2002 DEFINE_DUAL_API2(Scm_Sub, Scm_VMSub, scm_sub)
2003
2004 /*
2005 * Multiplication
2006 */
2007
2008 static ScmObj scm_mul(ScmObj arg0, ScmObj arg1, int vmp)
2009 {
2010 if (SCM_INTP(arg0)) {
2011 if (SCM_INTP(arg1)) {
2012 long v0 = SCM_INT_VALUE(arg0);
2013 long v1 = SCM_INT_VALUE(arg1);
2014 long k;
2015 int ov;
2016 /* Using SMULOV to detect overflow portably. */
2017 SMULOV(k, ov, v0, v1);
2018 if (ov || !SCM_SMALL_INT_FITS(k)) {
2019 ScmObj big = Scm_MakeBignumFromSI(v0);
2020 return Scm_BignumMulSI(SCM_BIGNUM(big), v1);
2021 } else {
2022 return Scm_MakeInteger(k);
2023 }
2024 }
2025 if (SCM_BIGNUMP(arg1)) {
2026 if (SCM_EXACT_ZERO_P(arg0)) return arg0;
2027 if (SCM_EQ(arg0, SCM_MAKE_INT(1))) return arg1;
2028 return Scm_BignumMulSI(SCM_BIGNUM(arg1), SCM_INT_VALUE(arg0));
2029 }
2030 if (SCM_RATNUMP(arg1)) {
2031 if (SCM_EXACT_ZERO_P(arg0)) return arg0;
2032 if (SCM_EQ(arg0, SCM_MAKE_INT(1))) return arg1;
2033 return Scm_RatnumMul(arg0, arg1);
2034 }
2035 if (SCM_FLONUMP(arg1)) {
2036 if (SCM_EXACT_ZERO_P(arg0)) return arg0;
2037 if (SCM_EQ(arg0, SCM_MAKE_INT(1))) return arg1;
2038 double z = (double)SCM_INT_VALUE(arg0) * SCM_FLONUM_VALUE(arg1);
2039 RETURN_FLONUM(z);
2040 }
2041 if (SCM_COMPNUMP(arg1)) {
2042 if (SCM_EXACT_ZERO_P(arg0)) return arg0;
2043 if (SCM_EQ(arg0, SCM_MAKE_INT(1))) return arg1;
2044 return Scm_MakeComplex((double)SCM_INT_VALUE(arg0)
2045 * SCM_COMPNUM_REAL(arg1),
2046 (double)SCM_INT_VALUE(arg0)
2047 * SCM_COMPNUM_IMAG(arg1));
2048 }
2049 /* fallback to generic */
2050 }
2051 if (SCM_BIGNUMP(arg0)) {
2052 if (SCM_INTP(arg1)) {
2053 if (SCM_EXACT_ZERO_P(arg1)) return arg1;
2054 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2055 return Scm_BignumMulSI(SCM_BIGNUM(arg0), SCM_INT_VALUE(arg1));
2056 }
2057 if (SCM_BIGNUMP(arg1)) {
2058 return Scm_BignumMul(SCM_BIGNUM(arg0), SCM_BIGNUM(arg1));
2059 }
2060 if (SCM_RATNUMP(arg1)) {
2061 return Scm_RatnumMul(arg0, arg1);
2062 }
2063 if (SCM_FLONUMP(arg1)) {
2064 double z = Scm_GetDouble(arg0) * SCM_FLONUM_VALUE(arg1);
2065 RETURN_FLONUM(z);
2066 }
2067 if (SCM_COMPNUMP(arg1)) {
2068 double z = Scm_GetDouble(arg0);
2069 return Scm_MakeComplex(z * SCM_COMPNUM_REAL(arg1),
2070 z * SCM_COMPNUM_IMAG(arg1));
2071 }
2072 /* fallback to generic */
2073 }
2074 if (SCM_RATNUMP(arg0)) {
2075 if (SCM_INTP(arg1)) {
2076 if (SCM_EXACT_ZERO_P(arg1)) return arg1;
2077 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2078 return Scm_RatnumMul(arg0, arg1);
2079 }
2080 if (SCM_BIGNUMP(arg1)||SCM_RATNUMP(arg1)) {
2081 return Scm_RatnumMul(arg0, arg1);
2082 }
2083 if (SCM_FLONUMP(arg1)) {
2084 if (SCM_FLONUM_VALUE(arg1) == 0.0) return arg1;
2085 double z = Scm_GetDouble(arg0) * SCM_FLONUM_VALUE(arg1);
2086 RETURN_FLONUM(z);
2087 }
2088 if (SCM_COMPNUMP(arg1)) {
2089 return Scm_MakeComplex(Scm_GetDouble(arg0)
2090 * SCM_COMPNUM_REAL(arg1),
2091 Scm_GetDouble(arg0)
2092 * SCM_COMPNUM_IMAG(arg1));
2093 }
2094 /* fallback to generic */
2095 }
2096 if (SCM_FLONUMP(arg0)) {
2097 if (SCM_INTP(arg1)) {
2098 /* inexact number * exact zero makes exact zero */
2099 if (SCM_EXACT_ZERO_P(arg1)) return arg1;
2100 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2101 double z = SCM_FLONUM_VALUE(arg0) * (double)SCM_INT_VALUE(arg1);
2102 RETURN_FLONUM(z);
2103 }
2104 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
2105 RETURN_FLONUM(SCM_FLONUM_VALUE(arg0) * Scm_GetDouble(arg1));
2106 }
2107 if (SCM_FLONUMP(arg1)) {
2108 if (SCM_FLONUM_VALUE(arg1) == 1.0) return arg0;
2109 RETURN_FLONUM(SCM_FLONUM_VALUE(arg0) * SCM_FLONUM_VALUE(arg1));
2110 }
2111 if (SCM_COMPNUMP(arg1)) {
2112 return Scm_MakeComplex(SCM_FLONUM_VALUE(arg0)
2113 * SCM_COMPNUM_REAL(arg1),
2114 SCM_FLONUM_VALUE(arg0)
2115 * SCM_COMPNUM_IMAG(arg1));
2116 }
2117 /* fallback to generic */
2118 }
2119 if (SCM_COMPNUMP(arg0)) {
2120 if (SCM_INTP(arg1)) {
2121 if (SCM_EXACT_ZERO_P(arg1)) return arg1;
2122 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2123 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
2124 * (double)SCM_INT_VALUE(arg1),
2125 SCM_COMPNUM_IMAG(arg0)
2126 * (double)SCM_INT_VALUE(arg1));
2127 }
2128 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
2129 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
2130 * Scm_GetDouble(arg1),
2131 SCM_COMPNUM_IMAG(arg0)
2132 * Scm_GetDouble(arg1));
2133 }
2134 if (SCM_FLONUMP(arg1)) {
2135 if (SCM_FLONUM_VALUE(arg1) == 1.0) return arg0;
2136 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)
2137 * SCM_FLONUM_VALUE(arg1),
2138 SCM_COMPNUM_IMAG(arg0)
2139 * SCM_FLONUM_VALUE(arg1));
2140 }
2141 if (SCM_COMPNUMP(arg1)) {
2142 double r0 = SCM_COMPNUM_REAL(arg0);
2143 double i0 = SCM_COMPNUM_IMAG(arg0);
2144 double r1 = SCM_COMPNUM_REAL(arg1);
2145 double i1 = SCM_COMPNUM_IMAG(arg1);
2146 return Scm_MakeComplex(r0 * r1 - i0 * i1,
2147 r0 * i1 + r1 * i0);
2148 }
2149 /* fallback to generic */
2150 }
2151 SCM_FLONUM_ENSURE_MEM(arg0);
2152 SCM_FLONUM_ENSURE_MEM(arg1);
2153 return Scm_ApplyRec(SCM_OBJ(&generic_mul), SCM_LIST2(arg0, arg1));
2154 }
2155 DEFINE_DUAL_API2(Scm_Mul, Scm_VMMul, scm_mul)
2156
2157 /*
2158 * Division
2159 */
2160
2161 /* We have three flavors of division API.
2162 * - Scm_Div : Scheme's `/'. Exact division produces exact result (maybe
2163 * rational)
2164 * - Scm_DivInexact : Scheme's `/.'. The result is always inexact. Fast.
2165 * - Scm_DivCompat : Scheme's `inexact-/'. This is only for the backward
2166 * compatibility, and probably we'll drop this in 1.0.
2167 * It works as Scm_Div, except that when Scm_Div produces ratnum,
2168 * Scm_DivCompat produces flonum.
2169 * There are also two 'VM' API, which can be used if you're returning
2170 * the value directly to the VM.
2171 * - Scm_VMDiv : The 'VM' version of Scm_Div.
2172 * - Scm_VMDivInexact : The 'VM' version of Scm_DivInexact.
2173 *
2174 * All these flavors are handled by a single function scm_div, with
2175 * three flags specifying the behavior.
2176 *
2177 * inexact compat vmp
2178 * Scm_Div FALSE FALSE FALSE
2179 * Scm_DivInexact TRUE FALSE FALSE
2180 * Scm_DivCompat d/c TRUE FALSE
2181 * Scm_VMDiv FALSE FALSE TRUE
2182 * Scm_VMDivInexact TRUE FALSE TRUE
2183 */
2184
2185 static ScmObj
2186 scm_div(ScmObj arg0, ScmObj arg1, int inexact, int compat, int vmp)
2187 {
2188 ScmObj r = SCM_UNBOUND;
2189
2190 #define SIMPLE_RETURN(x) do { r = (x); goto simple_return; } while (0)
2191
2192 if (SCM_INTP(arg0)) {
2193 if (SCM_INTP(arg1)) {
2194 if (SCM_EXACT_ZERO_P(arg1)) {
2195 if (inexact) goto anormal;
2196 else goto div_by_zero;
2197 }
2198 if (SCM_EXACT_ZERO_P(arg0)) SIMPLE_RETURN(arg0);
2199 if (SCM_EXACT_ONE_P(arg1)) SIMPLE_RETURN(arg0);
2200 if (compat) {
2201 if (SCM_INT_VALUE(arg0)%SCM_INT_VALUE(arg1) == 0) {
2202 long q = SCM_INT_VALUE(arg0)/SCM_INT_VALUE(arg1);
2203 return Scm_MakeInteger(q);
2204 } else {
2205 double z = (double)SCM_INT_VALUE(arg0)
2206 / (double)SCM_INT_VALUE(arg1);
2207 RETURN_FLONUM(z);
2208 }
2209 } else if (inexact) {
2210 double z = Scm_GetDouble(arg0)/Scm_GetDouble(arg1);
2211 RETURN_FLONUM(z);
2212 } else {
2213 return Scm_MakeRational(arg0, arg1);
2214 }
2215 }
2216 if (SCM_BIGNUMP(arg1)) {
2217 if (SCM_EXACT_ZERO_P(arg0)) SIMPLE_RETURN(arg0);
2218 goto ratnum_return;
2219 }
2220 if (SCM_RATNUMP(arg1)) {
2221 arg0 = Scm_Mul(arg0, SCM_RATNUM_DENOM(arg1));
2222 arg1 = SCM_RATNUM_NUMER(arg1);
2223 goto ratnum_return;
2224 }
2225 if (SCM_FLONUMP(arg1)) {
2226 if (SCM_FLONUM_VALUE(arg1) == 0.0) goto anormal;
2227 RETURN_FLONUM(SCM_INT_VALUE(arg0)/SCM_FLONUM_VALUE(arg1));
2228 }
2229 if (SCM_COMPNUMP(arg1)) {
2230 goto do_complex;
2231 }
2232 /* fallback to generic */
2233 }
2234 if (SCM_BIGNUMP(arg0)) {
2235 if (SCM_INTP(arg1)) {
2236 if (SCM_EXACT_ZERO_P(arg1)) {
2237 if (inexact) goto anormal;
2238 else goto div_by_zero;
2239 }
2240 if (SCM_EXACT_ONE_P(arg1)) SIMPLE_RETURN(arg0);
2241 goto ratnum_return;
2242 }
2243 if (SCM_BIGNUMP(arg1)) {
2244 goto ratnum_return;
2245 }
2246 if (SCM_RATNUMP(arg1)) {
2247 arg0 = Scm_Mul(arg0, SCM_RATNUM_DENOM(arg1));
2248 arg1 = SCM_RATNUM_NUMER(arg1);
2249 goto ratnum_return;
2250 }
2251 if (SCM_FLONUMP(arg1)) {
2252 if (SCM_FLONUM_VALUE(arg1) == 0.0) goto anormal;
2253 RETURN_FLONUM(Scm_GetDouble(arg0)/SCM_FLONUM_VALUE(arg1));
2254 }
2255 if (SCM_COMPNUMP(arg1)) {
2256 goto do_complex;
2257 }
2258 /* fallback to generic */
2259 }
2260 if (SCM_RATNUMP(arg0)) {
2261 if (SCM_INTP(arg1)) {
2262 if (SCM_EXACT_ZERO_P(arg1)) {
2263 if (inexact) goto anormal;
2264 else goto div_by_zero;
2265 }
2266 if (SCM_EXACT_ONE_P(arg1)) SIMPLE_RETURN(arg0);
2267 arg1 = Scm_Mul(SCM_RATNUM_DENOM(arg0), arg1);
2268 arg0 = SCM_RATNUM_NUMER(arg0);
2269 goto ratnum_return;
2270 }
2271 if (SCM_BIGNUMP(arg1)) {
2272 arg1 = Scm_Mul(SCM_RATNUM_DENOM(arg0), arg1);
2273 arg0 = SCM_RATNUM_NUMER(arg0);
2274 goto ratnum_return;
2275 }
2276 if (SCM_RATNUMP(arg1)) {
2277 if (!compat && !inexact) {
2278 return Scm_RatnumDiv(arg0, arg1);
2279 } else {
2280 ScmObj numer = Scm_Mul(SCM_RATNUM_NUMER(arg0),
2281 SCM_RATNUM_DENOM(arg1));
2282 ScmObj denom = Scm_Mul(SCM_RATNUM_DENOM(arg0),
2283 SCM_RATNUM_NUMER(arg1));
2284 arg0 = numer;
2285 arg1 = denom;
2286 goto ratnum_return;
2287 }
2288 }
2289 if (SCM_FLONUMP(arg1)) {
2290 if (SCM_FLONUM_VALUE(arg1) == 0.0) goto anormal;
2291 RETURN_FLONUM(Scm_GetDouble(arg0)/SCM_FLONUM_VALUE(arg1));
2292 }
2293 if (SCM_COMPNUMP(arg1)) {
2294 goto do_complex;
2295 }
2296 /* fallback to generic */
2297 }
2298 if (SCM_FLONUMP(arg0)) {
2299 if (SCM_INTP(arg1)) {
2300 if (SCM_IS_NAN(SCM_FLONUM_VALUE(arg0))) return SCM_NAN;
2301 if (SCM_EXACT_ZERO_P(arg1)) goto anormal;
2302 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2303 RETURN_FLONUM(SCM_FLONUM_VALUE(arg0)/SCM_INT_VALUE(arg1));
2304 }
2305 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
2306 RETURN_FLONUM(SCM_FLONUM_VALUE(arg0)/Scm_GetDouble(arg1));
2307 }
2308 if (SCM_FLONUMP(arg1)) {
2309 if (SCM_IS_NAN(SCM_FLONUM_VALUE(arg0))) return SCM_NAN;
2310 if (SCM_FLONUM_VALUE(arg1) == 0.0) goto anormal;
2311 RETURN_FLONUM(SCM_FLONUM_VALUE(arg0)/SCM_FLONUM_VALUE(arg1));
2312 }
2313 if (SCM_COMPNUMP(arg1)) {
2314 goto do_complex;
2315 }
2316 /* fallback to generic */
2317 }
2318 if (SCM_COMPNUMP(arg0)) {
2319 if (SCM_INTP(arg1)) {
2320 /* NB: Gauche has no exact compnum */
2321 if (SCM_EXACT_ZERO_P(arg1)) goto anormal_comp;
2322 if (SCM_EXACT_ONE_P(arg1)) return arg0;
2323 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)/SCM_INT_VALUE(arg1),
2324 SCM_COMPNUM_IMAG(arg0)/SCM_INT_VALUE(arg1));
2325 }
2326 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
2327 double z = Scm_GetDouble(arg1);
2328 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)/z,
2329 SCM_COMPNUM_IMAG(arg0)/z);
2330 }
2331 if (SCM_FLONUMP(arg1)) {
2332 if (SCM_FLONUM_VALUE(arg1) == 0.0) goto anormal_comp;
2333 return Scm_MakeComplex(SCM_COMPNUM_REAL(arg0)/SCM_FLONUM_VALUE(arg1),
2334 SCM_COMPNUM_IMAG(arg0)/SCM_FLONUM_VALUE(arg1));
2335 }
2336 if (SCM_COMPNUMP(arg1)) {
2337 double r0 = SCM_COMPNUM_REAL(arg0);
2338 double i0 = SCM_COMPNUM_IMAG(arg0);
2339 double r1 = SCM_COMPNUM_REAL(arg1);
2340 double i1 = SCM_COMPNUM_IMAG(arg1);
2341 double d = r1*r1+i1*i1;
2342 return Scm_MakeComplex((r0*r1 + i0*i1)/d,
2343 (i0*r1 - r0*i1)/d);
2344 }
2345 /* fallback to generic */
2346 }
2347 SCM_FLONUM_ENSURE_MEM(arg0);
2348 SCM_FLONUM_ENSURE_MEM(arg1);
2349 return Scm_ApplyRec(SCM_OBJ(&generic_div), SCM_LIST2(arg0, arg1));
2350
2351 ratnum_return:
2352 {
2353 /* arg0 and arg1 contains exact numbers.*/
2354 if (compat) goto compat_return;
2355 if (inexact) goto inexact_return;
2356 return Scm_MakeRational(arg0, arg1);
2357 }
2358 compat_return:
2359 {
2360 /* We have exact integer division arg0/arg1 (arg1 != 0).
2361 If it doesn't produce a whole integer, we coerce the
2362 result to flonum. */
2363 ScmObj rem;
2364 ScmObj q = Scm_Quotient(arg0, arg1, &rem);
2365 if (SCM_EXACT_ZERO_P(rem)) {
2366 return q;
2367 }
2368 /*FALLTHROUGH*/
2369 }
2370 inexact_return:
2371 {
2372 double numer = Scm_GetDouble(arg0);
2373 double denom = Scm_GetDouble(arg1);
2374 if (SCM_IS_INF(numer) || SCM_IS_INF(denom)) {
2375 /* special path - we need more sophisticated calculaton. */
2376 ScmObj r = Scm_MakeRational(arg0, arg1);
2377 RETURN_FLONUM(Scm_GetDouble(r));
2378 } else {
2379 RETURN_FLONUM(numer/denom);
2380 }
2381 }
2382 simple_return:
2383 {
2384 if (inexact) return Scm_Inexact(r);
2385 else return r;
2386 }
2387 div_by_zero:
2388 {
2389 Scm_Error("attempt to calculate a division by zero");
2390 }
2391 anormal:
2392 /* real inexact division by zero */
2393 {
2394 int s0 = Scm_Sign(arg0);
2395 int s1 = SCM_FLONUMP(arg1)? Scm_FlonumSign(SCM_FLONUM_VALUE(arg1)) : 1;
2396 if (s0 == 0) return SCM_NAN;
2397 if (s0*s1 < 0) return SCM_NEGATIVE_INFINITY;
2398 else return SCM_POSITIVE_INFINITY;
2399 }
2400 anormal_comp:
2401 /* complex inexact division by zero */
2402 {
2403 double r0 = SCM_COMPNUM_REAL(arg0);
2404 double i0 = SCM_COMPNUM_IMAG(arg0);
2405 int s1 = SCM_FLONUMP(arg1)? Scm_FlonumSign(SCM_FLONUM_VALUE(arg1)) : 1;
2406 double r =
2407 SCM_IS_NAN(r0) ? SCM_DBL_NAN
2408 : ((r0*s1 > 0.0) ? SCM_DBL_POSITIVE_INFINITY
2409 : ((r0*s1 < 0.0) ? SCM_DBL_NEGATIVE_INFINITY
2410 : SCM_DBL_NAN));
2411 double i =
2412 SCM_IS_NAN(i0) ? SCM_DBL_NAN
2413 : ((i0*s1 > 0.0) ? SCM_DBL_POSITIVE_INFINITY
2414 : ((i0*s1 < 0.0) ? SCM_DBL_NEGATIVE_INFINITY
2415 : SCM_DBL_NAN));
2416 return Scm_MakeComplex(r, i);
2417 }
2418 do_complex:
2419 {
2420 double r1 = SCM_COMPNUM_REAL(arg1);
2421 double i1 = SCM_COMPNUM_IMAG(arg1);
2422 double d = r1*r1+i1*i1;
2423 return Scm_MakeComplex(r1 * Scm_GetDouble(arg0) / d,
2424 -i1 * Scm_GetDouble(arg0) / d);
2425 }
2426 }
2427
2428 ScmObj Scm_Div(ScmObj x, ScmObj y)
2429 {
2430 return scm_div(x, y, FALSE, FALSE, FALSE);
2431 }
2432
2433 ScmObj Scm_DivInexact(ScmObj x, ScmObj y)
2434 {
2435 return scm_div(x, y, TRUE, FALSE, FALSE);
2436 }
2437
2438 ScmObj Scm_DivCompat(ScmObj x, ScmObj y)
2439 {
2440 return scm_div(x, y, FALSE, TRUE, FALSE);
2441 }
2442
2443 ScmObj Scm_VMDiv(ScmObj x, ScmObj y)
2444 {
2445 return scm_div(x, y, FALSE, FALSE, TRUE);
2446 }
2447
2448 ScmObj Scm_VMDivInexact(ScmObj x, ScmObj y)
2449 {
2450 return scm_div(x, y, TRUE, FALSE, TRUE);
2451 }
2452
2453
2454 /*
2455 * Integer division
2456 * Returns (quotient x y)
2457 * If rem != NULL, sets *rem to be (remainder x y) as well.
2458 * We don't provide Scm_VMQuotient, assuming passing flonums to
2459 * quotient is rare.
2460 */
2461 ScmObj Scm_Quotient(ScmObj x, ScmObj y, ScmObj *rem)
2462 {
2463 double rx, ry;
2464
2465 /* Trivial shortcut. This case may seem too specific, but actually
2466 it appears rather often in rational operations. */
2467 if (SCM_EQ(y, SCM_MAKE_INT(1))) {
2468 if (!Scm_IntegerP(x)) goto BADARG;
2469 if (rem) *rem = SCM_MAKE_INT(0);
2470 return x;
2471 }
2472
2473 if (SCM_INTP(x)) {
2474 if (SCM_INTP(y)) {
2475 if (SCM_INT_VALUE(y) == 0) goto DIVBYZERO;
2476 long q = SCM_INT_VALUE(x)/SCM_INT_VALUE(y);
2477 if (rem) {
2478 long r = SCM_INT_VALUE(x)%SCM_INT_VALUE(y);
2479 *rem = SCM_MAKE_INT(r);
2480 }
2481 return SCM_MAKE_INT(q);
2482 }
2483 if (SCM_BIGNUMP(y)) {
2484 if (rem) *rem = x;
2485 return SCM_MAKE_INT(0);
2486 }
2487 if (SCM_FLONUMP(y)) {
2488 rx = (double)SCM_INT_VALUE(x);
2489 ry = SCM_FLONUM_VALUE(y);
2490 if (ry != floor(ry)) goto BADARGY;
2491 goto DO_FLONUM;
2492 }
2493 goto BADARGY;
2494 } else if (SCM_BIGNUMP(x)) {
2495 if (SCM_INTP(y)) {
2496 long r;
2497 ScmObj q = Scm_BignumDivSI(SCM_BIGNUM(x), SCM_INT_VALUE(y), &r);
2498 if (rem) *rem = SCM_MAKE_INT(r);
2499 return q;
2500 } else if (SCM_BIGNUMP(y)) {
2501 ScmObj qr = Scm_BignumDivRem(SCM_BIGNUM(x), SCM_BIGNUM(y));
2502 if (rem) *rem = SCM_CDR(qr);
2503 return SCM_CAR(qr);
2504 } else if (SCM_FLONUMP(y)) {
2505 rx = Scm_BignumToDouble(SCM_BIGNUM(x));
2506 ry = SCM_FLONUM_VALUE(y);
2507 if (ry != floor(ry)) goto BADARGY;
2508 goto DO_FLONUM;
2509 }
2510 goto BADARGY;
2511 } else if (SCM_FLONUMP(x)) {
2512 rx = SCM_FLONUM_VALUE(x);
2513 if (rx != floor(rx)) goto BADARG;
2514 if (SCM_INTP(y)) {
2515 ry = (double)SCM_INT_VALUE(y);
2516 } else if (SCM_BIGNUMP(y)) {
2517 ry = Scm_BignumToDouble(SCM_BIGNUM(y));
2518 } else if (SCM_FLONUMP(y)) {
2519 ry = SCM_FLONUM_VALUE(y);
2520 if (ry != floor(ry)) goto BADARGY;
2521 } else {
2522 goto BADARGY;
2523 }
2524 DO_FLONUM:
2525 {
2526 if (ry == 0.0) goto DIVBYZERO;
2527 double q = (rx*ry > 0)? floor(rx/ry) : ceil(rx/ry);
2528 if (q == 0.0) q = 0.0; /* Don't return -0.0 */
2529 if (rem) {
2530 double rr = roundeven(rx - q*ry);
2531 if (rr == 0.0) rr = 0.0; /* Don't return -0.0 */
2532 *rem = Scm_MakeFlonum(rr);
2533 }
2534 return Scm_MakeFlonum(q);
2535 }
2536 } else {
2537 goto BADARG;
2538 }
2539 DIVBYZERO:
2540 Scm_Error("attempt to calculate a quotient by zero");
2541 BADARGY:
2542 x = y;
2543 BADARG:
2544 SCM_FLONUM_ENSURE_MEM(x);
2545 Scm_Error("integer required, but got %S", x);
2546 return SCM_UNDEFINED; /* dummy */
2547 }
2548
2549 /* Modulo and Reminder.
2550 We don't provide Scm_VMModulo, assuming passing flonums to modulo and
2551 remainder is rare.
2552 TODO: on gcc, % works like reminder. I'm not sure the exact behavior
2553 of % is defined in ANSI C. Need to check it later. */
2554 ScmObj Scm_Modulo(ScmObj x, ScmObj y, int remp)
2555 {
2556 double rx, ry;
2557 if (SCM_INTP(x)) {
2558 if (SCM_INTP(y)) {
2559 if (SCM_INT_VALUE(y) == 0) goto DIVBYZERO;
2560 long r = SCM_INT_VALUE(x)%SCM_INT_VALUE(y);
2561 if (!remp && r) {
2562 if ((SCM_INT_VALUE(x) > 0 && SCM_INT_VALUE(y) < 0)
2563 || (SCM_INT_VALUE(x) < 0 && SCM_INT_VALUE(y) > 0)) {
2564 r += SCM_INT_VALUE(y);
2565 }
2566 }
2567 return SCM_MAKE_INT(r);
2568 }
2569 if (SCM_BIGNUMP(y)) {
2570 if (remp) {
2571 return x;
2572 } else {
2573 if ((SCM_INT_VALUE(x) < 0 && SCM_BIGNUM_SIGN(y) > 0)
2574 || (SCM_INT_VALUE(x) > 0 && SCM_BIGNUM_SIGN(y) < 0)) {
2575 return Scm_BignumAddSI(SCM_BIGNUM(y), SCM_INT_VALUE(x));
2576 } else {
2577 return x;
2578 }
2579 }
2580 }
2581 rx = (double)SCM_INT_VALUE(x);
2582 if (SCM_FLONUMP(y)) {
2583 ry = SCM_FLONUM_VALUE(y);
2584 if (ry != floor(ry)) goto BADARGY;
2585 goto DO_FLONUM;
2586 }
2587 goto BADARGY;
2588 } else if (SCM_BIGNUMP(x)) {
2589 if (SCM_INTP(y)) {
2590 long iy = SCM_INT_VALUE(y);
2591 long rem = Scm_BignumRemSI(SCM_BIGNUM(x), iy);
2592 if (!remp
2593 && rem
2594 && ((SCM_BIGNUM_SIGN(x) < 0 && iy > 0)
2595 || (SCM_BIGNUM_SIGN(x) > 0 && iy < 0))) {
2596 return SCM_MAKE_INT(iy + rem);
2597 }
2598 return SCM_MAKE_INT(rem);
2599 }
2600 if (SCM_BIGNUMP(y)) {
2601 ScmObj rem = SCM_CDR(Scm_BignumDivRem(SCM_BIGNUM(x), SCM_BIGNUM(y)));
2602 if (!remp
2603 && (rem != SCM_MAKE_INT(0))
2604 && (SCM_BIGNUM_SIGN(x) * SCM_BIGNUM_SIGN(y) < 0)) {
2605 if (SCM_BIGNUMP(rem)) {
2606 return Scm_BignumAdd(SCM_BIGNUM(y), SCM_BIGNUM(rem));
2607 } else {
2608 return Scm_BignumAddSI(SCM_BIGNUM(y), SCM_INT_VALUE(rem));
2609 }
2610 }
2611 return rem;
2612 }
2613 rx = Scm_BignumToDouble(SCM_BIGNUM(x));
2614 if (SCM_FLONUMP(y)) {
2615 ry = SCM_FLONUM_VALUE(y);
2616 if (ry != floor(ry)) goto BADARGY;
2617 goto DO_FLONUM;
2618 }
2619 goto BADARGY;
2620 } else if (SCM_FLONUMP(x)) {
2621 double rem;
2622 rx = SCM_FLONUM_VALUE(x);
2623 if (rx != floor(rx)) goto BADARG;
2624 if (SCM_INTP(y)) {
2625 ry = (double)SCM_INT_VALUE(y);
2626 } else if (SCM_BIGNUMP(y)) {
2627 ry = Scm_BignumToDouble(SCM_BIGNUM(y));
2628 } else if (SCM_FLONUMP(y)) {
2629 ry = SCM_FLONUM_VALUE(y);
2630 if (ry != floor(ry)) goto BADARGY;
2631 } else {
2632 goto BADARGY;
2633 }
2634 DO_FLONUM:
2635 if (ry == 0.0) goto DIVBYZERO;
2636 rem = fmod(rx, ry);
2637 if (!remp && rem != 0.0) {
2638 if ((rx > 0 && ry < 0) || (rx < 0 && ry > 0)) {
2639 rem += ry;
2640 }
2641 }
2642 if (rem == 0.0) rem = 0.0; /* Don't return -0.0 */
2643 return Scm_MakeFlonum(rem);
2644 } else {
2645 goto BADARG;
2646 }
2647 DIVBYZERO:
2648 Scm_Error("attempt to take a modulo or remainder by zero");
2649 BADARGY:
2650 x = y;
2651 BADARG:
2652 SCM_FLONUM_ENSURE_MEM(x);
2653 Scm_Error("integer required, but got %S", x);
2654 return SCM_UNDEFINED; /* dummy */
2655 }
2656
2657 /*
2658 * Gcd
2659 */
2660
2661 /* assumes x > y >= 0 */
2662 static u_long gcd_fixfix(u_long x, u_long y)
2663 {
2664 while (y > 0) {
2665 u_long r = x % y;
2666 x = y;
2667 y = r;
2668 }
2669 return x;
2670 }
2671
2672 static double gcd_floflo(double x, double y)
2673 {
2674 if (x < 0) x = -x;
2675 if (y < 0) y = -y;
2676 if (x < y) { double t = x; x = y; y = t; }
2677
2678 while (y > 0.0) {
2679 double r = fmod(x, y);
2680 x = y;
2681 y = r;
2682 }
2683 return x;
2684 }
2685
2686 /* assumes y <= LONG_MAX. curiously, the sign of x doesn't matter,
2687 since it only affects the remainder's sign which we adjust afterwards. */
2688 static u_long gcd_bigfix(ScmBignum *x, u_long y)
2689 {
2690 long rem;
2691 (void)Scm_BignumDivSI(x, (signed long)y, &rem);
2692 if (rem < 0) rem = -rem;
2693 return gcd_fixfix(y, (u_long)rem);
2694 }
2695
2696 /* We don't provide Scm_VMGcd, assuming passing flonums to gcd is rare. */
2697 ScmObj Scm_Gcd(ScmObj x, ScmObj y)
2698 {
2699 if (!Scm_IntegerP(x)) {
2700 Scm_Error("integer required, but got %S", x);
2701 }
2702 if (!Scm_IntegerP(y)) {
2703 Scm_Error("integer required, but got %S", y);
2704 }
2705 if (SCM_FLONUMP(x) || SCM_FLONUMP(y)) {
2706 return Scm_MakeFlonum(gcd_floflo(Scm_GetDouble(x), Scm_GetDouble(y)));
2707 }
2708
2709 if (SCM_EXACT_ZERO_P(x)) return y;
2710 if (SCM_EXACT_ZERO_P(y)) return x;
2711
2712 int ox = FALSE, oy = FALSE;
2713 long ix = Scm_GetIntegerClamp(x, SCM_CLAMP_NONE, &ox);
2714 long iy = Scm_GetIntegerClamp(y, SCM_CLAMP_NONE, &oy);
2715
2716 if (!ox && !oy) {
2717 u_long ux = (ix < 0)? -ix : ix;
2718 u_long uy = (iy < 0)? -iy : iy;
2719 u_long ur = (ux >= uy)? gcd_fixfix(ux, uy) : gcd_fixfix(uy, ux);
2720 return Scm_MakeIntegerU(ur);
2721 }
2722
2723 if (!oy && iy != LONG_MIN) {
2724 /* x overflows long. y doesn't. so we know abs(x) > abs(y)
2725 (abs(x) == abs(y) iff LONG_MAX+1 and y == LONG_MIN, but we've
2726 excluded it above). */
2727 SCM_ASSERT(SCM_BIGNUMP(x));
2728 u_long uy = (iy < 0)? -iy : iy;
2729 u_long ur = gcd_bigfix(SCM_BIGNUM(x), uy);
2730 return Scm_MakeIntegerU(ur);
2731 }
2732
2733 if (!ox && ix != LONG_MIN) {
2734 /* reverse condition of above */
2735 SCM_ASSERT(SCM_BIGNUMP(y));
2736 u_long ux = (ix < 0)? -ix : ix;
2737 u_long ur = gcd_bigfix(SCM_BIGNUM(y), ux);
2738 return Scm_MakeIntegerU(ur);
2739 }
2740
2741 /* Now we need to treat both args as bignums. We could use
2742 Algorithm L in Knuth's TAOCP 4.5.2, but we assume this path
2743 is rarely executed, so we don't bother for now. */
2744 x = Scm_Abs(x);
2745 y = Scm_Abs(y);
2746 if (Scm_NumCmp(x, y) < 0) {ScmObj t = x; x = y; y = t;}
2747
2748 while (!SCM_EXACT_ZERO_P(y)) {
2749 ScmObj r = Scm_Modulo(x, y, TRUE);
2750 x = y;
2751 y = r;
2752 }
2753 return x;
2754 }
2755
2756 /*===============================================================
2757 * Exponential and trigometric functions
2758 */
2759
2760 /* Integer power of 10. It is extensively used during string->number
2761 and number->string operations.
2762 IEXPT10_TABLESIZ is ceil(-log10(ldexp(1.0, -1022-52))) + 2 */
2763 /* NB: actually we need more margin here to handle denormalized numbers. */
2764 #define IEXPT10_TABLESIZ 341
2765 static ScmObj iexpt10_n[IEXPT10_TABLESIZ] = { NULL };
2766 static int iexpt10_initialized = FALSE;
2767
2768 static void iexpt10_init(void)
2769 {
2770 iexpt10_n[0] = SCM_MAKE_INT(1);
2771 iexpt10_n[1] = SCM_MAKE_INT(10);
2772 iexpt10_n[2] = SCM_MAKE_INT(100);
2773 iexpt10_n[3] = SCM_MAKE_INT(1000);
2774 iexpt10_n[4] = SCM_MAKE_INT(10000);
2775 iexpt10_n[5] = SCM_MAKE_INT(100000);
2776 iexpt10_n[6] = SCM_MAKE_INT(1000000);
2777 for (int i=7; i<IEXPT10_TABLESIZ; i++) {
2778 iexpt10_n[i] = Scm_Mul(iexpt10_n[i-1], SCM_MAKE_INT(10));
2779 }
2780 iexpt10_initialized = TRUE;
2781 }
2782
2783 #define IEXPT10_INIT() \
2784 do { if (!iexpt10_initialized) iexpt10_init(); } while (0)
2785
2786 /* expt(x, y) where x is exact and y is integer */
2787 ScmObj Scm_ExactIntegerExpt(ScmObj x, ScmObj y)
2788 {
2789 int sign = Scm_Sign(y);
2790 ScmObj r = SCM_MAKE_INT(1);
2791
2792 if (sign == 0) return r;
2793 if (SCM_EQ(x, SCM_MAKE_INT(1))) return r;
2794 if (SCM_EQ(x, SCM_MAKE_INT(-1))) return Scm_OddP(y)? SCM_MAKE_INT(-1) : r;
2795
2796 if (!SCM_INTP(y)) {
2797 /* who wants such a heavy calculation? */
2798 Scm_Error("exponent too big: %S", y);
2799 }
2800 long iy = SCM_INT_VALUE(y);
2801 /* Shortcut for special cases */
2802 if (SCM_EQ(x, SCM_MAKE_INT(10)) && iy > 0 && iy < IEXPT10_TABLESIZ) {
2803 /* We have a precalculated table for 10^y */
2804 IEXPT10_INIT();
2805 r = iexpt10_n[iy];
2806 } else if (SCM_EQ(x, SCM_MAKE_INT(2)) && iy > 0) {
2807 /* Use shift operation for 2^y, y>0 */
2808 r = Scm_Ash(SCM_MAKE_INT(1), iy);
2809 } else {
2810 /* General case */
2811 if (iy < 0) iy = -iy;
2812 for (;;) {
2813 if (iy == 0) break;
2814 if (iy == 1) { r = Scm_Mul(r, x); break; }
2815 if (iy & 0x01) r = Scm_Mul(r, x);
2816 x = Scm_Mul(x, x);
2817 iy >>= 1;
2818 }
2819 }
2820 return (sign < 0)? Scm_Reciprocal(r) : r;
2821 }
2822
2823 static ScmObj scm_expt(ScmObj x, ScmObj y, int vmp)
2824 {
2825 /* NB: The exact case is handled by expt in libnum.scm; we check this case
2826 just for the backward compatibility. */
2827 if (SCM_EXACTP(x) && SCM_INTEGERP(y)) return Scm_ExactIntegerExpt(x, y);
2828 if (!SCM_REALP(x)) Scm_Error("real number required, but got %S", x);
2829 if (!SCM_REALP(y)) Scm_Error("real number required, but got %S", y);
2830 double dx = Scm_GetDouble(x);
2831 double dy = Scm_GetDouble(y);
2832 if (dy == 0.0) {
2833 RETURN_FLONUM(1.0);
2834 } else if (dx < 0 && !Scm_IntegerP(y)) {
2835 /* x^y == exp(y * log(x)) = exp(y*log(|x|))*exp(y*arg(x)*i)
2836 if x is a negative real number, arg(x) == pi
2837 */
2838 double mag = exp(dy * log(-dx));
2839 return Scm_MakeComplex(mag * Scm_CosPi(dy), mag * Scm_SinPi(dy));
2840 } else {
2841 RETURN_FLONUM(pow(dx, dy));
2842 }
2843 }
2844 DEFINE_DUAL_API2(Scm_Expt, Scm_VMExpt, scm_expt)
2845
2846 /* If num is exact 2^s (s >= 0), returns s. Otherwise returns -1. */
2847 long Scm_TwosPower(ScmObj n)
2848 {
2849 if (SCM_INTP(n)) {
2850 long i = SCM_INT_VALUE(n);
2851 if (i <= 0) return -1;
2852 if ((i<<1) == ((i ^ (i-1)) + 1)) {
2853 return Scm__HighestBitNumber(i);
2854 }
2855 /*FALTHROUGH*/
2856 } else if (SCM_BIGNUMP(n) && SCM_BIGNUM_SIGN(n) > 0) {
2857 ScmBits *b = (ScmBits*)SCM_BIGNUM(n)->values;
2858 int l = SCM_BIGNUM_SIZE(n) * SCM_WORD_BITS;
2859 int c = Scm_BitsLowest1(b, 0, l);
2860 if (c == Scm_BitsHighest1(b, 0, l)) return c;
2861 /*FALTHROUGH*/
2862 }
2863 return -1;
2864 }
2865
2866 /* sinpi(x) = sin(x * pi)
2867 cospi(x) = cos(x * pi)
2868 tanpi(x) = tan(x * pi)
2869
2870 We first reduce input range to -1 <= x <= 1 by trig_pi_reduce_range.
2871 */
2872 static double trig_pi_reduce_range(double x)
2873 {
2874 double xx = fmod(x, 2.0); /* -2.0 < x < 2.0 */
2875 if (xx > 1.0) return xx - 2.0;
2876 if (xx < -1.0) return xx + 2.0;
2877 if (xx == 0.0) return 0.0; /* we don't return -0.0 */
2878 else return xx;
2879 }
2880
2881 double Scm_SinPi(double x)
2882 {
2883 double xx = trig_pi_reduce_range(x);
2884 if (xx >= 0) {
2885 if (xx > 0.5) xx = 1 - xx;
2886 if (xx >= 0.25) return cos(M_PI*(0.5-xx));
2887 else return sin(M_PI*xx);
2888 } else {
2889 if (xx < -0.5) xx = -1 - xx;
2890 if (xx <= -0.25) return -cos(M_PI*(-0.5-xx));
2891 else return sin(M_PI*xx);
2892 }
2893 }
2894
2895 double Scm_CosPi(double x)
2896 {
2897 double xx = fabs(trig_pi_reduce_range(x));
2898 if (xx >= 0.75) return -cos(M_PI*(1-xx));
2899 if (xx > 0.25) return sin(M_PI*(0.5-xx));
2900 else return cos(M_PI*xx);
2901 }
2902
2903 double Scm_TanPi(double x)
2904 {
2905 return Scm_SinPi(x)/Scm_CosPi(x);
2906 }
2907
2908 /*===============================================================
2909 * Comparison
2910 */
2911
2912 static inline int nan_p(ScmObj arg)
2913 {
2914 return (SCM_FLONUMP(arg) && SCM_IS_NAN(SCM_FLONUM_VALUE(arg)));
2915 }
2916
2917 static inline int either_nan_p(ScmObj arg0, ScmObj arg1)
2918 {
2919 return (nan_p(arg0) || nan_p(arg1));
2920 }
2921
2922 int Scm_NumEq(ScmObj arg0, ScmObj arg1)
2923 {
2924 if (SCM_COMPNUMP(arg0)) {
2925 if (SCM_COMPNUMP(arg1)) {
2926 return ((SCM_COMPNUM_REAL(arg0) == SCM_COMPNUM_REAL(arg1))
2927 && (SCM_COMPNUM_IMAG(arg0) == SCM_COMPNUM_IMAG(arg1)));
2928 }
2929 return FALSE;
2930 } else {
2931 if (SCM_COMPNUMP(arg1)) return FALSE;
2932 if (either_nan_p(arg0, arg1)) return FALSE;
2933 return (Scm_NumCmp(arg0, arg1) == 0);
2934 }
2935 }
2936
2937 int Scm_NumLT(ScmObj arg0, ScmObj arg1)
2938 {
2939 if (either_nan_p(arg0, arg1)) return FALSE;
2940 return Scm_NumCmp(arg0, arg1) < 0;
2941 }
2942
2943 int Scm_NumLE(ScmObj arg0, ScmObj arg1)
2944 {
2945 if (either_nan_p(arg0, arg1)) return FALSE;
2946 return Scm_NumCmp(arg0, arg1) <= 0;
2947 }
2948
2949 int Scm_NumGT(ScmObj arg0, ScmObj arg1)
2950 {
2951 if (either_nan_p(arg0, arg1)) return FALSE;
2952 return Scm_NumCmp(arg0, arg1) > 0;
2953 }
2954
2955 int Scm_NumGE(ScmObj arg0, ScmObj arg1)
2956 {
2957 if (either_nan_p(arg0, arg1)) return FALSE;
2958 return Scm_NumCmp(arg0, arg1) >= 0;
2959 }
2960
2961 /* 2-arg comparison.
2962 NB: This routine is called from VM or built-in SUBRs when arg0 and/or
2963 arg1 contain register flonums. That's why we insert SCM_FLONUM_ENSURE_MEM
2964 in the path to Scm_Error at the end. For all other paths we know the
2965 register flonum will never leak out. If you make changes here,
2966 keep in mind that args can be register flonums, and make sure to insert
2967 SCM_FLONUM_ENSURE_MEM wherever they can leak out.
2968
2969 Caveat: Scm_NumCmp returns 0 (means equal) when arg0 and/or arg1 is/are NaN.
2970 That's because NaN doesn't make any sense in three-way comparison. The
2971 premise is that NaN has already been filtered out before NumCmp is called.
2972
2973 Pitfall: R7RS requires '=' transitivity. When comparing an exact number vs
2974 an inexact number, simply converting the exact one to inexact can't satisfy
2975 this requirement (cf. https://github.com/shirok/Gauche/issues/805 )
2976 However, we don't want to always convert the inexact one to exact, for
2977 it can be expensive. So we first compare inexactly, and only when it
2978 yields equal and we determine we need more precision, we do exact
2979 comparison.
2980 */
2981 int Scm_NumCmp(ScmObj arg0, ScmObj arg1)
2982 {
2983 ScmObj badnum;
2984
2985 if (SCM_INTP(arg0)) {
2986 if (SCM_INTP(arg1)) {
2987 long r = SCM_INT_VALUE(arg0) - SCM_INT_VALUE(arg1);
2988 if (r < 0) return -1;
2989 if (r > 0) return 1;
2990 return 0;
2991 }
2992 if (SCM_FLONUMP(arg1)) {
2993 double r = (double)SCM_INT_VALUE(arg0) - SCM_FLONUM_VALUE(arg1);
2994 if (r < 0) return -1;
2995 if (r > 0) return 1;
2996 #if SIZEOF_LONG >= 8
2997 /* exact v inexact case. see if we need more precise comparison */
2998 if (!double_precision(arg0, NULL, NULL)) {
2999 return Scm_NumCmp(arg0, Scm_Exact(arg1));
3000 }
3001 #endif
3002 return 0;
3003 }
3004 if (SCM_BIGNUMP(arg1))
3005 return Scm_BignumCmp(SCM_BIGNUM(Scm_MakeBignumFromSI(SCM_INT_VALUE(arg0))),
3006 SCM_BIGNUM(arg1));
3007 if (SCM_RATNUMP(arg1)) {
3008 if (SCM_EQ(SCM_INT_VALUE(0), arg0)) {
3009 return -Scm_Sign(arg1);
3010 } else {
3011 /* Roughly estimates the result by coercing the RATNUM to
3012 double. We have 53bits of precision (denomalized
3013 numbers only matter when ARG0 is zero, which is excluded
3014 already). */
3015 double y = Scm_GetDouble(arg1);
3016 double r = SCM_INT_VALUE(arg0) - y;
3017 double err = y * 2.0e-52;
3018
3019 if (r < -err) return -1;
3020 if (r > err) return 1;
3021 /* We need more precise comparison. */
3022 return Scm_NumCmp(Scm_Mul(arg0, SCM_RATNUM_DENOM(arg1)),
3023 SCM_RATNUM_NUMER(arg1));
3024 }
3025 }
3026 badnum = arg1;
3027 }
3028 else if (SCM_FLONUMP(arg0)) {
3029 if (SCM_INTP(arg1)) {
3030 double r = SCM_FLONUM_VALUE(arg0) - SCM_INT_VALUE(arg1);
3031 if (r < 0) return -1;
3032 if (r > 0) return 1;
3033 #if SIZEOF_LONG >= 8
3034 /* exact v inexact case. see if we need more precise comparison */
3035 if (!double_precision(arg1, NULL, NULL)) {
3036 return Scm_NumCmp(Scm_Exact(arg0), arg1);
3037 }
3038 #endif
3039 return 0;
3040 }
3041 if (SCM_FLONUMP(arg1)) {
3042 double r = SCM_FLONUM_VALUE(arg0) - SCM_FLONUM_VALUE(arg1);
3043 if (r < 0) return -1;
3044 if (r > 0) return 1;
3045 return 0;
3046 }
3047 if (SCM_BIGNUMP(arg1) || SCM_RATNUMP(arg1)) {
3048 /* NaN is already excluded. We filter out obvious. */
3049 if (SCM_IS_INF(SCM_FLONUM_VALUE(arg0))) {
3050 return Scm_Sign(arg0);
3051 }
3052 double r = SCM_FLONUM_VALUE(arg0) - Scm_GetDouble(arg1);
3053 if (r < 0) return -1;
3054 if (r > 0) return 1;
3055 /* exact v inexact */
3056 return Scm_NumCmp(Scm_Exact(arg0), arg1);
3057 }
3058 badnum = arg1;
3059 }
3060 else if (SCM_BIGNUMP(arg0)) {
3061 if (SCM_INTP(arg1))
3062 return Scm_BignumCmp(SCM_BIGNUM(arg0),
3063 SCM_BIGNUM(Scm_MakeBignumFromSI(SCM_INT_VALUE(arg1))));
3064 if (SCM_FLONUMP(arg1))
3065 return -Scm_NumCmp(arg1, arg0);
3066 if (SCM_BIGNUMP(arg1))
3067 return Scm_BignumCmp(SCM_BIGNUM(arg0), SCM_BIGNUM(arg1));
3068 if (SCM_RATNUMP(arg1)) {
3069 /* we can't coerce to flonum, for it may lose precision. */
3070 ScmObj d1 = SCM_RATNUM_DENOM(arg1);
3071 return Scm_NumCmp(Scm_Mul(arg0, d1),
3072 SCM_RATNUM_NUMER(arg1));
3073 }
3074 badnum = arg1;
3075 }
3076 else if (SCM_RATNUMP(arg0)) {
3077 if (SCM_INTP(arg1) || SCM_BIGNUMP(arg1) || SCM_FLONUMP(arg1)) {
3078 return -Scm_NumCmp(arg1, arg0);
3079 }
3080 if (SCM_RATNUMP(arg1)) {
3081 ScmObj n0 = SCM_RATNUM_NUMER(arg0), d0 = SCM_RATNUM_DENOM(arg0);
3082 ScmObj n1 = SCM_RATNUM_NUMER(arg1), d1 = SCM_RATNUM_DENOM(arg1);
3083 int s0 = Scm_Sign(n0), s1 = Scm_Sign(n1);
3084
3085 /* screen the obvious cases without allocating new numbers */
3086 if (s0 < s1) return -1;
3087 if (s0 > s1) return 1;
3088 int d = Scm_NumCmp(d0, d1);
3089 if (d == 0) return Scm_NumCmp(n0, n1);
3090 if ((s0 > 0 && s1 > 0) || (s0 < 0 && s1 < 0)) {
3091 int n = Scm_NumCmp(n0, n1) * s0;
3092 if (d > 0 && n <= 0) return -s0;
3093 if (d < 0 && n >= 0) return s0;
3094 }
3095
3096 return Scm_NumCmp(Scm_Mul(n0, d1),
3097 Scm_Mul(n1, d0));
3098 }
3099 badnum = arg1;
3100 }
3101 else badnum = arg0;
3102
3103 SCM_FLONUM_ENSURE_MEM(badnum);
3104 Scm_Error("real number required: %S", badnum);
3105 return 0; /* dummy */
3106 }
3107
3108 void Scm_MinMax(ScmObj arg0, ScmObj args, ScmObj *min, ScmObj *max)
3109 {
3110 if (!SCM_REALP(arg0)) Scm_Error("real number required, but got %S", arg0);
3111 if (nan_p(arg0)) goto got_nan;
3112 int inexact = !SCM_EXACTP(arg0);
3113 ScmObj mi = arg0;
3114 ScmObj ma = arg0;
3115
3116 for (;SCM_PAIRP(args); args = SCM_CDR(args)) {
3117 ScmObj arg = SCM_CAR(args);
3118 if (!SCM_REALP(arg)) Scm_Error("real number required, but got %S", arg);
3119 if (nan_p(arg)) goto got_nan;
3120 if (!SCM_EXACTP(arg)) inexact = TRUE;
3121 if (min && Scm_NumCmp(mi, arg) > 0) mi = arg;
3122 if (max && Scm_NumCmp(ma, arg) < 0) ma = arg;
3123 }
3124 if (min) {
3125 if (inexact && SCM_EXACTP(mi)) {
3126 *min = Scm_Inexact(mi);
3127 } else {
3128 *min = mi;
3129 }
3130 }
3131 if (max) {
3132 if (inexact && SCM_EXACTP(ma)) {
3133 *max = Scm_Inexact(ma);
3134 } else {
3135 *max = ma;
3136 }
3137 }
3138 return;
3139 got_nan:
3140 if (min) *min = SCM_NAN;
3141 if (max) *max = SCM_NAN;
3142 }
3143
3144 /*===============================================================
3145 * ROUNDING
3146 */
3147
3148 /* NB: rint() is not in POSIX, so an alternative is provided here.
3149 We don't use round(), for it behaves differently when the
3150 argument is exactly the halfway of two whole numbers. */
3151 #ifdef HAVE_RINT
3152 #define roundeven rint
3153 #else /* !HAVE_RINT */
3154 static double roundeven(double v)
3155 {
3156 double r;
3157 double frac = modf(v, &r);
3158 if (v > 0.0) {
3159 if (frac > 0.5) r += 1.0;
3160 else if (frac == 0.5) {
3161 if (fmod(r,2.0) != 0.0) r += 1.0;
3162 }
3163 } else {
3164 if (frac < -0.5) r -= 1.0;
3165 else if (frac == -0.5) {
3166 if (fmod(r,2.0) != 0.0) r -= 1.0;
3167 }
3168 }
3169 return r;
3170 }
3171 #endif /* !HAVE_RINT */
3172
3173 static ScmObj scm_round(ScmObj num, int mode, int vmp)
3174 {
3175
3176 if (SCM_INTEGERP(num)) return num;
3177 if (SCM_RATNUMP(num)) {
3178 int offset = 0;
3179 ScmObj rem;
3180 ScmObj quot = Scm_Quotient(SCM_RATNUM_NUMER(num),
3181 SCM_RATNUM_DENOM(num), &rem);
3182 /* this shouldn't happen, but just in case.. */
3183 if (SCM_EXACT_ZERO_P(rem)) return quot;
3184
3185 /* Here we have quotient, which is always closer to zero
3186 than the original value */
3187 switch (mode) {
3188 case SCM_ROUND_FLOOR:
3189 offset = (Scm_Sign(num) < 0)? -1 : 0;
3190 break;
3191 case SCM_ROUND_CEIL:
3192 offset = (Scm_Sign(num) < 0)? 0 : 1;
3193 break;
3194 case SCM_ROUND_TRUNC:
3195 offset = 0;
3196 break;
3197 case SCM_ROUND_ROUND: {
3198 ScmObj rem2 = Scm_Mul(Scm_Abs(rem), SCM_MAKE_INT(2));
3199 int cmp = Scm_NumCmp(SCM_RATNUM_DENOM(num), rem2);
3200
3201 if (cmp > 0) {
3202 /* NUM is closer to zero than halfway */
3203 offset = 0;
3204 } else if (cmp < 0) {
3205 /* NUM is further from zero than halfway */
3206 offset = (Scm_Sign(num) < 0)? -1 : 1;
3207 } else {
3208 /* NUM is exactly the halfway. We round to even */
3209 if (Scm_OddP(quot)) {
3210 offset = (Scm_Sign(num) < 0)? -1 : 1;
3211 } else {
3212 offset = 0;
3213 }
3214 }
3215 break;
3216 }
3217 default: Scm_Panic("something screwed up");
3218 }
3219
3220 if (offset == 0) return quot;
3221 else return scm_add(quot, SCM_MAKE_INT(offset), vmp);
3222 }
3223 if (SCM_FLONUMP(num)) {
3224 double r = 0.0;
3225 double v = SCM_FLONUM_VALUE(num);
3226 switch (mode) {
3227 case SCM_ROUND_FLOOR: r = floor(v); break;
3228 case SCM_ROUND_CEIL: r = ceil(v); break;
3229 /* trunc is neither in ANSI nor in POSIX. */
3230 #ifdef HAVE_TRUNC
3231 case SCM_ROUND_TRUNC: r = trunc(v); break;
3232 #else
3233 case SCM_ROUND_TRUNC: r = (v < 0.0)? ceil(v) : floor(v); break;
3234 #endif
3235 case SCM_ROUND_ROUND: r = roundeven(v); break;
3236 default: Scm_Panic("something screwed up");
3237 }
3238 if (r == 0.0) r = 0.0; /* Don't return -0.0 */
3239 RETURN_FLONUM(r);
3240 }
3241 Scm_Error("real number required, but got %S", num);
3242 return SCM_UNDEFINED; /* dummy */
3243 }
3244
3245 ScmObj Scm_Round(ScmObj num, int mode)
3246 {
3247 return scm_round(num, mode, FALSE);
3248 }
3249
3250 ScmObj Scm_VMRound(ScmObj num, int mode)
3251 {
3252 return scm_round(num, mode, TRUE);
3253 }
3254
3255
3256 ScmObj Scm_RoundToExact(ScmObj num, int mode)
3257 {
3258 if (SCM_FLONUMP(num)) {
3259 double r = 0.0;
3260 double v = SCM_FLONUM_VALUE(num);
3261 if (SCM_IS_NAN(v) || SCM_IS_INF(v)) {
3262 Scm_Error("Exact infinity/nan is not supported: %S", num);
3263 }
3264 switch (mode) {
3265 case SCM_ROUND_FLOOR: r = floor(v); break;
3266 case SCM_ROUND_CEIL: r = ceil(v); break;
3267 /* trunc is neither in ANSI nor in POSIX. */
3268 #ifdef HAVE_TRUNC
3269 case SCM_ROUND_TRUNC: r = trunc(v); break;
3270 #else
3271 case SCM_ROUND_TRUNC: r = (v < 0.0)? ceil(v) : floor(v); break;
3272 #endif
3273 case SCM_ROUND_ROUND: r = roundeven(v); break;
3274 default: Scm_Panic("something screwed up");
3275 }
3276 return Scm_FlonumIntegerToExact(r);
3277 }
3278 if (SCM_INTEGERP(num)) return num;
3279 if (SCM_RATNUMP(num)) return Scm_Round(num, mode);
3280 Scm_Error("real number required, but got %S", num);
3281 return SCM_UNDEFINED; /* dummy */
3282 }
3283
3284 /*===============================================================
3285 * Logical (bitwise) operations
3286 */
3287
3288 ScmObj Scm_Ash(ScmObj x, ScmSmallInt cnt)
3289 {
3290 /* TODO: This is an arbitrary limit, but we need *some* limit anyway
3291 to prevent a silly mistake from consuming large amount of memory.
3292 Eventually we need a consistent limit on how big a bignum can be. */
3293 if (cnt >= 0x10000000) {
3294 Scm_Error("ash: shift amount too big to handle: %ld", cnt);
3295 }
3296
3297 if (SCM_INTP(x)) {
3298 long ix = SCM_INT_VALUE(x);
3299 if (cnt <= -(SIZEOF_LONG * 8)) {
3300 ix = (ix < 0)? -1 : 0;
3301 return Scm_MakeInteger(ix);
3302 } else if (cnt < 0) {
3303 if (ix < 0) {
3304 ix = ~((~ix) >> (-cnt));
3305 } else {
3306 ix >>= -cnt;
3307 }
3308 return Scm_MakeInteger(ix);
3309 } else if (cnt < SCM_SMALL_INT_SIZE) {
3310 if (ix < 0) {
3311 if (-ix < (SCM_SMALL_INT_MAX >> cnt)) {
3312 ix <<= cnt;
3313 return Scm_MakeInteger(ix);
3314 }
3315 } else {
3316 if (ix < (SCM_SMALL_INT_MAX >> cnt)) {
3317 ix <<= cnt;
3318 return Scm_MakeInteger(ix);
3319 }
3320 }
3321 }
3322 /* Here, we know the result must be a bignum. */
3323 {
3324 ScmObj big = Scm_MakeBignumFromSI(ix);
3325 return Scm_BignumAsh(SCM_BIGNUM(big), cnt);
3326 }
3327 } else if (SCM_BIGNUMP(x)) {
3328 return Scm_BignumAsh(SCM_BIGNUM(x), cnt);
3329 }
3330 Scm_Error("exact integer required, but got %S", x);
3331 return SCM_UNDEFINED;
3332 }
3333
3334 ScmObj Scm_LogNot(ScmObj x)
3335 {
3336 if (!SCM_INTEGERP(x)) Scm_Error("exact integer required, but got %S", x);
3337 if (SCM_INTP(x)) {
3338 /* this won't cause an overflow */
3339 return SCM_MAKE_INT(~SCM_INT_VALUE(x));
3340 } else {
3341 return Scm_Negate(Scm_BignumAddSI(SCM_BIGNUM(x), 1));
3342 }
3343 }
3344
3345 ScmObj Scm_LogAnd(ScmObj x, ScmObj y)
3346 {
3347 if (!SCM_INTEGERP(x)) Scm_Error("exact integer required, but got %S", x);
3348 if (!SCM_INTEGERP(y)) Scm_Error("exact integer required, but got %S", y);
3349 if (SCM_INTP(x)) {
3350 if (SCM_INTP(y)) {
3351 return SCM_MAKE_INT(SCM_INT_VALUE(x) & SCM_INT_VALUE(y));
3352 } else if (SCM_INT_VALUE(x) >= 0 && SCM_BIGNUM_SIGN(y) >= 0) {
3353 return Scm_MakeInteger(SCM_INT_VALUE(x)&SCM_BIGNUM(y)->values[0]);
3354 }
3355 x = Scm_MakeBignumFromSI(SCM_INT_VALUE(x));
3356 } else if (SCM_INTP(y)) {
3357 if (SCM_INT_VALUE(y) >= 0 && SCM_BIGNUM_SIGN(x) >= 0) {
3358 return Scm_MakeInteger(SCM_INT_VALUE(y)&SCM_BIGNUM(x)->values[0]);
3359 }
3360 y = Scm_MakeBignumFromSI(SCM_INT_VALUE(y));
3361 }
3362 return Scm_BignumLogAnd(SCM_BIGNUM(x), SCM_BIGNUM(y));
3363 }
3364
3365 ScmObj Scm_LogIor(ScmObj x, ScmObj y)
3366 {
3367 if (!SCM_INTEGERP(x)) Scm_Error("exact integer required, but got %S", x);
3368 if (!SCM_INTEGERP(y)) Scm_Error("exact integer required, but got %S", y);
3369 if (SCM_INTP(x)) {
3370 if (SCM_INTP(y))
3371 return SCM_MAKE_INT(SCM_INT_VALUE(x) | SCM_INT_VALUE(y));
3372 else
3373 x = Scm_MakeBignumFromSI(SCM_INT_VALUE(x));
3374 } else {
3375 if (SCM_INTP(y)) y = Scm_MakeBignumFromSI(SCM_INT_VALUE(y));
3376 }
3377 return Scm_BignumLogIor(SCM_BIGNUM(x), SCM_BIGNUM(y));
3378 }
3379
3380 ScmObj Scm_LogXor(ScmObj x, ScmObj y)
3381 {
3382 if (!SCM_INTEGERP(x)) Scm_Error("exact integer required, but got %S", x);
3383 if (!SCM_INTEGERP(y)) Scm_Error("exact integer required, but got %S", y);
3384 if (SCM_INTP(x)) {
3385 if (SCM_INTP(y))
3386 return SCM_MAKE_INT(SCM_INT_VALUE(x) ^ SCM_INT_VALUE(y));
3387 else
3388 x = Scm_MakeBignumFromSI(SCM_INT_VALUE(x));
3389 } else {
3390 if (SCM_INTP(y)) y = Scm_MakeBignumFromSI(SCM_INT_VALUE(y));
3391 }
3392 return Scm_BignumLogXor(SCM_BIGNUM(x), SCM_BIGNUM(y));
3393 }
3394
3395 /* Scheme's integer-length. Returns minumum # of bits to represent
3396 the given integer. */
3397 u_long Scm_IntegerLength(ScmObj n)
3398 {
3399 if (SCM_INTP(n)) {
3400 ScmBits z = (ScmBits)(long)SCM_INT_VALUE(n);
3401 if (SCM_INT_VALUE(n) >= 0) {
3402 return Scm_BitsHighest1(&z, 0, SCM_WORD_BITS) + 1;
3403 } else {
3404 return Scm_BitsHighest0(&z, 0, SCM_WORD_BITS) + 1;
3405 }
3406 } else if (SCM_BIGNUMP(n)) {
3407 /* 2's complement adjustment */
3408 if (SCM_BIGNUM_SIGN(n) < 0) {
3409 n = Scm_Add(n, SCM_MAKE_INT(1));
3410 }
3411 /* The above operation may change n to fixnum, so we check again */
3412 if (SCM_BIGNUMP(n)) {
3413 ScmBits *z = (ScmBits*)SCM_BIGNUM(n)->values;
3414 int k = SCM_BIGNUM_SIZE(n);
3415 return Scm_BitsHighest1(z, 0, k*SCM_WORD_BITS) + 1;
3416 } else {
3417 /* If n+1 becomes fixnum, we know n was the least fixnum. */
3418 return SCM_SMALL_INT_SIZE+1;
3419 }
3420 } else {
3421 SCM_TYPE_ERROR(n, "exact integer");
3422 return 0; /* dummy */
3423 }
3424 }
3425
3426
3427 /*===============================================================
3428 * System-specific integral types
3429 */
3430
3431 static ScmObj SCM_SIZE_T_MAX;
3432 static ScmObj SCM_SSIZE_T_MAX;
3433 static ScmObj SCM_SSIZE_T_MIN;
3434 static ScmObj SCM_PTRDIFF_T_MAX;
3435 static ScmObj SCM_PTRDIFF_T_MIN;
3436 static ScmObj SCM_INTPTR_T_MIN;
3437 static ScmObj SCM_INTPTR_T_MAX;
3438 static ScmObj SCM_UINTPTR_T_MAX;
3439
3440 int Scm_IntegerFitsSizeP(ScmObj i)
3441 {
3442 if (SCM_INTP(i)) return SCM_INT_VALUE(i) >= 0;
3443 if (SCM_BIGNUMP(i)) {
3444 return (SCM_BIGNUM_SIGN(i) >= 0
3445 && Scm_NumCmp(i, SCM_SSIZE_T_MAX) <= 0);
3446 }
3447 return FALSE;
3448 }
3449
3450 /* i must satisfy Scm_IntegerFitsSizeP */
3451 size_t Scm_IntegerToSize(ScmObj i)
3452 {
3453 if (SCM_INTP(i) && SCM_INT_VALUE(i) >= 0) {
3454 return (size_t)SCM_INT_VALUE(i);
3455 } else if (SCM_BIGNUMP(i) && SCM_BIGNUM_SIGN(i) >= 0) {
3456 #if SIZEOF_SIZE_T == SIZEOF_LONG
3457 return (size_t)Scm_GetIntegerUClamp(i, SCM_CLAMP_ERROR, NULL);
3458 #elif SIZEOF_SIZE_T == 8
3459 return (size_t)Scm_GetIntegerU64Clamp(i, SCM_CLAMP_ERROR, NULL);
3460 #else
3461 /* I don't think there's such an architecture. */
3462 # error "size_t size on this platform is not suported."
3463 #endif
3464 }
3465 Scm_Error("bad value as size_t: %S", i);
3466 return (size_t)-1; /* dummy */
3467 }
3468
3469 ScmObj Scm_SizeToInteger(size_t off)
3470 {
3471 #if SIZEOF_SIZE_T == SIZEOF_LONG
3472 return Scm_MakeInteger(off);
3473 #elif SIZEOF_SIZE_T == 8
3474 return Scm_MakeInteger64((int64_t)off);
3475 #else
3476 # error "size_t size on this platform is not suported."
3477 #endif
3478 }
3479
3480 int Scm_IntegerFitsSsizeP(ScmObj i)
3481 {
3482 if (SCM_INTP(i)) return TRUE; /* all fixnums should fit in ssize_t */
3483 if (SCM_BIGNUMP(i)) {
3484 return (Scm_NumCmp(i, SCM_SSIZE_T_MIN) >= 0
3485 && Scm_NumCmp(i, SCM_SSIZE_T_MAX) <= 0);
3486 }
3487 return FALSE;
3488 }
3489
3490 /* i must satisfy Scm_IntegerFitsSsizeP */
3491 ssize_t Scm_IntegerToSsize(ScmObj i)
3492 {
3493 if (SCM_INTP(i)) return (ssize_t)SCM_INT_VALUE(i);
3494 if (SCM_BIGNUMP(i)) {
3495 #if SIZEOF_SSIZE_T == SIZEOF_LONG
3496 return (ssize_t)Scm_GetIntegerClamp(i, SCM_CLAMP_ERROR, NULL);
3497 #elif SIZEOF_SSIZE_T == 8
3498 return (ssize_t)Scm_GetInteger64Clamp(i, SCM_CLAMP_ERROR, NULL);
3499 #else
3500 /* I don't think there's such an architecture. */
3501 # error "ssize_t size on this platform is not suported."
3502 #endif
3503 }
3504 Scm_Error("bad value as ssize_t: %S", i);
3505 return (ssize_t)-1; /* dummy */
3506 }
3507
3508 /* There're platforms where pointer width is smaller than long's, so
3509 not all fixnums may fit in ptfdiff_t.
3510 */
3511 int Scm_IntegerFitsPtrdiffP(ScmObj i)
3512 {
3513 if (SCM_INTEGERP(i)) {
3514 return (Scm_NumCmp(i, SCM_PTRDIFF_T_MIN) >= 0
3515 && Scm_NumCmp(i, SCM_PTRDIFF_T_MAX) <= 0);
3516 }
3517 return FALSE;
3518 }
3519
3520 ptrdiff_t Scm_IntegerToPtrdiff(ScmObj i)
3521 {
3522 if (SCM_INTEGERP(i)) {
3523 #if SIZEOF_PTRDIFF_T == SIZEOF_LONG
3524 return (ptrdiff_t)Scm_GetIntegerClamp(i, SCM_CLAMP_ERROR, NULL);
3525 #elif SIZEOF_PTRDIFF_T == 8
3526 return (ptrdiff_t)Scm_GetInteger64Clamp(i, SCM_CLAMP_ERROR, NULL);
3527 #else
3528 # error "ptrdiff_t size on this platform is not suported."
3529 #endif
3530 }
3531 Scm_Error("bad value as ptrdiff: %S", i);
3532 return (ptrdiff_t)-1; /* dummy */
3533 }
3534
3535 ScmObj Scm_PtrdiffToInteger(ptrdiff_t d)
3536 {
3537 #if SIZEOF_PTRDIFF_T == SIZEOF_LONG
3538 return Scm_MakeInteger((long)d);
3539 #elif SIZEOF_PTRDIFF_T == 8
3540 return Scm_MakeInteger64((int64_t)d);
3541 #else
3542 # error "ptrdiff_t size on this platform is not suported."
3543 #endif
3544 }
3545
3546 /* Range of off_t is not provided in POSIX. We assume the range of signed
3547 integer that fits in the size of off_t. */
3548 int Scm_IntegerFitsOffsetP(ScmObj i)
3549 {
3550 if (SCM_INTP(i)) return TRUE;
3551 #if SIZEOF_OFF_T == 4
3552 if (SCM_BIGNUMP(i)) {
3553 return (Scm_NumCmp(i, SCM_MINUS_2_31) >= 0
3554 && Scm_NumCmp(i, SCM_2_31) >= 0);
3555 }
3556 #elif SIZEOF_OFF_T == 8
3557 if (SCM_BIGNUMP(i)) {
3558 return (Scm_NumCmp(i, SCM_MINUS_2_63) >= 0
3559 && Scm_NumCmp(i, SCM_2_63) >= 0);
3560 }
3561 #else
3562 # error "off_t size on this platform is not suported."
3563 #endif
3564 return FALSE;
3565 }
3566
3567 off_t Scm_IntegerToOffset(ScmObj i)
3568 {
3569 if (SCM_INTP(i)) {
3570 return (off_t)SCM_INT_VALUE(i);
3571 } else if (SCM_BIGNUMP(i)) {
3572 #if SIZEOF_OFF_T == SIZEOF_LONG
3573 return (off_t)Scm_GetIntegerClamp(i, SCM_CLAMP_ERROR, NULL);
3574 #elif SIZEOF_OFF_T == 8
3575 return (off_t)Scm_GetInteger64Clamp(i, SCM_CLAMP_ERROR, NULL);
3576 #else
3577 # error "off_t size on this platform is not suported."
3578 #endif
3579 }
3580 Scm_Error("bad value as offset: %S", i);
3581 return (off_t)-1; /* dummy */
3582 }
3583
3584 ScmObj Scm_OffsetToInteger(off_t off)
3585 {
3586 #if SIZEOF_OFF_T == SIZEOF_LONG
3587 return Scm_MakeInteger(off);
3588 #elif SIZEOF_OFF_T == 8
3589 return Scm_MakeInteger64((int64_t)off);
3590 #else
3591 # error "off_t size on this platform is not suported."
3592 #endif
3593 }
3594
3595 int Scm_IntegerFitsIntptrP(ScmObj i)
3596 {
3597 if (SCM_INTEGERP(i)) {
3598 return (Scm_NumCmp(i, SCM_INTPTR_T_MIN) >= 0
3599 && Scm_NumCmp(i, SCM_INTPTR_T_MAX) <= 0);
3600 }
3601 return FALSE;
3602 }
3603
3604 intptr_t Scm_IntegerToIntptr(ScmObj i)
3605 {
3606 if (SCM_INTP(i)) {
3607 return (intptr_t)SCM_INT_VALUE(i);
3608 } else if (SCM_BIGNUMP(i)) {
3609 #if SIZEOF_INTPTR_T == SIZEOF_LONG
3610 return (intptr_t)Scm_GetIntegerClamp(i, SCM_CLAMP_ERROR, NULL);
3611 #elif SIZEOF_INTPTR_T <= 8
3612 return (intptr_t)Scm_GetInteger64Clamp(i, SCM_CLAMP_ERROR, NULL);
3613 #else
3614 /* I don't think there's such an architecture. */
3615 # error "intptr_t size on this platform is not suported."
3616 #endif
3617 }
3618 Scm_Error("bad value as intptr: %S", i);
3619 return (intptr_t)-1; /* dummy */
3620 }
3621
3622 ScmObj Scm_IntptrToInteger(intptr_t i)
3623 {
3624 #if SIZEOF_INTPTR_T == SIZEOF_LONG
3625 return Scm_MakeInteger(i);
3626 #elif SIZEOF_INTPTR_T <= 8
3627 return Scm_MakeInteger64((int64_t)i);
3628 #else
3629 # error "intptr_t size on this platform is not suported."
3630 #endif
3631 }
3632
3633 int Scm_IntegerFitsUintptrP(ScmObj i)
3634 {
3635 if (SCM_INTP(i)) return SCM_INT_VALUE(i) >= 0;
3636 if (SCM_BIGNUMP(i)) {
3637 return (SCM_BIGNUM_SIGN(i) >= 0
3638 && Scm_NumCmp(i, SCM_UINTPTR_T_MAX) <= 0);
3639 }
3640 return FALSE;
3641 }
3642
3643 uintptr_t Scm_IntegerToUintptr(ScmObj i)
3644 {
3645 if (SCM_INTP(i)) {
3646 return (uintptr_t)SCM_INT_VALUE(i);
3647 } else if (SCM_BIGNUMP(i)) {
3648 #if SIZEOF_UINTPTR_T == SIZEOF_LONG
3649 return (uintptr_t)Scm_GetIntegerClamp(i, SCM_CLAMP_ERROR, NULL);
3650 #elif SIZEOF_UINTPTR_T <= 8
3651 return (uintptr_t)Scm_GetInteger64Clamp(i, SCM_CLAMP_ERROR, NULL);
3652 #else
3653 /* I don't think there's such an architecture. */
3654 # error "uintptr_t size on this platform is not suported."
3655 #endif
3656 }
3657 Scm_Error("bad value as intptr: %S", i);
3658 return (intptr_t)-1; /* dummy */
3659 }
3660
3661 ScmObj Scm_UintptrToInteger(uintptr_t i)
3662 {
3663 #if SIZEOF_UINTPTR_T == SIZEOF_LONG
3664 return Scm_MakeIntegerU(i);
3665 #elif SIZEOF_UINTPTR_T <= 8
3666 return Scm_MakeIntegerU64((uint64_t)i);
3667 #else
3668 # error "uintptr_t size on this platform is not suported."
3669 #endif
3670 }
3671
3672 /*===============================================================
3673 * Number I/O
3674 */
3675
3676 /* contants frequently used in number I/O */
3677 static double dexpt2_minus_52 = 0.0; /* 2.0^-52 */
3678 static double dexpt2_minus_53 = 0.0; /* 2.0^-53 */
3679
3680 /* max N where 10.0^N can be representable exactly in double.
3681 it is max N where N * log2(5) < 53. */
3682 #define MAX_EXACT_10_EXP 23
3683
3684 /* fast 10^n for limited cases */
3685 static inline ScmObj iexpt10(int e)
3686 {
3687 if (e < IEXPT10_TABLESIZ) {
3688 return iexpt10_n[e];
3689 } else {
3690 /* This recursive case can happen if excessive number of decimal
3691 digits are given below the decimal point, and the exponent
3692 is close to minimum. There may be more efficient way to
3693 prune lower digits so that we can keep scale factor bounded,
3694 since those lower digits are very unlikely to contribute to
3695 the result. But it is difficult to avoid double-rounding
3696 error compeletely, so we take safer path for now. */
3697 return Scm_Mul(iexpt10_n[IEXPT10_TABLESIZ-1],
3698 iexpt10(e - IEXPT10_TABLESIZ + 1));
3699 }
3700 }
3701
3702 /* integer power of R by N, N is rather small.
3703 Assuming everything is in range. */
3704 static inline u_long ipow(int r, int n)
3705 {
3706 u_long k;
3707 for (k=1; n>0; n--) k *= r;
3708 return k;
3709 }
3710
3711 /* X * 10.0^N by double.
3712 10.0^N can be represented _exactly_ in double-precision floating point
3713 number in the range 0 <= N <= 23.
3714 If N is out of this range, a rounding error occurs, which will be
3715 corrected in the algorithmR routine below. */
3716 static double raise_pow10(double x, int n)
3717 {
3718 static double dpow10[] = { 1.0, 1.0e1, 1.0e2, 1.0e3, 1.0e4,
3719 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9,
3720 1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14,
3721 1.0e15, 1.0e16, 1.0e17, 1.0e18, 1.0e19,
3722 1.0e20, 1.0e21, 1.0e22, 1.0e23 };
3723 if (n >= 0) {
3724 while (n > 23) {
3725 x *= 1.0e24;
3726 n -= 24;
3727 }
3728 return x*dpow10[n];
3729 } else {
3730 while (n < -23) {
3731 x /= 1.0e24;
3732 n += 24;
3733 }
3734 return x/dpow10[-n];
3735 }
3736 }
3737
3738 /*
3739 * Number Printer
3740 *
3741 * This version implements Burger&Dybvig algorithm (Robert G. Burger
3742 * and and R. Kent Dybvig, "Priting Floating-Point Numbers Quickly and
3743 * Accurately", PLDI '96, pp.108--116, 1996).
3744 */
3745
3746 /* compare x+d and y. x, d, y are exact positive integers.
3747 this is called in inner loops so we need to be fast. */
3748 static inline int numcmp3(ScmObj x, ScmObj d, ScmObj y)
3749 {
3750 if (SCM_INTP(x) && SCM_INTP(d) && SCM_INTP(y)) {
3751 long xd = SCM_INT_VALUE(x)+SCM_INT_VALUE(d);
3752 if (xd < SCM_INT_VALUE(y)) return -1;
3753 if (xd > SCM_INT_VALUE(y)) return 1;
3754 else return 0;
3755 } else {
3756 ScmObj bx = SCM_BIGNUMP(x)? x : Scm_MakeBignumFromSI(SCM_INT_VALUE(x));
3757 ScmObj bd = SCM_BIGNUMP(d)? d : Scm_MakeBignumFromSI(SCM_INT_VALUE(d));
3758 ScmObj by = SCM_BIGNUMP(y)? y : Scm_MakeBignumFromSI(SCM_INT_VALUE(y));
3759 return Scm_BignumCmp3U(SCM_BIGNUM(bx), SCM_BIGNUM(bd), SCM_BIGNUM(by));
3760 }
3761 }
3762
3763 /* Increment the given decimal number represented as a string.
3764
3765 /------------------ start
3766 | /---- end
3767 v v
3768 buf |- 3 . 1 4 1 5 9 |
3769
3770 In this example, we add 1 to the 10000th ('9') and handle any carryovers.
3771 If the carry over spills on the left, we shift entire string to right.
3772 Returns NUL-terminated string.
3773 */
3774 static char *notational_roundup(const char *src, int start, int end)
3775 {
3776 char *r = SCM_NEW_ATOMIC2(char*, end+2);
3777 memcpy(r, src, end);
3778 r[end] = r[end+1] = '\0';
3779
3780 /* loop as long as we carry over */
3781 char *s = r+start;
3782 char *p = r+end-1;
3783 for (; s <= p; p--) {
3784 if (*p == '.') continue;
3785 if (*p == '9') { *p = '0'; continue; }
3786 else { (*p)++; break; }
3787 }
3788 if (p < s && *s == '0') {
3789 /* spill over */
3790 for (p = r+end-1; s <= p; p--) p[1] = p[0];
3791 *s = '1';
3792 }
3793 return r;
3794 }
3795
3796 /* Notational rounding
3797 Should we use commercial rounding (round half towards infinity)
3798 or banker's rounding? Since notational rounding is inherently
3799 taking convenience than accuracy, we go with commercial rounding.
3800 */
3801 static void notational_rounding(ScmDString *ds, int numstart, int precision)
3802 {
3803 Scm_DStringWeld(ds);
3804 ScmSmallInt size;
3805 const char *cbuf = Scm_DStringPeek(ds, &size, NULL);
3806 const char *end = cbuf + size;
3807 const char *p = cbuf;
3808 while (p < end && *p != '.') p++;
3809 SCM_ASSERT(p < end);
3810 p++; /* p is on tenths */
3811 if (end-p > precision) {
3812 char c = *(p+precision);
3813 if (c < '5') {
3814 /* round down - we just truncate */
3815 Scm_DStringTruncate(ds, p+precision-cbuf);
3816 } else {
3817 /* round up */
3818 char *nbuf = notational_roundup(cbuf, numstart,
3819 p+precision-cbuf);
3820 Scm_DStringTruncate(ds, 0);
3821 Scm_DStringPutz(ds, nbuf, -1);
3822 }
3823 }
3824 }
3825
3826 /* Increment the last digit and handle all carryovers.
3827 If we always emit highest precision, Burger&Dybvig algorithm strictly
3828 emits digits forward, without backing up to handle carry over.
3829 However, if we round the number before it, there can be a case that
3830 the last digit gets rounded up and its carry-over propagates upward.
3831 In such a case, this is called. The last digit in DS is '9', and we
3832 know we need to round it up.
3833 */
3834 static void spill_fixup(ScmDString *ds, int numstart)
3835 {
3836 ScmSmallInt size;
3837 const char *cbuf = Scm_DStringPeek(ds, &size, NULL);
3838 char *nbuf = notational_roundup(cbuf, numstart, size);
3839 Scm_DStringTruncate(ds, 0);
3840 Scm_DStringPutz(ds, nbuf, -1);
3841 }
3842
3843 /* The main routine to get string representation of double.
3844 Convert VAL to a string and store to BUF, which must have at least FLT_BUF
3845 bytes long.
3846 True for PLUS_SIGN forces adding '+' for nonnegative numbers.
3847 EXP_LO and EXP_HI control when to switch exponential representation.
3848 We use n.nnne+zz representation when zz can be smaller than or equal
3849 to EXP_LO, or greater than or equal to EXP_HI.
3850 PRECISION specifies the number of digits to be printed after
3851 the decimal point; -1 means no limit.
3852 NOTATIONAL flags changes how the rounding with precision is done; if it's
3853 false, we choose closest decimal to the actual number represented by VAL.
3854 If it's true, we first generate optimal decimal notation, then round.
3855 */
3856 static void print_double(ScmDString *ds, double val, int plus_sign,
3857 int precision, int notational,
3858 int exp_lo, int exp_hi, int exp_width)
3859 {
3860 /* Handle a few special cases first. */
3861 if (val == 0.0) {
3862 if (Scm_FlonumSign(val) > 0) {
3863 if (plus_sign) SCM_DSTRING_PUTC(ds, '+');
3864 } else {
3865 SCM_DSTRING_PUTC(ds, '-');
3866 }
3867 if (precision < 0) Scm_DStringPutz(ds, "0.0", 3);
3868 else {
3869 Scm_DStringPutz(ds, "0.", 2);
3870 for (int i=0; i<precision; i++) {
3871 Scm_DStringPutc(ds, '0');
3872 }
3873 }
3874 return;
3875 } else if (SCM_IS_INF(val)) {
3876 if (val < 0.0) Scm_DStringPutz(ds, "-inf.0", 6);
3877 else Scm_DStringPutz(ds, "+inf.0", 6);
3878 return;
3879 } else if (SCM_IS_NAN(val)) {
3880 Scm_DStringPutz(ds, "+nan.0", 6);
3881 return;
3882 }
3883
3884 if (val < 0.0) SCM_DSTRING_PUTC(ds, '-');
3885 else if (plus_sign) SCM_DSTRING_PUTC(ds, '+');
3886
3887 int numstart = Scm_DStringSize(ds); /* remember this for notational rounding */
3888
3889 /* variable names follows Burger&Dybvig paper. mp, mm for m+, m-.
3890 note that m+ == m- for most cases, and m+ == 2*m- for the rest.
3891 so we calculate m+ from m- for each iteration, using the flag
3892 mp2 as m+ = mp? m- : 2*m-. */
3893 ScmObj r, s, mm;
3894 int exp, sign;
3895 int mp2 = FALSE, fixup = FALSE;
3896 int fracdigs = -1; /* Count digits below the decimal point.
3897 Initial value is -1. Once we emit the decimal
3898 point it becomes 0, then we start counting. */
3899
3900 IEXPT10_INIT();
3901 if (val < 0) val = -val;
3902
3903 /* initialize r, s, m+ and m- */
3904 ScmObj f = Scm_DecodeFlonum(val, &exp, &sign);
3905 int round = !Scm_OddP(f);
3906 if (exp >= 0) {
3907 ScmObj be = Scm_Ash(SCM_MAKE_INT(1), exp);
3908 if (Scm_NumCmp(f, SCM_2_52) != 0) {
3909 r = Scm_Ash(f, exp+1);
3910 s = SCM_MAKE_INT(2);
3911 mp2= FALSE;
3912 mm = be;
3913 } else {
3914 r = Scm_Ash(f, exp+2);
3915 s = SCM_MAKE_INT(4);
3916 mp2 = TRUE;
3917 mm = be;
3918 }
3919 } else {
3920 if (exp == -1023 || Scm_NumCmp(f, SCM_2_52) != 0) {
3921 r = Scm_Ash(f, 1);
3922 s = Scm_Ash(SCM_MAKE_INT(1), -exp+1);
3923 mp2 = FALSE;
3924 mm = SCM_MAKE_INT(1);
3925 } else {
3926 r = Scm_Ash(f, 2);
3927 s = Scm_Ash(SCM_MAKE_INT(1), -exp+2);
3928 mp2 = TRUE;
3929 mm = SCM_MAKE_INT(1);
3930 }
3931 }
3932
3933 /* estimate scale */
3934 int est = (int)ceil(log10(val) - 0.1);
3935 if (est >= 0) {
3936 s = Scm_Mul(s, iexpt10(est));
3937 } else {
3938 ScmObj scale = iexpt10(-est);
3939 r = Scm_Mul(r, scale);
3940 mm = Scm_Mul(mm, scale);
3941 }
3942
3943 /* fixup. avoid calculating m+ for obvious case. */
3944 if (Scm_NumCmp(r, s) >= 0) {
3945 fixup = TRUE;
3946 } else {
3947 ScmObj mp = (mp2? Scm_Ash(mm, 1) : mm);
3948 if (round) {
3949 fixup = (numcmp3(r, mp, s) >= 0);
3950 } else {
3951 fixup = (numcmp3(r, mp, s) > 0);
3952 }
3953 }
3954 if (fixup) {
3955 s = Scm_Mul(s, SCM_MAKE_INT(10));
3956 est++;
3957 }
3958
3959 /* Scm_Printf(SCM_CURERR, "est=%d, r=%S, s=%S, mp=%S, mm=%S\n",
3960 est, r, s, mp, mm); */
3961
3962 /* Determine position of decimal point. we avoid exponential
3963 notation if exponent is small, i.e. 0.9 and 30.0 instead of
3964 9.0e-1 and 3.0e1. */
3965 int point;
3966 if (est < exp_hi && est > exp_lo) { point = est; est = 1; }
3967 else { point = 1; }
3968
3969 /* Now, we print XX.YYeZZ, where XX.YY is VAL*10^EST and
3970 ZZ is EST. If EST == 1 we omit exponent part. POINT is
3971 the number of digits in XX part; so POINT=1 for 1.23,
3972 POINT=2 for 12.3 and so on. */
3973
3974 /* If POINT <= 0, we need to emit preceding zeros. */
3975 if (point <= 0) {
3976 for (int digs=point; digs<1 ;digs++) {
3977 /* check the number of digits to be printed */
3978 if (!notational && precision >= 0 && fracdigs >= precision-1) {
3979 if (digs == 0) {
3980 /* whether r/s is greater than 1/2 or not defines the
3981 first number of significant digits */
3982 ScmObj r2 = Scm_Ash(r, 1);
3983 if (Scm_NumCmp(r2, s) > 0) SCM_DSTRING_PUTC(ds, '1');
3984 else SCM_DSTRING_PUTC(ds, '0');
3985 } else {
3986 SCM_DSTRING_PUTC(ds, '0');
3987 }
3988 if (digs == point) SCM_DSTRING_PUTC(ds, '.');
3989 /* no more digits. */
3990 goto show_exponent;
3991 }
3992 SCM_DSTRING_PUTC(ds, '0');
3993 if (digs == point) SCM_DSTRING_PUTC(ds, '.');
3994 fracdigs++;
3995 }
3996 }
3997
3998 /* generate the digits */
3999 int spilled = FALSE;
4000 int digs;
4001 for (digs=1; ; digs++) {
4002 ScmObj r10 = Scm_Mul(r, SCM_MAKE_INT(10));
4003 ScmObj q = Scm_Quotient(r10, s, &r);
4004 ScmObj mp;
4005
4006 /* if we round early, we should extend the boundary
4007 _one digit before the rounded digit_. It's a bit complicated
4008 since when precision == 0 we have to do it before printing
4009 decimal point. */
4010 if (!notational
4011 && ((precision == 0 && digs == point)
4012 || (precision > 0 && fracdigs >= precision-1))) {
4013 mm = mp = Scm_Ash(s, -1);
4014 } else {
4015 mm = Scm_Mul(mm, SCM_MAKE_INT(10));
4016 mp = (mp2? Scm_Ash(mm, 1) : mm);
4017 }
4018
4019 /*Scm_Printf(SCM_CURERR, "q=%S, r=%S, s=%S mp=%S, mm=%S\n",
4020 q, r, s, mp, mm);*/
4021
4022 SCM_ASSERT(SCM_INTP(q));
4023 int tc1, tc2;
4024 if (round) {
4025 tc1 = (Scm_NumCmp(r, mm) <= 0);
4026 tc2 = (numcmp3(r, mp, s) >= 0);
4027 } else {
4028 tc1 = (Scm_NumCmp(r, mm) < 0);
4029 tc2 = (numcmp3(r, mp, s) > 0);
4030 }
4031 if (!tc1) {
4032 if (!tc2) {
4033 ScmChar c = (char)SCM_INT_VALUE(q) + '0';
4034 SCM_DSTRING_PUTC(ds, c);
4035 if (digs == point) SCM_DSTRING_PUTC(ds, '.');
4036 if (digs >= point) fracdigs++;
4037 continue;
4038 } else {
4039 ScmChar c = (char)SCM_INT_VALUE(q) + '1';
4040 if (c > '9') { spilled = TRUE; c = '9'; }
4041 SCM_DSTRING_PUTC(ds, c);
4042 if (digs > point) fracdigs++;
4043 break;
4044 }
4045 } else {
4046 if (!tc2) {
4047 SCM_ASSERT(SCM_INTP(q));
4048 ScmChar c = (char)SCM_INT_VALUE(q) + '0';
4049 SCM_DSTRING_PUTC(ds, c);
4050 if (digs > point) fracdigs++;
4051 break;
4052 } else {
4053 int tc3 = numcmp3(r, r, s); /* r*2 <=> s */
4054 if ((round && tc3 <= 0) || (!round && tc3 < 0)) {
4055 ScmChar c = (char)SCM_INT_VALUE(q) + '0';
4056 SCM_DSTRING_PUTC(ds, c);
4057 if (digs > point) fracdigs++;
4058 break;
4059 } else {
4060 ScmChar c = (char)SCM_INT_VALUE(q) + '1';
4061 if (c > '9') { spilled = TRUE; c = '9'; }
4062 SCM_DSTRING_PUTC(ds, c);
4063 if (digs > point) fracdigs++;
4064 break;
4065 }
4066 }
4067 }
4068 }
4069 if (spilled) spill_fixup(ds, numstart);
4070
4071 /* Notational rounding, if necessary */
4072 if (notational && precision >= 0 && fracdigs > precision) {
4073 notational_rounding(ds, numstart, precision);
4074 }
4075
4076 /* print the trailing zeros if necessary */
4077 if (digs <= point) {
4078 for (;digs < point; digs++) SCM_DSTRING_PUTC(ds, '0');
4079 SCM_DSTRING_PUTC(ds, '.');
4080 if (precision < 0) SCM_DSTRING_PUTC(ds, '0');
4081 }
4082 for (;(digs-point) < precision; digs++) {
4083 SCM_DSTRING_PUTC(ds, '0');
4084 }
4085
4086 show_exponent:
4087 SCM_ASSERT(est < 1000 && est > -1000);
4088 /* prints exponent. we shifted decimal point, so -1. */
4089 est--;
4090 if (est != 0) {
4091 SCM_DSTRING_PUTC(ds, 'e');
4092 if (est < 0) {
4093 Scm_DStringPutc(ds, '-');
4094 est = -est;
4095 }
4096 char zbuf[5]; /* we know est is at most 4 digits */
4097 int echars = sprintf(zbuf, "%d", (int)est);
4098 if (echars < exp_width) {
4099 int fill = exp_width - echars;
4100 while (fill--) {
4101 Scm_DStringPutc(ds, '0');
4102 }
4103 }
4104 Scm_DStringPutz(ds, zbuf, -1);
4105 }
4106 }
4107
4108 static void number_print(ScmObj obj, ScmPort *port,
4109 ScmWriteContext *ctx SCM_UNUSED)
4110 {
4111 Scm_PrintNumber(port, obj, NULL);
4112 }
4113
4114 #define FLT_BUF 65 /* need to hold binary representation of the least fixnum */
4115
4116 static size_t
4117 print_radix_prefix(ScmPort *port, u_long radix)
4118 {
4119 char buf[FLT_BUF];
4120 switch (radix) {
4121 case 2: Scm_Putz("#b", 2, port); return 2;
4122 case 8: Scm_Putz("#o", 2, port); return 2;
4123 case 10: Scm_Putz("#d", 2, port); return 2;
4124 case 16: Scm_Putz("#x", 2, port); return 2;
4125 default:
4126 {
4127 int nc = snprintf(buf, sizeof(buf), "#%lur", radix);
4128 Scm_Putz(buf, nc, port);
4129 return nc;
4130 }
4131 }
4132 }
4133
4134 static size_t
4135 print_number(ScmPort *port, ScmObj obj, u_long flags, ScmNumberFormat *fmt)
4136 {
4137 int use_upper = flags & SCM_NUMBER_FORMAT_USE_UPPER;
4138 int show_plus = flags & SCM_NUMBER_FORMAT_SHOW_PLUS;
4139 int radix = fmt->radix;
4140 int nchars = 0;
4141 char buf[FLT_BUF];
4142
4143 if ((flags & SCM_NUMBER_FORMAT_ALT_RADIX) && SCM_EXACTP(obj)) {
4144 nchars += print_radix_prefix(port, radix);
4145 }
4146
4147 if (SCM_INTP(obj)) {
4148 long value = SCM_INT_VALUE(obj);
4149 if (value < 0) {
4150 SCM_PUTC('-', port);
4151 nchars++;
4152 value = -value; /* this won't overflow */
4153 } else if (show_plus) {
4154 SCM_PUTC('+', port);
4155 nchars++;
4156 }
4157 if (value == 0) { SCM_PUTC('0', port); return nchars+1; }
4158 int i;
4159 for (i = FLT_BUF-1; i >= 0 && value > 0; i--) {
4160 int c = value % radix;
4161 buf[i] = (c<10)?(c+'0'):(use_upper?(c-10+'A'):(c-10+'a'));
4162 value /= radix;
4163 nchars++;
4164 }
4165 Scm_Putz(buf+i+1, FLT_BUF-i-1, port);
4166 return nchars;
4167 } else if (SCM_BIGNUMP(obj)) {
4168 ScmObj s = Scm_BignumToString(SCM_BIGNUM(obj), radix, use_upper);
4169 if(show_plus && Scm_Sign(obj) >= 0) {
4170 Scm_Putc('+', port);
4171 nchars++;
4172 }
4173 Scm_Puts(SCM_STRING(s), port);
4174 return nchars + SCM_STRING_BODY_LENGTH(SCM_STRING_BODY(s));
4175 } else if (SCM_FLONUMP(obj)) {
4176 ScmDString ds;
4177 Scm_DStringInit(&ds);
4178 print_double(&ds, SCM_FLONUM_VALUE(obj), show_plus,
4179 fmt->precision,
4180 fmt->flags&SCM_NUMBER_FORMAT_ROUND_NOTATIONAL,
4181 fmt->exp_lo, fmt->exp_hi, fmt->exp_width);
4182 Scm_Putz(Scm_DStringGetz(&ds), -1, port);
4183 return Scm_DStringSize(&ds);
4184 } else if (SCM_RATNUMP(obj)) {
4185 if (flags & SCM_NUMBER_FORMAT_EXACT_DECIMAL_POINT) {
4186 ScmObj print_exact_decimal_point_number_proc = SCM_UNDEFINED;
4187 SCM_BIND_PROC(print_exact_decimal_point_number_proc,
4188 "print-exact-decimal-point-number",
4189 Scm_GaucheInternalModule());
4190 ScmObj r =
4191 Scm_ApplyRec2(print_exact_decimal_point_number_proc,
4192 obj, SCM_OBJ(port));
4193 if (SCM_INTP(r)) return SCM_INT_VALUE(r);
4194 /* FALLTHROUGH */
4195 }
4196
4197 u_long flags2 = flags & ~SCM_NUMBER_FORMAT_ALT_RADIX;
4198 nchars = print_number(port, SCM_RATNUM_NUMER(obj), flags2, fmt);
4199 Scm_Putc('/', port);
4200 nchars++;
4201 flags2 &= ~SCM_NUMBER_FORMAT_SHOW_PLUS;
4202 nchars += print_number(port, SCM_RATNUM_DENOM(obj), flags2, fmt);
4203 return nchars;
4204 } else if (SCM_COMPNUMP(obj)) {
4205 ScmDString ds;
4206 Scm_DStringInit(&ds);
4207 print_double(&ds, SCM_COMPNUM_REAL(obj), show_plus,
4208 fmt->precision,
4209 fmt->flags&SCM_NUMBER_FORMAT_ROUND_NOTATIONAL,
4210 fmt->exp_lo, fmt->exp_hi, fmt->exp_width);
4211 Scm_Putz(Scm_DStringGetz(&ds), -1, port);
4212 nchars += Scm_DStringSize(&ds);
4213 Scm_DStringTruncate(&ds, 0);
4214 print_double(&ds, SCM_COMPNUM_IMAG(obj), TRUE,
4215 fmt->precision,
4216 fmt->flags&SCM_NUMBER_FORMAT_ROUND_NOTATIONAL,
4217 fmt->exp_lo, fmt->exp_hi, fmt->exp_width);
4218 Scm_Putz(Scm_DStringGetz(&ds), -1, port);
4219 nchars += Scm_DStringSize(&ds);
4220 Scm_Putc('i', port);
4221 return nchars+1;
4222 } else {
4223 Scm_Error("number required: %S", obj);
4224 return 0; /* dummy */
4225 }
4226 }
4227
4228 /* API */
4229 void Scm_NumberFormatInit(ScmNumberFormat* fmt)
4230 {
4231 fmt->flags = 0;
4232 fmt->radix = 10;
4233 fmt->precision = -1;
4234 fmt->exp_lo = -3;
4235 fmt->exp_hi = 10;
4236 fmt->exp_width = 0;
4237 }
4238
4239 /* API */
4240 ScmObj Scm_NumberToString(ScmObj obj, int radix, u_long flags)
4241 {
4242 if (radix < SCM_RADIX_MIN || radix > SCM_RADIX_MAX)
4243 Scm_Error("radix out of range: %d", radix);
4244 ScmPort *p = SCM_PORT(Scm_MakeOutputStringPort(TRUE));
4245 ScmNumberFormat fmt;
4246 Scm_NumberFormatInit(&fmt);
4247 fmt.flags = flags;
4248 fmt.radix = radix;
4249 Scm_PrintNumber(p, obj, &fmt);
4250 return Scm_GetOutputString(p, 0);
4251 }
4252
4253 /* API. FMT can be NULL. */
4254 size_t Scm_PrintNumber(ScmPort *port, ScmObj n, ScmNumberFormat *fmt)
4255 {
4256 ScmNumberFormat defaults;
4257 if (fmt == NULL) {
4258 Scm_NumberFormatInit(&defaults);
4259 fmt = &defaults;
4260 }
4261 return print_number(port, n, fmt->flags, fmt);
4262 }
4263
4264 /* API. FMT can be NULL. Utility to expose Burger&Dybvig algorithm. */
4265 size_t Scm_PrintDouble(ScmPort *port, double d, ScmNumberFormat *fmt)
4266 {
4267 ScmNumberFormat defaults;
4268 if (fmt == NULL) {
4269 Scm_NumberFormatInit(&defaults);
4270 fmt = &defaults;
4271 }
4272 ScmDString ds;
4273 Scm_DStringInit(&ds);
4274 print_double(&ds, d,
4275 fmt->flags & SCM_NUMBER_FORMAT_SHOW_PLUS,
4276 fmt->precision,
4277 fmt->flags & SCM_NUMBER_FORMAT_ROUND_NOTATIONAL,
4278 fmt->exp_lo, fmt->exp_hi, fmt->exp_width);
4279 size_t nchars = Scm_DStringSize(&ds);
4280 Scm_Putz(Scm_DStringGetz(&ds), (int)nchars, port);
4281 return nchars;
4282 }
4283
4284 /*
4285 * Number Parser
4286 *
4287 * <number> : <prefix> <complex>
4288 * <prefix> : <radix> <exactness> | <exactness> <radix>
4289 * <radix> : <empty> | '#b' | '#o' | '#d' | '#x'
4290 * <exactness> : <empty> | '#e' | '#i'
4291 * <complex> : <real>
4292 * | <real> '@' <real> ['p' 'i']
4293 * | <real> '+' <ureal> 'i'
4294 * | <real> '-' <ureal> 'i'
4295 * | <real> '+' 'i'
4296 * | <real> '-' 'i'
4297 * | '+' <ureal> 'i'
4298 * | '-' <ureal> 'i'
4299 * | '+' 'i'
4300 * | '-' 'i'
4301 * <real> : <sign> <ureal>
4302 * <sign> : <empty> | '+' | '-'
4303 * <ureal> : <uinteger>
4304 * | <uinteger> '/' <uinteger>
4305 * | <decimal>
4306 * <uinteger> : <digit>+ '#'*
4307 * <decimal> : <digit10>+ '#'* <suffix>
4308 * | '.' <digit10>+ '#'* <suffix>
4309 * | <digit10>+ '.' <digit10>+ '#'* <suffix>
4310 * | <digit10>+ '#'+ '.' '#'* <suffix>
4311 * <suffix> : <empty> | <exponent-marker> <sign> <digit10>+
4312 * <exponent-marker> : 'e' | 's' | 'f' | 'd' | 'l'
4313 *
4314 * The parser reads characters from on-memory buffer.
4315 * Multibyte strings are filtered out in the early stage of
4316 * parsing, so the subroutines assume the buffer contains
4317 * only ASCII chars.
4318 */
4319
4320 struct numread_packet {
4321 const char *buffer; /* original buffer */
4322 int buflen; /* original length */
4323 int radix; /* radix (can be overridden by prefix) */
4324 int noradixprefix; /* do not allow radix prefix */
4325 int exactness; /* exactness; see enum below */
4326 int padread; /* '#' padding has been read */
4327 int explicit; /* explicit prefix is appeared */
4328 int strict; /* reject gauche extension */
4329 int throwerror; /* throws error on parse, instead of
4330 returning #f. */
4331 };
4332
4333 enum { /* used in the exactness flag */
4334 NOEXACT, EXACT, INEXACT
4335 };
4336
4337 /* Max digits D such that all D-digit radix R integers fit in signed
4338 long, i.e. R^(D+1)-1 <= LONG_MAX */
4339 static long longdigs[SCM_RADIX_MAX-SCM_RADIX_MIN+1] = { 0 };
4340
4341 /* Max integer I such that reading next digit (in radix R) will overflow
4342 long integer. floor(LONG_MAX/R - R). */
4343 static u_long longlimit[SCM_RADIX_MAX-SCM_RADIX_MIN+1] = { 0 };
4344
4345 /* An integer table of R^D, which is a "big digit" to be added
4346 into bignum. */
4347 static u_long bigdig[SCM_RADIX_MAX-SCM_RADIX_MIN+1] = { 0 };
4348
4349 static ScmObj numread_error(const char *msg, struct numread_packet *ctx);
4350
4351 /* Returns either small integer, bignum, or #f.
4352 initval may be a Scheme integer that will be 'concatenated' before
4353 the integer to be read; it is used to read floating-point number.
4354 Note that value_big may keep denormalized bignum. */
4355 static ScmObj read_uint(const char **strp, int *lenp,
4356 struct numread_packet *ctx,
4357 ScmObj initval)
4358 {
4359 const char *str = *strp;
4360 int digread = FALSE;
4361 int len = *lenp;
4362 int radix = ctx->radix;
4363 int digits = 0, diglimit = longdigs[radix-SCM_RADIX_MIN];
4364 int underscore_read = FALSE;
4365 u_long limit = longlimit[radix-SCM_RADIX_MIN], bdig = bigdig[radix-SCM_RADIX_MIN];
4366 u_long value_int = 0;
4367 ScmBignum *value_big = NULL;
4368 static const char tab[] = "0123456789abcdefghijklmnopqrstuvwxyz";
4369
4370 if (!SCM_FALSEP(initval)) {
4371 if (SCM_INTP(initval)) {
4372 if ((u_long)SCM_INT_VALUE(initval) > limit) {
4373 value_big = Scm_MakeBignumWithSize(4, SCM_INT_VALUE(initval));
4374 } else {
4375 value_int = SCM_INT_VALUE(initval);
4376 }
4377 } else if (SCM_BIGNUMP(initval)) {
4378 value_big = SCM_BIGNUM(Scm_BignumCopy(SCM_BIGNUM(initval)));
4379 }
4380 digread = TRUE;
4381 } else if (*str == '0') {
4382 /* Ignore leading 0's, to avoid unnecessary bignum operations. */
4383 while (len > 0 && *str == '0') { str++; len--; }
4384 digread = TRUE;
4385 }
4386
4387 for (; len > 0; str++, len--) {
4388 int digval = -1;
4389 char c = tolower(*str);
4390 if (c == '_') {
4391 if (ctx->strict || str == *strp) return SCM_FALSE;
4392 /* srfi-169 - allow '_' in digits for readability
4393 when number is expliticly prefixed. */
4394 if (underscore_read || (!digread && digits == 0)) {
4395 /* Don't allow underscore at the beginning, or
4396 consecutive underscores */
4397 return SCM_FALSE;
4398 }
4399 underscore_read = TRUE;
4400 continue;
4401 }
4402
4403 if (ctx->padread) {
4404 if (c == '#') digval = 0;
4405 else break;
4406 } else if (digread && c == '#') {
4407 digval = 0;
4408 ctx->padread = TRUE;
4409 if (ctx->exactness == NOEXACT) {
4410 ctx->exactness = INEXACT;
4411 }
4412 } else {
4413 for (const char *ptab = tab; ptab < tab+radix; ptab++) {
4414 if (c == *ptab) {
4415 digval = (int)(ptab-tab);
4416 digread = TRUE;
4417 break;
4418 }
4419 }
4420 }
4421 if (digval < 0) break;
4422 underscore_read = FALSE;
4423 value_int = value_int * radix + digval;
4424 digits++;
4425 if (value_big == NULL) {
4426 if (value_int >= limit) {
4427 value_big = Scm_MakeBignumWithSize(4, value_int);
4428 value_int = digits = 0;
4429 }
4430 } else if (digits > diglimit) {
4431 value_big = Scm_BignumAccMultAddUI(value_big, bdig, value_int);
4432 value_int = digits = 0;
4433 }
4434 }
4435 if (str == *strp && SCM_FALSEP(initval)) return SCM_FALSE;
4436 *strp = str; *lenp = len;
4437 if (underscore_read) {
4438 /* integer literal can't end with '_' */
4439 return SCM_FALSE;
4440 }
4441
4442 if (value_big == NULL) return Scm_MakeInteger(value_int);
4443 if (digits > 0) {
4444 value_big = Scm_BignumAccMultAddUI(value_big,
4445 ipow(radix, digits),
4446 value_int);
4447 }
4448 return Scm_NormalizeBignum(SCM_BIGNUM(value_big));
4449 }
4450
4451 /*
4452 * Find a double number closest to f * 10^e, using z as the starting
4453 * approximation. The algorithm (and its name) is taken from Will Clinger's
4454 * paper "How to Read Floating Point Numbers Accurately", in the ACM
4455 * SIGPLAN '90, pp.92--101.
4456 * The algorithm is modified to take advantage of coherency between loops.
4457 */
4458 static double algorithmR(ScmObj f, int e, double z)
4459 {
4460 int k, s;
4461 ScmObj m = Scm_DecodeFlonum(z, &k, &s);
4462 ScmObj x, y;
4463 IEXPT10_INIT();
4464 retry:
4465 if (k >= 0) {
4466 if (e >= 0) {
4467 x = Scm_Mul(f, iexpt10(e));
4468 y = Scm_Ash(m, k);
4469 } else {
4470 x = f;
4471 y = Scm_Ash(Scm_Mul(m, iexpt10(-e)), k);
4472 }
4473 } else {
4474 if (e >= 0) {
4475 x = Scm_Ash(Scm_Mul(f, iexpt10(e)), -k);
4476 y = m;
4477 } else {
4478 x = Scm_Ash(f, -k);
4479 y = Scm_Mul(m, iexpt10(-e));
4480 }
4481 }
4482 int kprev = k;
4483
4484 /* compare */
4485 for (;;) {
4486 /*Scm_Printf(SCM_CURERR, "z=%.20lg,\nx=%S,\ny=%S\nf=%S\nm=%S\ne=%d, k=%d\n", z, x, y, f, m, e, k);*/
4487 /* compare */
4488 int sign_d = Scm_NumCmp(x, y);
4489 ScmObj abs_d = (sign_d > 0)? Scm_Sub(x, y) : Scm_Sub(y, x);
4490 ScmObj d2 = Scm_Ash(Scm_Mul(m, abs_d), 1);
4491 switch (Scm_NumCmp(d2, y)) {
4492 case -1: /* d2 < y */
4493 if (Scm_NumCmp(m, SCM_2_52) == 0
4494 && sign_d < 0
4495 && k > -1074
4496 && Scm_NumCmp(Scm_Ash(d2, 1), y) > 0) {
4497 goto prevfloat;
4498 } else {
4499 return ldexp(Scm_GetDouble(m), k);
4500 }
4501 case 0: /* d2 == y */
4502 if (!Scm_OddP(m)) {
4503 if (Scm_NumCmp(m, SCM_2_52) == 0
4504 && sign_d < 0) {
4505 goto prevfloat;
4506 } else {
4507 return ldexp(Scm_GetDouble(m), k);
4508 }
4509 } else if (sign_d < 0) {
4510 goto prevfloat;
4511 } else {
4512 goto nextfloat;
4513 }
4514 default:
4515 if (sign_d < 0) goto prevfloat;
4516 else goto nextfloat;
4517 }
4518 prevfloat:
4519 m = Scm_Sub(m, SCM_MAKE_INT(1));
4520 if (k > -1074 && Scm_NumCmp(m, SCM_2_52) < 0) {
4521 m = Scm_Ash(m, 1);
4522 k--;
4523 }
4524 goto next;
4525 nextfloat:
4526 m = Scm_Add(m, SCM_MAKE_INT(1));
4527 if (Scm_NumCmp(m, SCM_2_53) >= 0) {
4528 m = Scm_Ash(m, -1);
4529 k++;
4530 }
4531 /*FALLTHROUGH*/
4532 next:
4533 if (kprev >= 0) {
4534 if (k >= 0) {
4535 /* k stays positive. x is invariant */
4536 if (e >= 0) {
4537 y = Scm_Ash(m, k);
4538 } else {
4539 y = Scm_Ash(Scm_Mul(m, iexpt10(-e)), k);
4540 }
4541 } else {
4542 /* k turned to negative */
4543 goto retry;
4544 }
4545 } else {
4546 if (k < 0) {
4547 /* k stays negative. */
4548 if (e >= 0) {
4549 if (k != kprev) x = Scm_Ash(Scm_Mul(f, iexpt10(e)), -k);
4550 y = m;
4551 } else {
4552 if (k != kprev) x = Scm_Ash(f, -k);
4553 y = Scm_Mul(m, iexpt10(-e));
4554 }
4555 } else {
4556 /* k turned to positive */
4557 goto retry;
4558 }
4559 }
4560 }
4561 /*NOTREACHED*/
4562 }
4563
4564 static ScmObj read_real(const char **strp, int *lenp,
4565 struct numread_packet *ctx)
4566 {
4567 int minusp = FALSE, exp_minusp = FALSE, exp_overflow = FALSE;
4568 int sign_seen = FALSE;
4569 int fracdigs = 0;
4570 long exponent = 0;
4571 ScmObj intpart, fraction;
4572 const char *mark; /* will point (*strp)[1] if there's a sign,
4573 otherwise (*strp)[0], to check if the
4574 given str has valid content. */
4575
4576 switch (**strp) {
4577 case '-': minusp = TRUE;
4578 /* FALLTHROUGH */
4579 case '+':
4580 (*strp)++; (*lenp)--; sign_seen = TRUE;
4581 }
4582 if ((*lenp) <= 0) return SCM_FALSE;
4583 mark = *strp;
4584
4585 /* Recognize specials */
4586 if (sign_seen && (*lenp) >= 5) {
4587 if (strncasecmp(*strp, "inf.0", 5) == 0) {
4588 (*strp) += 5; (*lenp) -= 5;
4589 return minusp?SCM_NEGATIVE_INFINITY:SCM_POSITIVE_INFINITY;
4590 }
4591 if (strncasecmp(*strp, "nan.0", 5) == 0) {
4592 (*strp) += 5; (*lenp) -= 5;
4593 return SCM_NAN;
4594 }
4595 }
4596
4597 /* Read integral part */
4598 if (**strp != '.') {
4599 intpart = read_uint(strp, lenp, ctx, SCM_FALSE);
4600 if (SCM_FALSEP(intpart)) return SCM_FALSE;
4601 if ((*lenp) <= 0) {
4602 if (minusp) intpart = Scm_Negate(intpart);
4603 if (ctx->exactness == INEXACT) {
4604 return Scm_Inexact(intpart);
4605 } else {
4606 return intpart;
4607 }
4608 }
4609 if (**strp == '/') {
4610 /* possibly rational */
4611 ScmObj denom;
4612 int lensave;
4613
4614 if ((*lenp) <= 1 || mark == *strp) return SCM_FALSE;
4615 (*strp)++; (*lenp)--;
4616 lensave = *lenp;
4617 denom = read_uint(strp, lenp, ctx, SCM_FALSE);
4618 if (SCM_FALSEP(denom)) return SCM_FALSE;
4619 if (SCM_EXACT_ZERO_P(denom)) {
4620 if (lensave > *lenp) {
4621 if (ctx->exactness != INEXACT) {
4622 return numread_error("(exact infinity/nan is not supported.)",
4623 ctx);
4624 }
4625 if (SCM_EXACT_ZERO_P(intpart)) return SCM_NAN;
4626 return minusp? SCM_NEGATIVE_INFINITY:SCM_POSITIVE_INFINITY;
4627 } else {
4628 return SCM_FALSE;
4629 }
4630 }
4631 if (minusp) intpart = Scm_Negate(intpart);
4632 if (ctx->exactness == INEXACT) {
4633 return Scm_Inexact(Scm_Div(intpart, denom));
4634 } else {
4635 return Scm_MakeRational(intpart, denom);
4636 }
4637 }
4638 /* fallthrough */
4639 } else {
4640 intpart = SCM_FALSE; /* indicate there was no intpart */
4641 }
4642
4643 /* Read fractional part.
4644 At this point, simple integer is already eliminated. */
4645 if (**strp == '.') {
4646 if (ctx->radix != 10) {
4647 return numread_error("(only 10-based fraction is supported)", ctx);
4648 }
4649 (*strp)++; (*lenp)--;
4650 const char *fracp = *strp;
4651 fraction = read_uint(strp, lenp, ctx, intpart);
4652 if (SCM_FALSEP(fraction)) return SCM_FALSE;
4653 /* Count fraction digits. we can't simply do *strp - fracp,
4654 for fraction part may contain '_' (srfi-169). */
4655 for (; fracp < *strp; fracp++) {
4656 if (*fracp != '_') fracdigs++;
4657 }
4658 } else {
4659 fraction = intpart;
4660 }
4661
4662 if (SCM_FALSEP(intpart)) {
4663 if (fracdigs == 0) return SCM_FALSE; /* input was "." */
4664 }
4665 if (mark == *strp) return SCM_FALSE;
4666
4667 /* Read exponent. */
4668 if (*lenp > 0 && strchr("eEsSfFdDlL", (int)**strp)) {
4669 (*strp)++;
4670 if (--(*lenp) <= 0) return SCM_FALSE;
4671 switch (**strp) {
4672 case '-': exp_minusp = TRUE;
4673 /*FALLTHROUGH*/
4674 case '+':
4675 (*strp)++;
4676 if (--(*lenp) <= 0) return SCM_FALSE;
4677 }
4678 int underscore = FALSE;
4679 const char *str = *strp;
4680 for (; *lenp > 0; (*strp)++, (*lenp)--) {
4681 int c = **strp;
4682 if (c == '_') {
4683 if (underscore || str == *strp || *lenp == 1) return SCM_FALSE;
4684 underscore = TRUE;
4685 continue;
4686 }
4687 if (!isdigit(c)) break;
4688 underscore = FALSE;
4689 if (!exp_overflow) {
4690 exponent = exponent * 10 + (c - '0');
4691 /* Check obviously wrong exponent range. More subtle check
4692 will be done later. */
4693 if (exponent >= MAX_EXPONENT) {
4694 exp_overflow = TRUE;
4695 }
4696 }
4697 }
4698 if (exp_minusp) exponent = -exponent;
4699 }
4700 if (exp_overflow) {
4701 if (ctx->exactness == EXACT) {
4702 /* Although we can represent such a number using bignum and
4703 ratnum, such large (or small) exponent is highly unusual
4704 and we assume we can report implementation limitation
4705 violation. */
4706 return numread_error("(such an exact number is out of implementation limitation)",
4707 ctx);
4708 }
4709 if (exp_minusp || SCM_EQ(fraction, SCM_MAKE_INT(0))) {
4710 return Scm_MakeFlonum(minusp? -0.0:0.0);
4711 } else {
4712 return minusp? SCM_NEGATIVE_INFINITY : SCM_POSITIVE_INFINITY;
4713 }
4714 }
4715
4716 /*Scm_Printf(SCM_CURERR, "fraction=%S, exponent=%d\n", fraction, exponent);*/
4717
4718 /* Compose the number. */
4719 if (ctx->exactness == EXACT) {
4720 /* Explicit exact number. We can continue exact arithmetic
4721 (it may end up ratnum) */
4722 ScmObj e = Scm_Mul(fraction,
4723 Scm_ExactIntegerExpt(SCM_MAKE_INT(10),
4724 Scm_MakeInteger(exponent-fracdigs)));
4725 if (minusp) return Scm_Negate(e);
4726 else return e;
4727 }
4728
4729 /* Get double approximaiton of fraction. If fraction >= 2^53 we'll
4730 only get approximation, but the error will be corrected in
4731 AlgorithmR. We have to be careful, however, not to overflow
4732 the following GetDouble call. */
4733 int raise_factor = exponent - fracdigs;
4734 double realnum = Scm_GetDouble(fraction);
4735
4736 if (SCM_IS_INF(realnum)) {
4737 /* We have too many digits to fit in double. We can still get finite
4738 number if raise_factor is small, but we need to calculate realnum
4739 via rational. */
4740 if (raise_factor >= 0) {
4741 /* Exponent is too big. */
4742 return (minusp? SCM_NEGATIVE_INFINITY : SCM_POSITIVE_INFINITY);
4743 }
4744 IEXPT10_INIT();
4745 realnum = Scm_GetDouble(Scm_Div(fraction, iexpt10(-raise_factor)));
4746 } else {
4747 realnum = raise_pow10(realnum, raise_factor);
4748 }
4749
4750 if (SCM_IS_INF(realnum)) {
4751 /* Exponent is too big. */
4752 return (minusp? SCM_NEGATIVE_INFINITY : SCM_POSITIVE_INFINITY);
4753 }
4754
4755 if (realnum > 0.0
4756 && (Scm_NumCmp(fraction, SCM_2_52) > 0
4757 || raise_factor > MAX_EXACT_10_EXP
4758 || raise_factor < -MAX_EXACT_10_EXP)) {
4759 realnum = algorithmR(fraction, raise_factor, realnum);
4760 }
4761 if (minusp) realnum = -realnum;
4762 return Scm_MakeFlonum(realnum);
4763 }
4764
4765 /* Entry point */
4766 static ScmObj read_number(struct numread_packet *ctx)
4767 {
4768 int radix_seen = 0, exactness_seen = 0, sign_seen = 0;
4769
4770 const char *str = ctx->buffer;
4771 int len = ctx->buflen;
4772
4773 #define CHK_EXACT_COMPLEX() \
4774 do { \
4775 if (ctx->exactness == EXACT) { \
4776 return numread_error("(exact complex number is not supported)", \
4777 ctx); \
4778 } \
4779 } while (0)
4780
4781 /* check suggested radix. */
4782 if (ctx->radix < SCM_RADIX_MIN || ctx->radix > SCM_RADIX_MAX) {
4783 return SCM_FALSE;
4784 }
4785
4786 /* start from prefix part */
4787 while (len >= 0) {
4788 if (*str != '#') break;
4789 str++;
4790 switch (*str++) {
4791 case 'x':; case 'X':;
4792 if (ctx->noradixprefix || radix_seen) return SCM_FALSE;
4793 ctx->radix = 16; radix_seen++;
4794 ctx->explicit = TRUE;
4795 len -= 2;
4796 continue;
4797 case 'o':; case 'O':;
4798 if (ctx->noradixprefix || radix_seen) return SCM_FALSE;
4799 ctx->radix = 8; radix_seen++;
4800 ctx->explicit = TRUE;
4801 len -= 2;
4802 continue;
4803 case 'b':; case 'B':;
4804 if (ctx->noradixprefix || radix_seen) return SCM_FALSE;
4805 ctx->radix = 2; radix_seen++;
4806 ctx->explicit = TRUE;
4807 len -= 2;
4808 continue;
4809 case 'd':; case 'D':;
4810 if (ctx->noradixprefix || radix_seen) return SCM_FALSE;
4811 ctx->radix = 10; radix_seen++;
4812 ctx->explicit = TRUE;
4813 len -= 2;
4814 continue;
4815 case 'e':; case 'E':;
4816 if (exactness_seen) return SCM_FALSE;
4817 ctx->exactness = EXACT; exactness_seen++;
4818 ctx->explicit = TRUE;
4819 len -= 2;
4820 continue;
4821 case 'i':; case 'I':;
4822 if (exactness_seen) return SCM_FALSE;
4823 ctx->exactness = INEXACT; exactness_seen++;
4824 ctx->explicit = TRUE;
4825 len -= 2;
4826 continue;
4827 case '0': case '1': case '2': case '3': case '4':
4828 case '5': case '6': case '7': case '8': case '9':
4829 if (ctx->noradixprefix || ctx->strict || radix_seen) return SCM_FALSE;
4830 else {
4831 ScmSize nread = 0;
4832 long radix = Scm_ParseDigitsAsLong(--str, --len, 10, &nread);
4833 if (radix < SCM_RADIX_MIN || radix > SCM_RADIX_MAX) return SCM_FALSE;
4834 str += nread; len -= nread;
4835 if (len <= 0) return SCM_FALSE;
4836 if (*str != 'r' && *str != 'R') return SCM_FALSE;
4837 str++; len--;
4838 ctx->radix = radix; radix_seen++;
4839 ctx->explicit = TRUE;
4840 continue;
4841 }
4842 }
4843 return SCM_FALSE;
4844 }
4845 if (len <= 0) return SCM_FALSE;
4846
4847 /* number body. need to check the special case of pure imaginary,
4848 and also eliminates some confusing cases. */
4849 if (*str == '+' || *str == '-') {
4850 if (len == 1) return SCM_FALSE;
4851 if (len == 2 && (str[1] == 'i' || str[1] == 'I')) {
4852 CHK_EXACT_COMPLEX();
4853 return Scm_MakeComplex(0.0, (*str == '+')? 1.0 : -1.0);
4854 }
4855 sign_seen = TRUE;
4856 }
4857
4858 ScmObj realpart = read_real(&str, &len, ctx);
4859 if (SCM_FALSEP(realpart) || len == 0) return realpart;
4860
4861 switch (*str) {
4862 case '@':
4863 /* polar representation of complex*/
4864 if (len <= 1) {
4865 return SCM_FALSE;
4866 } else {
4867 str++; len--;
4868 ScmObj angle = read_real(&str, &len, ctx);
4869 if (SCM_FALSEP(angle)) return SCM_FALSE;
4870 /* Gauche extension: X@Ypi */
4871 int pi_angle = (len == 2 && str[0] == 'p' && str[1] == 'i');
4872 if (!pi_angle && len != 0) return SCM_FALSE;
4873 CHK_EXACT_COMPLEX();
4874 double dmag = Scm_GetDouble(realpart);
4875 double dangle = Scm_GetDouble(angle);
4876 return (pi_angle
4877 ? Scm_MakeComplexPolarPI(dmag, dangle)
4878 : Scm_MakeComplexPolar(dmag, dangle));
4879 }
4880 case '+':
4881 case '-':
4882 /* rectangular representation of complex */
4883 if (len <= 1) {
4884 return SCM_FALSE;
4885 } else if (len == 2 && (str[1] == 'i' || str[1] == 'I')) {
4886 return Scm_MakeComplex(Scm_GetDouble(realpart),
4887 (*str == '+' ? 1.0 : -1.0));
4888 } else {
4889 ScmObj imagpart = read_real(&str, &len, ctx);
4890 if (SCM_FALSEP(imagpart) || len != 1
4891 || (*str != 'i' && *str != 'I')) {
4892 return SCM_FALSE;
4893 }
4894 CHK_EXACT_COMPLEX();
4895 if (Scm_Sign(imagpart) == 0) return realpart;
4896 return Scm_MakeComplex(Scm_GetDouble(realpart),
4897 Scm_GetDouble(imagpart));
4898 }
4899 case 'i':
4900 case 'I':
4901 /* '+' <ureal> 'i' or '-' <ureal> 'i' */
4902 if (!sign_seen || len != 1) return SCM_FALSE;
4903 CHK_EXACT_COMPLEX();
4904 if (Scm_Sign(realpart) == 0) return Scm_MakeFlonum(0.0);
4905 else return Scm_MakeComplex(0.0, Scm_GetDouble(realpart));
4906 default:
4907 return SCM_FALSE;
4908 }
4909 }
4910
4911 static ScmObj numread_error(const char *msg, struct numread_packet *ctx)
4912 {
4913 if (ctx->throwerror) {
4914 Scm_Error("bad number format %s: %A", msg,
4915 Scm_MakeString(ctx->buffer, ctx->buflen,
4916 ctx->buflen, 0));
4917 }
4918 return SCM_FALSE;
4919 }
4920
4921 /* FLAGS is enum ScmNumberFormatFlags (see number.h). Only some of the
4922 flags are recognized for printing numbers. */
4923 ScmObj Scm_StringToNumber(ScmString *str, int radix, u_long flags)
4924 {
4925 ScmSmallInt len, size;
4926 const char *p = Scm_GetStringContent(str, &size, &len, NULL);
4927 if (size != len) {
4928 /* This can't be a proper number. */
4929 return SCM_FALSE;
4930 } else {
4931 struct numread_packet ctx;
4932 ctx.buffer = p;
4933 ctx.buflen = size;
4934 ctx.exactness = ((flags&SCM_NUMBER_FORMAT_EXACT)
4935 ? EXACT
4936 : ((flags&SCM_NUMBER_FORMAT_INEXACT)
4937 ? INEXACT
4938 : NOEXACT));
4939 ctx.padread = FALSE;
4940 ctx.explicit = FALSE;
4941 ctx.strict = flags&SCM_NUMBER_FORMAT_STRICT_R7RS;
4942 ctx.throwerror = FALSE;
4943 ctx.radix = radix;
4944 ctx.noradixprefix = flags&SCM_NUMBER_FORMAT_ALT_RADIX;
4945 return read_number(&ctx);
4946 }
4947 }
4948
4949 /*===============================================================
4950 * Initialization
4951 */
4952
4953 ScmObj Scm__ConstObjs[SCM_NUM_CONST_OBJS] = { SCM_FALSE };
4954
4955 void Scm__InitNumber(void)
4956 {
4957 ScmModule *mod = Scm_GaucheModule();
4958
4959 for (int radix = SCM_RADIX_MIN; radix <= SCM_RADIX_MAX; radix++) {
4960 longlimit[radix-SCM_RADIX_MIN] =
4961 (u_long)floor((double)LONG_MAX/radix - radix);
4962 /* Find max D where R^(D+1)-1 <= LONG_MAX */
4963 u_long n = 1;
4964 for (int i = 0; ; i++, n *= radix) {
4965 if (n >= (u_long)(LONG_MAX/radix)) {
4966 longdigs[radix-SCM_RADIX_MIN] = i-1;
4967 bigdig[radix-SCM_RADIX_MIN] = n;
4968 break;
4969 }
4970 }
4971 }
4972
4973 SCM_2_63 = Scm_Ash(SCM_MAKE_INT(1), 63);
4974 SCM_2_64 = Scm_Ash(SCM_MAKE_INT(1), 64);
4975 SCM_2_64_MINUS_1 = Scm_Sub(SCM_2_64, SCM_MAKE_INT(1));
4976 SCM_2_52 = Scm_Ash(SCM_MAKE_INT(1), 52);
4977 SCM_2_53 = Scm_Ash(SCM_MAKE_INT(1), 53);
4978 SCM_MINUS_2_63 = Scm_Negate(SCM_2_63);
4979 SCM_2_32 = Scm_Ash(SCM_MAKE_INT(1), 32);
4980 SCM_2_31 = Scm_Ash(SCM_MAKE_INT(1), 31);
4981 SCM_MINUS_2_31 = Scm_Negate(SCM_2_31);
4982 SCM_MIN_DENORMALIZED_FLONUM_EXACT =
4983 Scm_Reciprocal(Scm_Ash(SCM_MAKE_INT(1), 1075));
4984 SCM_MAX_FINITE_FLONUM_EXACT = Scm_Add(Scm_Sub(Scm_Ash(SCM_MAKE_INT(1), 1024),
4985 Scm_Ash(SCM_MAKE_INT(1), 971)),
4986 Scm_Sub(Scm_Ash(SCM_MAKE_INT(1), 970),
4987 SCM_MAKE_INT(1)));
4988
4989 SCM_POSITIVE_INFINITY = Scm_MakeFlonum(SCM_DBL_POSITIVE_INFINITY);
4990 SCM_NEGATIVE_INFINITY = Scm_MakeFlonum(SCM_DBL_NEGATIVE_INFINITY);
4991 SCM_NAN = Scm_MakeFlonum(SCM_DBL_NAN);
4992
4993 SCM_SIZE_T_MAX = Scm_MakeIntegerU64(SIZE_MAX);
4994 SCM_SSIZE_T_MAX = Scm_MakeInteger64(SSIZE_MAX);
4995 SCM_SSIZE_T_MIN = Scm_MakeInteger64(-(SSIZE_MAX-1));
4996 SCM_PTRDIFF_T_MAX = Scm_MakeInteger64(PTRDIFF_MAX);
4997 SCM_PTRDIFF_T_MIN = Scm_MakeInteger64(-(PTRDIFF_MAX-1));
4998 SCM_INTPTR_T_MIN = Scm_Negate(Scm_Expt(SCM_MAKE_INT(1L<<CHAR_BIT),
4999 SCM_MAKE_INT(sizeof(intptr_t)-1)));
5000 SCM_INTPTR_T_MAX = Scm_Sub(Scm_Expt(SCM_MAKE_INT(1L<<CHAR_BIT),
5001 SCM_MAKE_INT(sizeof(intptr_t)-1)),
5002 SCM_MAKE_INT(1));
5003 SCM_UINTPTR_T_MAX = Scm_Sub(Scm_Expt(SCM_MAKE_INT(1L<<CHAR_BIT),
5004 SCM_MAKE_INT(sizeof(intptr_t))),
5005 SCM_MAKE_INT(1));
5006
5007 dexpt2_minus_52 = ldexp(1.0, -52);
5008 dexpt2_minus_53 = ldexp(1.0, -53);
5009
5010 Scm_InitBuiltinGeneric(&generic_add, "object-+", mod);
5011 Scm_InitBuiltinGeneric(&generic_sub, "object--", mod);
5012 Scm_InitBuiltinGeneric(&generic_mul, "object-*", mod);
5013 Scm_InitBuiltinGeneric(&generic_div, "object-/", mod);
5014
5015 #ifdef DOUBLE_ARMENDIAN
5016 check_armendian();
5017 #endif /*DOUBLE_ARMENDIAN*/
5018
5019 (void)SCM_INTERNAL_MUTEX_INIT(default_endian_mutex);
5020
5021 #ifdef COUNT_FLONUM_ALLOC
5022 Scm_AddCleanupHandler(report_flonum_count, NULL);
5023 #endif
5024 }