gcd and lcm support inexact integer arguments.
[bpt/guile.git] / libguile / numbers.c
1 /* Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2 * 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012,
3 * 2013 Free Software Foundation, Inc.
4 *
5 * Portions Copyright 1990, 1991, 1992, 1993 by AT&T Bell Laboratories
6 * and Bellcore. See scm_divide.
7 *
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 3 of
12 * the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * 02110-1301 USA
23 */
24
25 \f
26 /* General assumptions:
27 * All objects satisfying SCM_BIGP() are too large to fit in a fixnum.
28 * If an object satisfies integer?, it's either an inum, a bignum, or a real.
29 * If floor (r) == r, r is an int, and mpz_set_d will DTRT.
30 * XXX What about infinities? They are equal to their own floor! -mhw
31 * All objects satisfying SCM_FRACTIONP are never an integer.
32 */
33
34 /* TODO:
35
36 - see if special casing bignums and reals in integer-exponent when
37 possible (to use mpz_pow and mpf_pow_ui) is faster.
38
39 - look in to better short-circuiting of common cases in
40 integer-expt and elsewhere.
41
42 - see if direct mpz operations can help in ash and elsewhere.
43
44 */
45
46 #ifdef HAVE_CONFIG_H
47 # include <config.h>
48 #endif
49
50 #include <verify.h>
51
52 #include <math.h>
53 #include <string.h>
54 #include <unicase.h>
55 #include <unictype.h>
56
57 #if HAVE_COMPLEX_H
58 #include <complex.h>
59 #endif
60
61 #include <stdarg.h>
62
63 #include "libguile/_scm.h"
64 #include "libguile/feature.h"
65 #include "libguile/ports.h"
66 #include "libguile/root.h"
67 #include "libguile/smob.h"
68 #include "libguile/strings.h"
69 #include "libguile/bdw-gc.h"
70
71 #include "libguile/validate.h"
72 #include "libguile/numbers.h"
73 #include "libguile/deprecation.h"
74
75 #include "libguile/eq.h"
76
77 /* values per glibc, if not already defined */
78 #ifndef M_LOG10E
79 #define M_LOG10E 0.43429448190325182765
80 #endif
81 #ifndef M_LN2
82 #define M_LN2 0.69314718055994530942
83 #endif
84 #ifndef M_PI
85 #define M_PI 3.14159265358979323846
86 #endif
87
88 /* FIXME: We assume that FLT_RADIX is 2 */
89 verify (FLT_RADIX == 2);
90
91 typedef scm_t_signed_bits scm_t_inum;
92 #define scm_from_inum(x) (scm_from_signed_integer (x))
93
94 /* Tests to see if a C double is neither infinite nor a NaN.
95 TODO: if it's available, use C99's isfinite(x) instead */
96 #define DOUBLE_IS_FINITE(x) (!isinf(x) && !isnan(x))
97
98 /* On some platforms, isinf(x) returns 0, 1 or -1, indicating the sign
99 of the infinity, but other platforms return a boolean only. */
100 #define DOUBLE_IS_POSITIVE_INFINITY(x) (isinf(x) && ((x) > 0))
101 #define DOUBLE_IS_NEGATIVE_INFINITY(x) (isinf(x) && ((x) < 0))
102
103 /* Test an inum to see if it can be converted to a double without loss
104 of precision. Note that this will sometimes return 0 even when 1
105 could have been returned, e.g. for large powers of 2. It is designed
106 to be a fast check to optimize common cases. */
107 #define INUM_LOSSLESSLY_CONVERTIBLE_TO_DOUBLE(n) \
108 (SCM_I_FIXNUM_BIT-1 <= DBL_MANT_DIG \
109 || ((n) ^ ((n) >> (SCM_I_FIXNUM_BIT-1))) < (1L << DBL_MANT_DIG))
110
111 #if ! HAVE_DECL_MPZ_INITS
112
113 /* GMP < 5.0.0 lacks `mpz_inits' and `mpz_clears'. Provide them. */
114
115 #define VARARG_MPZ_ITERATOR(func) \
116 static void \
117 func ## s (mpz_t x, ...) \
118 { \
119 va_list ap; \
120 \
121 va_start (ap, x); \
122 while (x != NULL) \
123 { \
124 func (x); \
125 x = va_arg (ap, mpz_ptr); \
126 } \
127 va_end (ap); \
128 }
129
130 VARARG_MPZ_ITERATOR (mpz_init)
131 VARARG_MPZ_ITERATOR (mpz_clear)
132
133 #endif
134
135 \f
136
137 /*
138 Wonder if this might be faster for some of our code? A switch on
139 the numtag would jump directly to the right case, and the
140 SCM_I_NUMTAG code might be faster than repeated SCM_FOOP tests...
141
142 #define SCM_I_NUMTAG_NOTNUM 0
143 #define SCM_I_NUMTAG_INUM 1
144 #define SCM_I_NUMTAG_BIG scm_tc16_big
145 #define SCM_I_NUMTAG_REAL scm_tc16_real
146 #define SCM_I_NUMTAG_COMPLEX scm_tc16_complex
147 #define SCM_I_NUMTAG(x) \
148 (SCM_I_INUMP(x) ? SCM_I_NUMTAG_INUM \
149 : (SCM_IMP(x) ? SCM_I_NUMTAG_NOTNUM \
150 : (((0xfcff & SCM_CELL_TYPE (x)) == scm_tc7_number) ? SCM_TYP16(x) \
151 : SCM_I_NUMTAG_NOTNUM)))
152 */
153 /* the macro above will not work as is with fractions */
154
155
156 /* Default to 1, because as we used to hard-code `free' as the
157 deallocator, we know that overriding these functions with
158 instrumented `malloc' / `free' is OK. */
159 int scm_install_gmp_memory_functions = 1;
160 static SCM flo0;
161 static SCM exactly_one_half;
162 static SCM flo_log10e;
163
164 #define SCM_SWAP(x, y) do { SCM __t = x; x = y; y = __t; } while (0)
165
166 /* FLOBUFLEN is the maximum number of characters neccessary for the
167 * printed or scm_string representation of an inexact number.
168 */
169 #define FLOBUFLEN (40+2*(sizeof(double)/sizeof(char)*SCM_CHAR_BIT*3+9)/10)
170
171
172 #if !defined (HAVE_ASINH)
173 static double asinh (double x) { return log (x + sqrt (x * x + 1)); }
174 #endif
175 #if !defined (HAVE_ACOSH)
176 static double acosh (double x) { return log (x + sqrt (x * x - 1)); }
177 #endif
178 #if !defined (HAVE_ATANH)
179 static double atanh (double x) { return 0.5 * log ((1 + x) / (1 - x)); }
180 #endif
181
182 /* mpz_cmp_d in GMP before 4.2 didn't recognise infinities, so
183 xmpz_cmp_d uses an explicit check. Starting with GMP 4.2 (released
184 in March 2006), mpz_cmp_d now handles infinities properly. */
185 #if 1
186 #define xmpz_cmp_d(z, d) \
187 (isinf (d) ? (d < 0.0 ? 1 : -1) : mpz_cmp_d (z, d))
188 #else
189 #define xmpz_cmp_d(z, d) mpz_cmp_d (z, d)
190 #endif
191
192
193 #if defined (GUILE_I)
194 #if defined HAVE_COMPLEX_DOUBLE
195
196 /* For an SCM object Z which is a complex number (ie. satisfies
197 SCM_COMPLEXP), return its value as a C level "complex double". */
198 #define SCM_COMPLEX_VALUE(z) \
199 (SCM_COMPLEX_REAL (z) + GUILE_I * SCM_COMPLEX_IMAG (z))
200
201 static inline SCM scm_from_complex_double (complex double z) SCM_UNUSED;
202
203 /* Convert a C "complex double" to an SCM value. */
204 static inline SCM
205 scm_from_complex_double (complex double z)
206 {
207 return scm_c_make_rectangular (creal (z), cimag (z));
208 }
209
210 #endif /* HAVE_COMPLEX_DOUBLE */
211 #endif /* GUILE_I */
212
213 \f
214
215 static mpz_t z_negative_one;
216
217 \f
218
219 /* Clear the `mpz_t' embedded in bignum PTR. */
220 static void
221 finalize_bignum (void *ptr, void *data)
222 {
223 SCM bignum;
224
225 bignum = PTR2SCM (ptr);
226 mpz_clear (SCM_I_BIG_MPZ (bignum));
227 }
228
229 /* The next three functions (custom_libgmp_*) are passed to
230 mp_set_memory_functions (in GMP) so that memory used by the digits
231 themselves is known to the garbage collector. This is needed so
232 that GC will be run at appropriate times. Otherwise, a program which
233 creates many large bignums would malloc a huge amount of memory
234 before the GC runs. */
235 static void *
236 custom_gmp_malloc (size_t alloc_size)
237 {
238 return scm_malloc (alloc_size);
239 }
240
241 static void *
242 custom_gmp_realloc (void *old_ptr, size_t old_size, size_t new_size)
243 {
244 return scm_realloc (old_ptr, new_size);
245 }
246
247 static void
248 custom_gmp_free (void *ptr, size_t size)
249 {
250 free (ptr);
251 }
252
253
254 /* Return a new uninitialized bignum. */
255 static inline SCM
256 make_bignum (void)
257 {
258 scm_t_bits *p;
259
260 /* Allocate one word for the type tag and enough room for an `mpz_t'. */
261 p = scm_gc_malloc_pointerless (sizeof (scm_t_bits) + sizeof (mpz_t),
262 "bignum");
263 p[0] = scm_tc16_big;
264
265 scm_i_set_finalizer (p, finalize_bignum, NULL);
266
267 return SCM_PACK (p);
268 }
269
270
271 SCM
272 scm_i_mkbig ()
273 {
274 /* Return a newly created bignum. */
275 SCM z = make_bignum ();
276 mpz_init (SCM_I_BIG_MPZ (z));
277 return z;
278 }
279
280 static SCM
281 scm_i_inum2big (scm_t_inum x)
282 {
283 /* Return a newly created bignum initialized to X. */
284 SCM z = make_bignum ();
285 #if SIZEOF_VOID_P == SIZEOF_LONG
286 mpz_init_set_si (SCM_I_BIG_MPZ (z), x);
287 #else
288 /* Note that in this case, you'll also have to check all mpz_*_ui and
289 mpz_*_si invocations in Guile. */
290 #error creation of mpz not implemented for this inum size
291 #endif
292 return z;
293 }
294
295 SCM
296 scm_i_long2big (long x)
297 {
298 /* Return a newly created bignum initialized to X. */
299 SCM z = make_bignum ();
300 mpz_init_set_si (SCM_I_BIG_MPZ (z), x);
301 return z;
302 }
303
304 SCM
305 scm_i_ulong2big (unsigned long x)
306 {
307 /* Return a newly created bignum initialized to X. */
308 SCM z = make_bignum ();
309 mpz_init_set_ui (SCM_I_BIG_MPZ (z), x);
310 return z;
311 }
312
313 SCM
314 scm_i_clonebig (SCM src_big, int same_sign_p)
315 {
316 /* Copy src_big's value, negate it if same_sign_p is false, and return. */
317 SCM z = make_bignum ();
318 mpz_init_set (SCM_I_BIG_MPZ (z), SCM_I_BIG_MPZ (src_big));
319 if (!same_sign_p)
320 mpz_neg (SCM_I_BIG_MPZ (z), SCM_I_BIG_MPZ (z));
321 return z;
322 }
323
324 int
325 scm_i_bigcmp (SCM x, SCM y)
326 {
327 /* Return neg if x < y, pos if x > y, and 0 if x == y */
328 /* presume we already know x and y are bignums */
329 int result = mpz_cmp (SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
330 scm_remember_upto_here_2 (x, y);
331 return result;
332 }
333
334 SCM
335 scm_i_dbl2big (double d)
336 {
337 /* results are only defined if d is an integer */
338 SCM z = make_bignum ();
339 mpz_init_set_d (SCM_I_BIG_MPZ (z), d);
340 return z;
341 }
342
343 /* Convert a integer in double representation to a SCM number. */
344
345 SCM
346 scm_i_dbl2num (double u)
347 {
348 /* SCM_MOST_POSITIVE_FIXNUM+1 and SCM_MOST_NEGATIVE_FIXNUM are both
349 powers of 2, so there's no rounding when making "double" values
350 from them. If plain SCM_MOST_POSITIVE_FIXNUM was used it could
351 get rounded on a 64-bit machine, hence the "+1".
352
353 The use of floor() to force to an integer value ensures we get a
354 "numerically closest" value without depending on how a
355 double->long cast or how mpz_set_d will round. For reference,
356 double->long probably follows the hardware rounding mode,
357 mpz_set_d truncates towards zero. */
358
359 /* XXX - what happens when SCM_MOST_POSITIVE_FIXNUM etc is not
360 representable as a double? */
361
362 if (u < (double) (SCM_MOST_POSITIVE_FIXNUM+1)
363 && u >= (double) SCM_MOST_NEGATIVE_FIXNUM)
364 return SCM_I_MAKINUM ((scm_t_inum) u);
365 else
366 return scm_i_dbl2big (u);
367 }
368
369 static SCM round_right_shift_exact_integer (SCM n, long count);
370
371 /* scm_i_big2dbl_2exp() is like frexp for bignums: it converts the
372 bignum b into a normalized significand and exponent such that
373 b = significand * 2^exponent and 1/2 <= abs(significand) < 1.
374 The return value is the significand rounded to the closest
375 representable double, and the exponent is placed into *expon_p.
376 If b is zero, then the returned exponent and significand are both
377 zero. */
378
379 static double
380 scm_i_big2dbl_2exp (SCM b, long *expon_p)
381 {
382 size_t bits = mpz_sizeinbase (SCM_I_BIG_MPZ (b), 2);
383 size_t shift = 0;
384
385 if (bits > DBL_MANT_DIG)
386 {
387 shift = bits - DBL_MANT_DIG;
388 b = round_right_shift_exact_integer (b, shift);
389 if (SCM_I_INUMP (b))
390 {
391 int expon;
392 double signif = frexp (SCM_I_INUM (b), &expon);
393 *expon_p = expon + shift;
394 return signif;
395 }
396 }
397
398 {
399 long expon;
400 double signif = mpz_get_d_2exp (&expon, SCM_I_BIG_MPZ (b));
401 scm_remember_upto_here_1 (b);
402 *expon_p = expon + shift;
403 return signif;
404 }
405 }
406
407 /* scm_i_big2dbl() rounds to the closest representable double,
408 in accordance with R5RS exact->inexact. */
409 double
410 scm_i_big2dbl (SCM b)
411 {
412 long expon;
413 double signif = scm_i_big2dbl_2exp (b, &expon);
414 return ldexp (signif, expon);
415 }
416
417 SCM
418 scm_i_normbig (SCM b)
419 {
420 /* convert a big back to a fixnum if it'll fit */
421 /* presume b is a bignum */
422 if (mpz_fits_slong_p (SCM_I_BIG_MPZ (b)))
423 {
424 scm_t_inum val = mpz_get_si (SCM_I_BIG_MPZ (b));
425 if (SCM_FIXABLE (val))
426 b = SCM_I_MAKINUM (val);
427 }
428 return b;
429 }
430
431 static SCM_C_INLINE_KEYWORD SCM
432 scm_i_mpz2num (mpz_t b)
433 {
434 /* convert a mpz number to a SCM number. */
435 if (mpz_fits_slong_p (b))
436 {
437 scm_t_inum val = mpz_get_si (b);
438 if (SCM_FIXABLE (val))
439 return SCM_I_MAKINUM (val);
440 }
441
442 {
443 SCM z = make_bignum ();
444 mpz_init_set (SCM_I_BIG_MPZ (z), b);
445 return z;
446 }
447 }
448
449 /* Make the ratio NUMERATOR/DENOMINATOR, where:
450 1. NUMERATOR and DENOMINATOR are exact integers
451 2. NUMERATOR and DENOMINATOR are reduced to lowest terms: gcd(n,d) == 1 */
452 static SCM
453 scm_i_make_ratio_already_reduced (SCM numerator, SCM denominator)
454 {
455 /* Flip signs so that the denominator is positive. */
456 if (scm_is_false (scm_positive_p (denominator)))
457 {
458 if (SCM_UNLIKELY (scm_is_eq (denominator, SCM_INUM0)))
459 scm_num_overflow ("make-ratio");
460 else
461 {
462 numerator = scm_difference (numerator, SCM_UNDEFINED);
463 denominator = scm_difference (denominator, SCM_UNDEFINED);
464 }
465 }
466
467 /* Check for the integer case */
468 if (scm_is_eq (denominator, SCM_INUM1))
469 return numerator;
470
471 return scm_double_cell (scm_tc16_fraction,
472 SCM_UNPACK (numerator),
473 SCM_UNPACK (denominator), 0);
474 }
475
476 static SCM scm_exact_integer_quotient (SCM x, SCM y);
477
478 /* Make the ratio NUMERATOR/DENOMINATOR */
479 static SCM
480 scm_i_make_ratio (SCM numerator, SCM denominator)
481 #define FUNC_NAME "make-ratio"
482 {
483 /* Make sure the arguments are proper */
484 if (!SCM_LIKELY (SCM_I_INUMP (numerator) || SCM_BIGP (numerator)))
485 SCM_WRONG_TYPE_ARG (1, numerator);
486 else if (!SCM_LIKELY (SCM_I_INUMP (denominator) || SCM_BIGP (denominator)))
487 SCM_WRONG_TYPE_ARG (2, denominator);
488 else
489 {
490 SCM the_gcd = scm_gcd (numerator, denominator);
491 if (!(scm_is_eq (the_gcd, SCM_INUM1)))
492 {
493 /* Reduce to lowest terms */
494 numerator = scm_exact_integer_quotient (numerator, the_gcd);
495 denominator = scm_exact_integer_quotient (denominator, the_gcd);
496 }
497 return scm_i_make_ratio_already_reduced (numerator, denominator);
498 }
499 }
500 #undef FUNC_NAME
501
502 static mpz_t scm_i_divide2double_lo2b;
503
504 /* Return the double that is closest to the exact rational N/D, with
505 ties rounded toward even mantissas. N and D must be exact
506 integers. */
507 static double
508 scm_i_divide2double (SCM n, SCM d)
509 {
510 int neg;
511 mpz_t nn, dd, lo, hi, x;
512 ssize_t e;
513
514 if (SCM_LIKELY (SCM_I_INUMP (d)))
515 {
516 if (SCM_LIKELY
517 (SCM_I_INUMP (n)
518 && INUM_LOSSLESSLY_CONVERTIBLE_TO_DOUBLE (SCM_I_INUM (n))
519 && INUM_LOSSLESSLY_CONVERTIBLE_TO_DOUBLE (SCM_I_INUM (d))))
520 /* If both N and D can be losslessly converted to doubles, then
521 we can rely on IEEE floating point to do proper rounding much
522 faster than we can. */
523 return ((double) SCM_I_INUM (n)) / ((double) SCM_I_INUM (d));
524
525 if (SCM_UNLIKELY (scm_is_eq (d, SCM_INUM0)))
526 {
527 if (scm_is_true (scm_positive_p (n)))
528 return 1.0 / 0.0;
529 else if (scm_is_true (scm_negative_p (n)))
530 return -1.0 / 0.0;
531 else
532 return 0.0 / 0.0;
533 }
534
535 mpz_init_set_si (dd, SCM_I_INUM (d));
536 }
537 else
538 mpz_init_set (dd, SCM_I_BIG_MPZ (d));
539
540 if (SCM_I_INUMP (n))
541 mpz_init_set_si (nn, SCM_I_INUM (n));
542 else
543 mpz_init_set (nn, SCM_I_BIG_MPZ (n));
544
545 neg = (mpz_sgn (nn) < 0) ^ (mpz_sgn (dd) < 0);
546 mpz_abs (nn, nn);
547 mpz_abs (dd, dd);
548
549 /* Now we need to find the value of e such that:
550
551 For e <= 0:
552 b^{p-1} - 1/2b <= b^-e n / d < b^p - 1/2 [1A]
553 (2 b^p - 1) <= 2 b b^-e n / d < (2 b^p - 1) b [2A]
554 (2 b^p - 1) d <= 2 b b^-e n < (2 b^p - 1) d b [3A]
555
556 For e >= 0:
557 b^{p-1} - 1/2b <= n / b^e d < b^p - 1/2 [1B]
558 (2 b^p - 1) <= 2 b n / b^e d < (2 b^p - 1) b [2B]
559 (2 b^p - 1) d b^e <= 2 b n < (2 b^p - 1) d b b^e [3B]
560
561 where: p = DBL_MANT_DIG
562 b = FLT_RADIX (here assumed to be 2)
563
564 After rounding, the mantissa must be an integer between b^{p-1} and
565 (b^p - 1), except for subnormal numbers. In the inequations [1A]
566 and [1B], the middle expression represents the mantissa *before*
567 rounding, and therefore is bounded by the range of values that will
568 round to a floating-point number with the exponent e. The upper
569 bound is (b^p - 1 + 1/2) = (b^p - 1/2), and is exclusive because
570 ties will round up to the next power of b. The lower bound is
571 (b^{p-1} - 1/2b), and is inclusive because ties will round toward
572 this power of b. Here we subtract 1/2b instead of 1/2 because it
573 is in the range of the next smaller exponent, where the
574 representable numbers are closer together by a factor of b.
575
576 Inequations [2A] and [2B] are derived from [1A] and [1B] by
577 multiplying by 2b, and in [3A] and [3B] we multiply by the
578 denominator of the middle value to obtain integer expressions.
579
580 In the code below, we refer to the three expressions in [3A] or
581 [3B] as lo, x, and hi. If the number is normalizable, we will
582 achieve the goal: lo <= x < hi */
583
584 /* Make an initial guess for e */
585 e = mpz_sizeinbase (nn, 2) - mpz_sizeinbase (dd, 2) - (DBL_MANT_DIG-1);
586 if (e < DBL_MIN_EXP - DBL_MANT_DIG)
587 e = DBL_MIN_EXP - DBL_MANT_DIG;
588
589 /* Compute the initial values of lo, x, and hi
590 based on the initial guess of e */
591 mpz_inits (lo, hi, x, NULL);
592 mpz_mul_2exp (x, nn, 2 + ((e < 0) ? -e : 0));
593 mpz_mul (lo, dd, scm_i_divide2double_lo2b);
594 if (e > 0)
595 mpz_mul_2exp (lo, lo, e);
596 mpz_mul_2exp (hi, lo, 1);
597
598 /* Adjust e as needed to satisfy the inequality lo <= x < hi,
599 (but without making e less then the minimum exponent) */
600 while (mpz_cmp (x, lo) < 0 && e > DBL_MIN_EXP - DBL_MANT_DIG)
601 {
602 mpz_mul_2exp (x, x, 1);
603 e--;
604 }
605 while (mpz_cmp (x, hi) >= 0)
606 {
607 /* If we ever used lo's value again,
608 we would need to double lo here. */
609 mpz_mul_2exp (hi, hi, 1);
610 e++;
611 }
612
613 /* Now compute the rounded mantissa:
614 n / b^e d (if e >= 0)
615 n b^-e / d (if e <= 0) */
616 {
617 int cmp;
618 double result;
619
620 if (e < 0)
621 mpz_mul_2exp (nn, nn, -e);
622 else
623 mpz_mul_2exp (dd, dd, e);
624
625 /* mpz does not directly support rounded right
626 shifts, so we have to do it the hard way.
627 For efficiency, we reuse lo and hi.
628 hi == quotient, lo == remainder */
629 mpz_fdiv_qr (hi, lo, nn, dd);
630
631 /* The fractional part of the unrounded mantissa would be
632 remainder/dividend, i.e. lo/dd. So we have a tie if
633 lo/dd = 1/2. Multiplying both sides by 2*dd yields the
634 integer expression 2*lo = dd. Here we do that comparison
635 to decide whether to round up or down. */
636 mpz_mul_2exp (lo, lo, 1);
637 cmp = mpz_cmp (lo, dd);
638 if (cmp > 0 || (cmp == 0 && mpz_odd_p (hi)))
639 mpz_add_ui (hi, hi, 1);
640
641 result = ldexp (mpz_get_d (hi), e);
642 if (neg)
643 result = -result;
644
645 mpz_clears (nn, dd, lo, hi, x, NULL);
646 return result;
647 }
648 }
649
650 double
651 scm_i_fraction2double (SCM z)
652 {
653 return scm_i_divide2double (SCM_FRACTION_NUMERATOR (z),
654 SCM_FRACTION_DENOMINATOR (z));
655 }
656
657 static int
658 double_is_non_negative_zero (double x)
659 {
660 static double zero = 0.0;
661
662 return !memcmp (&x, &zero, sizeof(double));
663 }
664
665 SCM_PRIMITIVE_GENERIC (scm_exact_p, "exact?", 1, 0, 0,
666 (SCM x),
667 "Return @code{#t} if @var{x} is an exact number, @code{#f}\n"
668 "otherwise.")
669 #define FUNC_NAME s_scm_exact_p
670 {
671 if (SCM_INEXACTP (x))
672 return SCM_BOOL_F;
673 else if (SCM_NUMBERP (x))
674 return SCM_BOOL_T;
675 else
676 SCM_WTA_DISPATCH_1 (g_scm_exact_p, x, 1, s_scm_exact_p);
677 }
678 #undef FUNC_NAME
679
680 int
681 scm_is_exact (SCM val)
682 {
683 return scm_is_true (scm_exact_p (val));
684 }
685
686 SCM_PRIMITIVE_GENERIC (scm_inexact_p, "inexact?", 1, 0, 0,
687 (SCM x),
688 "Return @code{#t} if @var{x} is an inexact number, @code{#f}\n"
689 "else.")
690 #define FUNC_NAME s_scm_inexact_p
691 {
692 if (SCM_INEXACTP (x))
693 return SCM_BOOL_T;
694 else if (SCM_NUMBERP (x))
695 return SCM_BOOL_F;
696 else
697 SCM_WTA_DISPATCH_1 (g_scm_inexact_p, x, 1, s_scm_inexact_p);
698 }
699 #undef FUNC_NAME
700
701 int
702 scm_is_inexact (SCM val)
703 {
704 return scm_is_true (scm_inexact_p (val));
705 }
706
707 SCM_PRIMITIVE_GENERIC (scm_odd_p, "odd?", 1, 0, 0,
708 (SCM n),
709 "Return @code{#t} if @var{n} is an odd number, @code{#f}\n"
710 "otherwise.")
711 #define FUNC_NAME s_scm_odd_p
712 {
713 if (SCM_I_INUMP (n))
714 {
715 scm_t_inum val = SCM_I_INUM (n);
716 return scm_from_bool ((val & 1L) != 0);
717 }
718 else if (SCM_BIGP (n))
719 {
720 int odd_p = mpz_odd_p (SCM_I_BIG_MPZ (n));
721 scm_remember_upto_here_1 (n);
722 return scm_from_bool (odd_p);
723 }
724 else if (SCM_REALP (n))
725 {
726 double val = SCM_REAL_VALUE (n);
727 if (DOUBLE_IS_FINITE (val))
728 {
729 double rem = fabs (fmod (val, 2.0));
730 if (rem == 1.0)
731 return SCM_BOOL_T;
732 else if (rem == 0.0)
733 return SCM_BOOL_F;
734 }
735 }
736 SCM_WTA_DISPATCH_1 (g_scm_odd_p, n, 1, s_scm_odd_p);
737 }
738 #undef FUNC_NAME
739
740
741 SCM_PRIMITIVE_GENERIC (scm_even_p, "even?", 1, 0, 0,
742 (SCM n),
743 "Return @code{#t} if @var{n} is an even number, @code{#f}\n"
744 "otherwise.")
745 #define FUNC_NAME s_scm_even_p
746 {
747 if (SCM_I_INUMP (n))
748 {
749 scm_t_inum val = SCM_I_INUM (n);
750 return scm_from_bool ((val & 1L) == 0);
751 }
752 else if (SCM_BIGP (n))
753 {
754 int even_p = mpz_even_p (SCM_I_BIG_MPZ (n));
755 scm_remember_upto_here_1 (n);
756 return scm_from_bool (even_p);
757 }
758 else if (SCM_REALP (n))
759 {
760 double val = SCM_REAL_VALUE (n);
761 if (DOUBLE_IS_FINITE (val))
762 {
763 double rem = fabs (fmod (val, 2.0));
764 if (rem == 1.0)
765 return SCM_BOOL_F;
766 else if (rem == 0.0)
767 return SCM_BOOL_T;
768 }
769 }
770 SCM_WTA_DISPATCH_1 (g_scm_even_p, n, 1, s_scm_even_p);
771 }
772 #undef FUNC_NAME
773
774 SCM_PRIMITIVE_GENERIC (scm_finite_p, "finite?", 1, 0, 0,
775 (SCM x),
776 "Return @code{#t} if the real number @var{x} is neither\n"
777 "infinite nor a NaN, @code{#f} otherwise.")
778 #define FUNC_NAME s_scm_finite_p
779 {
780 if (SCM_REALP (x))
781 return scm_from_bool (DOUBLE_IS_FINITE (SCM_REAL_VALUE (x)));
782 else if (scm_is_real (x))
783 return SCM_BOOL_T;
784 else
785 SCM_WTA_DISPATCH_1 (g_scm_finite_p, x, 1, s_scm_finite_p);
786 }
787 #undef FUNC_NAME
788
789 SCM_PRIMITIVE_GENERIC (scm_inf_p, "inf?", 1, 0, 0,
790 (SCM x),
791 "Return @code{#t} if the real number @var{x} is @samp{+inf.0} or\n"
792 "@samp{-inf.0}. Otherwise return @code{#f}.")
793 #define FUNC_NAME s_scm_inf_p
794 {
795 if (SCM_REALP (x))
796 return scm_from_bool (isinf (SCM_REAL_VALUE (x)));
797 else if (scm_is_real (x))
798 return SCM_BOOL_F;
799 else
800 SCM_WTA_DISPATCH_1 (g_scm_inf_p, x, 1, s_scm_inf_p);
801 }
802 #undef FUNC_NAME
803
804 SCM_PRIMITIVE_GENERIC (scm_nan_p, "nan?", 1, 0, 0,
805 (SCM x),
806 "Return @code{#t} if the real number @var{x} is a NaN,\n"
807 "or @code{#f} otherwise.")
808 #define FUNC_NAME s_scm_nan_p
809 {
810 if (SCM_REALP (x))
811 return scm_from_bool (isnan (SCM_REAL_VALUE (x)));
812 else if (scm_is_real (x))
813 return SCM_BOOL_F;
814 else
815 SCM_WTA_DISPATCH_1 (g_scm_nan_p, x, 1, s_scm_nan_p);
816 }
817 #undef FUNC_NAME
818
819 /* Guile's idea of infinity. */
820 static double guile_Inf;
821
822 /* Guile's idea of not a number. */
823 static double guile_NaN;
824
825 static void
826 guile_ieee_init (void)
827 {
828 /* Some version of gcc on some old version of Linux used to crash when
829 trying to make Inf and NaN. */
830
831 #ifdef INFINITY
832 /* C99 INFINITY, when available.
833 FIXME: The standard allows for INFINITY to be something that overflows
834 at compile time. We ought to have a configure test to check for that
835 before trying to use it. (But in practice we believe this is not a
836 problem on any system guile is likely to target.) */
837 guile_Inf = INFINITY;
838 #elif defined HAVE_DINFINITY
839 /* OSF */
840 extern unsigned int DINFINITY[2];
841 guile_Inf = (*((double *) (DINFINITY)));
842 #else
843 double tmp = 1e+10;
844 guile_Inf = tmp;
845 for (;;)
846 {
847 guile_Inf *= 1e+10;
848 if (guile_Inf == tmp)
849 break;
850 tmp = guile_Inf;
851 }
852 #endif
853
854 #ifdef NAN
855 /* C99 NAN, when available */
856 guile_NaN = NAN;
857 #elif defined HAVE_DQNAN
858 {
859 /* OSF */
860 extern unsigned int DQNAN[2];
861 guile_NaN = (*((double *)(DQNAN)));
862 }
863 #else
864 guile_NaN = guile_Inf / guile_Inf;
865 #endif
866 }
867
868 SCM_DEFINE (scm_inf, "inf", 0, 0, 0,
869 (void),
870 "Return Inf.")
871 #define FUNC_NAME s_scm_inf
872 {
873 static int initialized = 0;
874 if (! initialized)
875 {
876 guile_ieee_init ();
877 initialized = 1;
878 }
879 return scm_from_double (guile_Inf);
880 }
881 #undef FUNC_NAME
882
883 SCM_DEFINE (scm_nan, "nan", 0, 0, 0,
884 (void),
885 "Return NaN.")
886 #define FUNC_NAME s_scm_nan
887 {
888 static int initialized = 0;
889 if (!initialized)
890 {
891 guile_ieee_init ();
892 initialized = 1;
893 }
894 return scm_from_double (guile_NaN);
895 }
896 #undef FUNC_NAME
897
898
899 SCM_PRIMITIVE_GENERIC (scm_abs, "abs", 1, 0, 0,
900 (SCM x),
901 "Return the absolute value of @var{x}.")
902 #define FUNC_NAME s_scm_abs
903 {
904 if (SCM_I_INUMP (x))
905 {
906 scm_t_inum xx = SCM_I_INUM (x);
907 if (xx >= 0)
908 return x;
909 else if (SCM_POSFIXABLE (-xx))
910 return SCM_I_MAKINUM (-xx);
911 else
912 return scm_i_inum2big (-xx);
913 }
914 else if (SCM_LIKELY (SCM_REALP (x)))
915 {
916 double xx = SCM_REAL_VALUE (x);
917 /* If x is a NaN then xx<0 is false so we return x unchanged */
918 if (xx < 0.0)
919 return scm_from_double (-xx);
920 /* Handle signed zeroes properly */
921 else if (SCM_UNLIKELY (xx == 0.0))
922 return flo0;
923 else
924 return x;
925 }
926 else if (SCM_BIGP (x))
927 {
928 const int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
929 if (sgn < 0)
930 return scm_i_clonebig (x, 0);
931 else
932 return x;
933 }
934 else if (SCM_FRACTIONP (x))
935 {
936 if (scm_is_false (scm_negative_p (SCM_FRACTION_NUMERATOR (x))))
937 return x;
938 return scm_i_make_ratio_already_reduced
939 (scm_difference (SCM_FRACTION_NUMERATOR (x), SCM_UNDEFINED),
940 SCM_FRACTION_DENOMINATOR (x));
941 }
942 else
943 SCM_WTA_DISPATCH_1 (g_scm_abs, x, 1, s_scm_abs);
944 }
945 #undef FUNC_NAME
946
947
948 SCM_PRIMITIVE_GENERIC (scm_quotient, "quotient", 2, 0, 0,
949 (SCM x, SCM y),
950 "Return the quotient of the numbers @var{x} and @var{y}.")
951 #define FUNC_NAME s_scm_quotient
952 {
953 if (SCM_LIKELY (scm_is_integer (x)))
954 {
955 if (SCM_LIKELY (scm_is_integer (y)))
956 return scm_truncate_quotient (x, y);
957 else
958 SCM_WTA_DISPATCH_2 (g_scm_quotient, x, y, SCM_ARG2, s_scm_quotient);
959 }
960 else
961 SCM_WTA_DISPATCH_2 (g_scm_quotient, x, y, SCM_ARG1, s_scm_quotient);
962 }
963 #undef FUNC_NAME
964
965 SCM_PRIMITIVE_GENERIC (scm_remainder, "remainder", 2, 0, 0,
966 (SCM x, SCM y),
967 "Return the remainder of the numbers @var{x} and @var{y}.\n"
968 "@lisp\n"
969 "(remainder 13 4) @result{} 1\n"
970 "(remainder -13 4) @result{} -1\n"
971 "@end lisp")
972 #define FUNC_NAME s_scm_remainder
973 {
974 if (SCM_LIKELY (scm_is_integer (x)))
975 {
976 if (SCM_LIKELY (scm_is_integer (y)))
977 return scm_truncate_remainder (x, y);
978 else
979 SCM_WTA_DISPATCH_2 (g_scm_remainder, x, y, SCM_ARG2, s_scm_remainder);
980 }
981 else
982 SCM_WTA_DISPATCH_2 (g_scm_remainder, x, y, SCM_ARG1, s_scm_remainder);
983 }
984 #undef FUNC_NAME
985
986
987 SCM_PRIMITIVE_GENERIC (scm_modulo, "modulo", 2, 0, 0,
988 (SCM x, SCM y),
989 "Return the modulo of the numbers @var{x} and @var{y}.\n"
990 "@lisp\n"
991 "(modulo 13 4) @result{} 1\n"
992 "(modulo -13 4) @result{} 3\n"
993 "@end lisp")
994 #define FUNC_NAME s_scm_modulo
995 {
996 if (SCM_LIKELY (scm_is_integer (x)))
997 {
998 if (SCM_LIKELY (scm_is_integer (y)))
999 return scm_floor_remainder (x, y);
1000 else
1001 SCM_WTA_DISPATCH_2 (g_scm_modulo, x, y, SCM_ARG2, s_scm_modulo);
1002 }
1003 else
1004 SCM_WTA_DISPATCH_2 (g_scm_modulo, x, y, SCM_ARG1, s_scm_modulo);
1005 }
1006 #undef FUNC_NAME
1007
1008 /* Return the exact integer q such that n = q*d, for exact integers n
1009 and d, where d is known in advance to divide n evenly (with zero
1010 remainder). For large integers, this can be computed more
1011 efficiently than when the remainder is unknown. */
1012 static SCM
1013 scm_exact_integer_quotient (SCM n, SCM d)
1014 #define FUNC_NAME "exact-integer-quotient"
1015 {
1016 if (SCM_LIKELY (SCM_I_INUMP (n)))
1017 {
1018 scm_t_inum nn = SCM_I_INUM (n);
1019 if (SCM_LIKELY (SCM_I_INUMP (d)))
1020 {
1021 scm_t_inum dd = SCM_I_INUM (d);
1022 if (SCM_UNLIKELY (dd == 0))
1023 scm_num_overflow ("exact-integer-quotient");
1024 else
1025 {
1026 scm_t_inum qq = nn / dd;
1027 if (SCM_LIKELY (SCM_FIXABLE (qq)))
1028 return SCM_I_MAKINUM (qq);
1029 else
1030 return scm_i_inum2big (qq);
1031 }
1032 }
1033 else if (SCM_LIKELY (SCM_BIGP (d)))
1034 {
1035 /* n is an inum and d is a bignum. Given that d is known to
1036 divide n evenly, there are only two possibilities: n is 0,
1037 or else n is fixnum-min and d is abs(fixnum-min). */
1038 if (nn == 0)
1039 return SCM_INUM0;
1040 else
1041 return SCM_I_MAKINUM (-1);
1042 }
1043 else
1044 SCM_WRONG_TYPE_ARG (2, d);
1045 }
1046 else if (SCM_LIKELY (SCM_BIGP (n)))
1047 {
1048 if (SCM_LIKELY (SCM_I_INUMP (d)))
1049 {
1050 scm_t_inum dd = SCM_I_INUM (d);
1051 if (SCM_UNLIKELY (dd == 0))
1052 scm_num_overflow ("exact-integer-quotient");
1053 else if (SCM_UNLIKELY (dd == 1))
1054 return n;
1055 else
1056 {
1057 SCM q = scm_i_mkbig ();
1058 if (dd > 0)
1059 mpz_divexact_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (n), dd);
1060 else
1061 {
1062 mpz_divexact_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (n), -dd);
1063 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
1064 }
1065 scm_remember_upto_here_1 (n);
1066 return scm_i_normbig (q);
1067 }
1068 }
1069 else if (SCM_LIKELY (SCM_BIGP (d)))
1070 {
1071 SCM q = scm_i_mkbig ();
1072 mpz_divexact (SCM_I_BIG_MPZ (q),
1073 SCM_I_BIG_MPZ (n),
1074 SCM_I_BIG_MPZ (d));
1075 scm_remember_upto_here_2 (n, d);
1076 return scm_i_normbig (q);
1077 }
1078 else
1079 SCM_WRONG_TYPE_ARG (2, d);
1080 }
1081 else
1082 SCM_WRONG_TYPE_ARG (1, n);
1083 }
1084 #undef FUNC_NAME
1085
1086 /* two_valued_wta_dispatch_2 is a version of SCM_WTA_DISPATCH_2 for
1087 two-valued functions. It is called from primitive generics that take
1088 two arguments and return two values, when the core procedure is
1089 unable to handle the given argument types. If there are GOOPS
1090 methods for this primitive generic, it dispatches to GOOPS and, if
1091 successful, expects two values to be returned, which are placed in
1092 *rp1 and *rp2. If there are no GOOPS methods, it throws a
1093 wrong-type-arg exception.
1094
1095 FIXME: This obviously belongs somewhere else, but until we decide on
1096 the right API, it is here as a static function, because it is needed
1097 by the *_divide functions below.
1098 */
1099 static void
1100 two_valued_wta_dispatch_2 (SCM gf, SCM a1, SCM a2, int pos,
1101 const char *subr, SCM *rp1, SCM *rp2)
1102 {
1103 if (SCM_UNPACK (gf))
1104 scm_i_extract_values_2 (scm_call_generic_2 (gf, a1, a2), rp1, rp2);
1105 else
1106 scm_wrong_type_arg (subr, pos, (pos == SCM_ARG1) ? a1 : a2);
1107 }
1108
1109 SCM_DEFINE (scm_euclidean_quotient, "euclidean-quotient", 2, 0, 0,
1110 (SCM x, SCM y),
1111 "Return the integer @var{q} such that\n"
1112 "@math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1113 "where @math{0 <= @var{r} < abs(@var{y})}.\n"
1114 "@lisp\n"
1115 "(euclidean-quotient 123 10) @result{} 12\n"
1116 "(euclidean-quotient 123 -10) @result{} -12\n"
1117 "(euclidean-quotient -123 10) @result{} -13\n"
1118 "(euclidean-quotient -123 -10) @result{} 13\n"
1119 "(euclidean-quotient -123.2 -63.5) @result{} 2.0\n"
1120 "(euclidean-quotient 16/3 -10/7) @result{} -3\n"
1121 "@end lisp")
1122 #define FUNC_NAME s_scm_euclidean_quotient
1123 {
1124 if (scm_is_false (scm_negative_p (y)))
1125 return scm_floor_quotient (x, y);
1126 else
1127 return scm_ceiling_quotient (x, y);
1128 }
1129 #undef FUNC_NAME
1130
1131 SCM_DEFINE (scm_euclidean_remainder, "euclidean-remainder", 2, 0, 0,
1132 (SCM x, SCM y),
1133 "Return the real number @var{r} such that\n"
1134 "@math{0 <= @var{r} < abs(@var{y})} and\n"
1135 "@math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1136 "for some integer @var{q}.\n"
1137 "@lisp\n"
1138 "(euclidean-remainder 123 10) @result{} 3\n"
1139 "(euclidean-remainder 123 -10) @result{} 3\n"
1140 "(euclidean-remainder -123 10) @result{} 7\n"
1141 "(euclidean-remainder -123 -10) @result{} 7\n"
1142 "(euclidean-remainder -123.2 -63.5) @result{} 3.8\n"
1143 "(euclidean-remainder 16/3 -10/7) @result{} 22/21\n"
1144 "@end lisp")
1145 #define FUNC_NAME s_scm_euclidean_remainder
1146 {
1147 if (scm_is_false (scm_negative_p (y)))
1148 return scm_floor_remainder (x, y);
1149 else
1150 return scm_ceiling_remainder (x, y);
1151 }
1152 #undef FUNC_NAME
1153
1154 SCM_DEFINE (scm_i_euclidean_divide, "euclidean/", 2, 0, 0,
1155 (SCM x, SCM y),
1156 "Return the integer @var{q} and the real number @var{r}\n"
1157 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1158 "and @math{0 <= @var{r} < abs(@var{y})}.\n"
1159 "@lisp\n"
1160 "(euclidean/ 123 10) @result{} 12 and 3\n"
1161 "(euclidean/ 123 -10) @result{} -12 and 3\n"
1162 "(euclidean/ -123 10) @result{} -13 and 7\n"
1163 "(euclidean/ -123 -10) @result{} 13 and 7\n"
1164 "(euclidean/ -123.2 -63.5) @result{} 2.0 and 3.8\n"
1165 "(euclidean/ 16/3 -10/7) @result{} -3 and 22/21\n"
1166 "@end lisp")
1167 #define FUNC_NAME s_scm_i_euclidean_divide
1168 {
1169 if (scm_is_false (scm_negative_p (y)))
1170 return scm_i_floor_divide (x, y);
1171 else
1172 return scm_i_ceiling_divide (x, y);
1173 }
1174 #undef FUNC_NAME
1175
1176 void
1177 scm_euclidean_divide (SCM x, SCM y, SCM *qp, SCM *rp)
1178 {
1179 if (scm_is_false (scm_negative_p (y)))
1180 return scm_floor_divide (x, y, qp, rp);
1181 else
1182 return scm_ceiling_divide (x, y, qp, rp);
1183 }
1184
1185 static SCM scm_i_inexact_floor_quotient (double x, double y);
1186 static SCM scm_i_exact_rational_floor_quotient (SCM x, SCM y);
1187
1188 SCM_PRIMITIVE_GENERIC (scm_floor_quotient, "floor-quotient", 2, 0, 0,
1189 (SCM x, SCM y),
1190 "Return the floor of @math{@var{x} / @var{y}}.\n"
1191 "@lisp\n"
1192 "(floor-quotient 123 10) @result{} 12\n"
1193 "(floor-quotient 123 -10) @result{} -13\n"
1194 "(floor-quotient -123 10) @result{} -13\n"
1195 "(floor-quotient -123 -10) @result{} 12\n"
1196 "(floor-quotient -123.2 -63.5) @result{} 1.0\n"
1197 "(floor-quotient 16/3 -10/7) @result{} -4\n"
1198 "@end lisp")
1199 #define FUNC_NAME s_scm_floor_quotient
1200 {
1201 if (SCM_LIKELY (SCM_I_INUMP (x)))
1202 {
1203 scm_t_inum xx = SCM_I_INUM (x);
1204 if (SCM_LIKELY (SCM_I_INUMP (y)))
1205 {
1206 scm_t_inum yy = SCM_I_INUM (y);
1207 scm_t_inum xx1 = xx;
1208 scm_t_inum qq;
1209 if (SCM_LIKELY (yy > 0))
1210 {
1211 if (SCM_UNLIKELY (xx < 0))
1212 xx1 = xx - yy + 1;
1213 }
1214 else if (SCM_UNLIKELY (yy == 0))
1215 scm_num_overflow (s_scm_floor_quotient);
1216 else if (xx > 0)
1217 xx1 = xx - yy - 1;
1218 qq = xx1 / yy;
1219 if (SCM_LIKELY (SCM_FIXABLE (qq)))
1220 return SCM_I_MAKINUM (qq);
1221 else
1222 return scm_i_inum2big (qq);
1223 }
1224 else if (SCM_BIGP (y))
1225 {
1226 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
1227 scm_remember_upto_here_1 (y);
1228 if (sign > 0)
1229 return SCM_I_MAKINUM ((xx < 0) ? -1 : 0);
1230 else
1231 return SCM_I_MAKINUM ((xx > 0) ? -1 : 0);
1232 }
1233 else if (SCM_REALP (y))
1234 return scm_i_inexact_floor_quotient (xx, SCM_REAL_VALUE (y));
1235 else if (SCM_FRACTIONP (y))
1236 return scm_i_exact_rational_floor_quotient (x, y);
1237 else
1238 SCM_WTA_DISPATCH_2 (g_scm_floor_quotient, x, y, SCM_ARG2,
1239 s_scm_floor_quotient);
1240 }
1241 else if (SCM_BIGP (x))
1242 {
1243 if (SCM_LIKELY (SCM_I_INUMP (y)))
1244 {
1245 scm_t_inum yy = SCM_I_INUM (y);
1246 if (SCM_UNLIKELY (yy == 0))
1247 scm_num_overflow (s_scm_floor_quotient);
1248 else if (SCM_UNLIKELY (yy == 1))
1249 return x;
1250 else
1251 {
1252 SCM q = scm_i_mkbig ();
1253 if (yy > 0)
1254 mpz_fdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), yy);
1255 else
1256 {
1257 mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), -yy);
1258 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
1259 }
1260 scm_remember_upto_here_1 (x);
1261 return scm_i_normbig (q);
1262 }
1263 }
1264 else if (SCM_BIGP (y))
1265 {
1266 SCM q = scm_i_mkbig ();
1267 mpz_fdiv_q (SCM_I_BIG_MPZ (q),
1268 SCM_I_BIG_MPZ (x),
1269 SCM_I_BIG_MPZ (y));
1270 scm_remember_upto_here_2 (x, y);
1271 return scm_i_normbig (q);
1272 }
1273 else if (SCM_REALP (y))
1274 return scm_i_inexact_floor_quotient
1275 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
1276 else if (SCM_FRACTIONP (y))
1277 return scm_i_exact_rational_floor_quotient (x, y);
1278 else
1279 SCM_WTA_DISPATCH_2 (g_scm_floor_quotient, x, y, SCM_ARG2,
1280 s_scm_floor_quotient);
1281 }
1282 else if (SCM_REALP (x))
1283 {
1284 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
1285 SCM_BIGP (y) || SCM_FRACTIONP (y))
1286 return scm_i_inexact_floor_quotient
1287 (SCM_REAL_VALUE (x), scm_to_double (y));
1288 else
1289 SCM_WTA_DISPATCH_2 (g_scm_floor_quotient, x, y, SCM_ARG2,
1290 s_scm_floor_quotient);
1291 }
1292 else if (SCM_FRACTIONP (x))
1293 {
1294 if (SCM_REALP (y))
1295 return scm_i_inexact_floor_quotient
1296 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
1297 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
1298 return scm_i_exact_rational_floor_quotient (x, y);
1299 else
1300 SCM_WTA_DISPATCH_2 (g_scm_floor_quotient, x, y, SCM_ARG2,
1301 s_scm_floor_quotient);
1302 }
1303 else
1304 SCM_WTA_DISPATCH_2 (g_scm_floor_quotient, x, y, SCM_ARG1,
1305 s_scm_floor_quotient);
1306 }
1307 #undef FUNC_NAME
1308
1309 static SCM
1310 scm_i_inexact_floor_quotient (double x, double y)
1311 {
1312 if (SCM_UNLIKELY (y == 0))
1313 scm_num_overflow (s_scm_floor_quotient); /* or return a NaN? */
1314 else
1315 return scm_from_double (floor (x / y));
1316 }
1317
1318 static SCM
1319 scm_i_exact_rational_floor_quotient (SCM x, SCM y)
1320 {
1321 return scm_floor_quotient
1322 (scm_product (scm_numerator (x), scm_denominator (y)),
1323 scm_product (scm_numerator (y), scm_denominator (x)));
1324 }
1325
1326 static SCM scm_i_inexact_floor_remainder (double x, double y);
1327 static SCM scm_i_exact_rational_floor_remainder (SCM x, SCM y);
1328
1329 SCM_PRIMITIVE_GENERIC (scm_floor_remainder, "floor-remainder", 2, 0, 0,
1330 (SCM x, SCM y),
1331 "Return the real number @var{r} such that\n"
1332 "@math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1333 "where @math{@var{q} = floor(@var{x} / @var{y})}.\n"
1334 "@lisp\n"
1335 "(floor-remainder 123 10) @result{} 3\n"
1336 "(floor-remainder 123 -10) @result{} -7\n"
1337 "(floor-remainder -123 10) @result{} 7\n"
1338 "(floor-remainder -123 -10) @result{} -3\n"
1339 "(floor-remainder -123.2 -63.5) @result{} -59.7\n"
1340 "(floor-remainder 16/3 -10/7) @result{} -8/21\n"
1341 "@end lisp")
1342 #define FUNC_NAME s_scm_floor_remainder
1343 {
1344 if (SCM_LIKELY (SCM_I_INUMP (x)))
1345 {
1346 scm_t_inum xx = SCM_I_INUM (x);
1347 if (SCM_LIKELY (SCM_I_INUMP (y)))
1348 {
1349 scm_t_inum yy = SCM_I_INUM (y);
1350 if (SCM_UNLIKELY (yy == 0))
1351 scm_num_overflow (s_scm_floor_remainder);
1352 else
1353 {
1354 scm_t_inum rr = xx % yy;
1355 int needs_adjustment;
1356
1357 if (SCM_LIKELY (yy > 0))
1358 needs_adjustment = (rr < 0);
1359 else
1360 needs_adjustment = (rr > 0);
1361
1362 if (needs_adjustment)
1363 rr += yy;
1364 return SCM_I_MAKINUM (rr);
1365 }
1366 }
1367 else if (SCM_BIGP (y))
1368 {
1369 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
1370 scm_remember_upto_here_1 (y);
1371 if (sign > 0)
1372 {
1373 if (xx < 0)
1374 {
1375 SCM r = scm_i_mkbig ();
1376 mpz_sub_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), -xx);
1377 scm_remember_upto_here_1 (y);
1378 return scm_i_normbig (r);
1379 }
1380 else
1381 return x;
1382 }
1383 else if (xx <= 0)
1384 return x;
1385 else
1386 {
1387 SCM r = scm_i_mkbig ();
1388 mpz_add_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), xx);
1389 scm_remember_upto_here_1 (y);
1390 return scm_i_normbig (r);
1391 }
1392 }
1393 else if (SCM_REALP (y))
1394 return scm_i_inexact_floor_remainder (xx, SCM_REAL_VALUE (y));
1395 else if (SCM_FRACTIONP (y))
1396 return scm_i_exact_rational_floor_remainder (x, y);
1397 else
1398 SCM_WTA_DISPATCH_2 (g_scm_floor_remainder, x, y, SCM_ARG2,
1399 s_scm_floor_remainder);
1400 }
1401 else if (SCM_BIGP (x))
1402 {
1403 if (SCM_LIKELY (SCM_I_INUMP (y)))
1404 {
1405 scm_t_inum yy = SCM_I_INUM (y);
1406 if (SCM_UNLIKELY (yy == 0))
1407 scm_num_overflow (s_scm_floor_remainder);
1408 else
1409 {
1410 scm_t_inum rr;
1411 if (yy > 0)
1412 rr = mpz_fdiv_ui (SCM_I_BIG_MPZ (x), yy);
1413 else
1414 rr = -mpz_cdiv_ui (SCM_I_BIG_MPZ (x), -yy);
1415 scm_remember_upto_here_1 (x);
1416 return SCM_I_MAKINUM (rr);
1417 }
1418 }
1419 else if (SCM_BIGP (y))
1420 {
1421 SCM r = scm_i_mkbig ();
1422 mpz_fdiv_r (SCM_I_BIG_MPZ (r),
1423 SCM_I_BIG_MPZ (x),
1424 SCM_I_BIG_MPZ (y));
1425 scm_remember_upto_here_2 (x, y);
1426 return scm_i_normbig (r);
1427 }
1428 else if (SCM_REALP (y))
1429 return scm_i_inexact_floor_remainder
1430 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
1431 else if (SCM_FRACTIONP (y))
1432 return scm_i_exact_rational_floor_remainder (x, y);
1433 else
1434 SCM_WTA_DISPATCH_2 (g_scm_floor_remainder, x, y, SCM_ARG2,
1435 s_scm_floor_remainder);
1436 }
1437 else if (SCM_REALP (x))
1438 {
1439 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
1440 SCM_BIGP (y) || SCM_FRACTIONP (y))
1441 return scm_i_inexact_floor_remainder
1442 (SCM_REAL_VALUE (x), scm_to_double (y));
1443 else
1444 SCM_WTA_DISPATCH_2 (g_scm_floor_remainder, x, y, SCM_ARG2,
1445 s_scm_floor_remainder);
1446 }
1447 else if (SCM_FRACTIONP (x))
1448 {
1449 if (SCM_REALP (y))
1450 return scm_i_inexact_floor_remainder
1451 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
1452 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
1453 return scm_i_exact_rational_floor_remainder (x, y);
1454 else
1455 SCM_WTA_DISPATCH_2 (g_scm_floor_remainder, x, y, SCM_ARG2,
1456 s_scm_floor_remainder);
1457 }
1458 else
1459 SCM_WTA_DISPATCH_2 (g_scm_floor_remainder, x, y, SCM_ARG1,
1460 s_scm_floor_remainder);
1461 }
1462 #undef FUNC_NAME
1463
1464 static SCM
1465 scm_i_inexact_floor_remainder (double x, double y)
1466 {
1467 /* Although it would be more efficient to use fmod here, we can't
1468 because it would in some cases produce results inconsistent with
1469 scm_i_inexact_floor_quotient, such that x != q * y + r (not even
1470 close). In particular, when x is very close to a multiple of y,
1471 then r might be either 0.0 or y, but those two cases must
1472 correspond to different choices of q. If r = 0.0 then q must be
1473 x/y, and if r = y then q must be x/y-1. If quotient chooses one
1474 and remainder chooses the other, it would be bad. */
1475 if (SCM_UNLIKELY (y == 0))
1476 scm_num_overflow (s_scm_floor_remainder); /* or return a NaN? */
1477 else
1478 return scm_from_double (x - y * floor (x / y));
1479 }
1480
1481 static SCM
1482 scm_i_exact_rational_floor_remainder (SCM x, SCM y)
1483 {
1484 SCM xd = scm_denominator (x);
1485 SCM yd = scm_denominator (y);
1486 SCM r1 = scm_floor_remainder (scm_product (scm_numerator (x), yd),
1487 scm_product (scm_numerator (y), xd));
1488 return scm_divide (r1, scm_product (xd, yd));
1489 }
1490
1491
1492 static void scm_i_inexact_floor_divide (double x, double y,
1493 SCM *qp, SCM *rp);
1494 static void scm_i_exact_rational_floor_divide (SCM x, SCM y,
1495 SCM *qp, SCM *rp);
1496
1497 SCM_PRIMITIVE_GENERIC (scm_i_floor_divide, "floor/", 2, 0, 0,
1498 (SCM x, SCM y),
1499 "Return the integer @var{q} and the real number @var{r}\n"
1500 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1501 "and @math{@var{q} = floor(@var{x} / @var{y})}.\n"
1502 "@lisp\n"
1503 "(floor/ 123 10) @result{} 12 and 3\n"
1504 "(floor/ 123 -10) @result{} -13 and -7\n"
1505 "(floor/ -123 10) @result{} -13 and 7\n"
1506 "(floor/ -123 -10) @result{} 12 and -3\n"
1507 "(floor/ -123.2 -63.5) @result{} 1.0 and -59.7\n"
1508 "(floor/ 16/3 -10/7) @result{} -4 and -8/21\n"
1509 "@end lisp")
1510 #define FUNC_NAME s_scm_i_floor_divide
1511 {
1512 SCM q, r;
1513
1514 scm_floor_divide(x, y, &q, &r);
1515 return scm_values (scm_list_2 (q, r));
1516 }
1517 #undef FUNC_NAME
1518
1519 #define s_scm_floor_divide s_scm_i_floor_divide
1520 #define g_scm_floor_divide g_scm_i_floor_divide
1521
1522 void
1523 scm_floor_divide (SCM x, SCM y, SCM *qp, SCM *rp)
1524 {
1525 if (SCM_LIKELY (SCM_I_INUMP (x)))
1526 {
1527 scm_t_inum xx = SCM_I_INUM (x);
1528 if (SCM_LIKELY (SCM_I_INUMP (y)))
1529 {
1530 scm_t_inum yy = SCM_I_INUM (y);
1531 if (SCM_UNLIKELY (yy == 0))
1532 scm_num_overflow (s_scm_floor_divide);
1533 else
1534 {
1535 scm_t_inum qq = xx / yy;
1536 scm_t_inum rr = xx % yy;
1537 int needs_adjustment;
1538
1539 if (SCM_LIKELY (yy > 0))
1540 needs_adjustment = (rr < 0);
1541 else
1542 needs_adjustment = (rr > 0);
1543
1544 if (needs_adjustment)
1545 {
1546 rr += yy;
1547 qq--;
1548 }
1549
1550 if (SCM_LIKELY (SCM_FIXABLE (qq)))
1551 *qp = SCM_I_MAKINUM (qq);
1552 else
1553 *qp = scm_i_inum2big (qq);
1554 *rp = SCM_I_MAKINUM (rr);
1555 }
1556 return;
1557 }
1558 else if (SCM_BIGP (y))
1559 {
1560 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
1561 scm_remember_upto_here_1 (y);
1562 if (sign > 0)
1563 {
1564 if (xx < 0)
1565 {
1566 SCM r = scm_i_mkbig ();
1567 mpz_sub_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), -xx);
1568 scm_remember_upto_here_1 (y);
1569 *qp = SCM_I_MAKINUM (-1);
1570 *rp = scm_i_normbig (r);
1571 }
1572 else
1573 {
1574 *qp = SCM_INUM0;
1575 *rp = x;
1576 }
1577 }
1578 else if (xx <= 0)
1579 {
1580 *qp = SCM_INUM0;
1581 *rp = x;
1582 }
1583 else
1584 {
1585 SCM r = scm_i_mkbig ();
1586 mpz_add_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), xx);
1587 scm_remember_upto_here_1 (y);
1588 *qp = SCM_I_MAKINUM (-1);
1589 *rp = scm_i_normbig (r);
1590 }
1591 return;
1592 }
1593 else if (SCM_REALP (y))
1594 return scm_i_inexact_floor_divide (xx, SCM_REAL_VALUE (y), qp, rp);
1595 else if (SCM_FRACTIONP (y))
1596 return scm_i_exact_rational_floor_divide (x, y, qp, rp);
1597 else
1598 return two_valued_wta_dispatch_2 (g_scm_floor_divide, x, y, SCM_ARG2,
1599 s_scm_floor_divide, qp, rp);
1600 }
1601 else if (SCM_BIGP (x))
1602 {
1603 if (SCM_LIKELY (SCM_I_INUMP (y)))
1604 {
1605 scm_t_inum yy = SCM_I_INUM (y);
1606 if (SCM_UNLIKELY (yy == 0))
1607 scm_num_overflow (s_scm_floor_divide);
1608 else
1609 {
1610 SCM q = scm_i_mkbig ();
1611 SCM r = scm_i_mkbig ();
1612 if (yy > 0)
1613 mpz_fdiv_qr_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
1614 SCM_I_BIG_MPZ (x), yy);
1615 else
1616 {
1617 mpz_cdiv_qr_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
1618 SCM_I_BIG_MPZ (x), -yy);
1619 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
1620 }
1621 scm_remember_upto_here_1 (x);
1622 *qp = scm_i_normbig (q);
1623 *rp = scm_i_normbig (r);
1624 }
1625 return;
1626 }
1627 else if (SCM_BIGP (y))
1628 {
1629 SCM q = scm_i_mkbig ();
1630 SCM r = scm_i_mkbig ();
1631 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
1632 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
1633 scm_remember_upto_here_2 (x, y);
1634 *qp = scm_i_normbig (q);
1635 *rp = scm_i_normbig (r);
1636 return;
1637 }
1638 else if (SCM_REALP (y))
1639 return scm_i_inexact_floor_divide
1640 (scm_i_big2dbl (x), SCM_REAL_VALUE (y), qp, rp);
1641 else if (SCM_FRACTIONP (y))
1642 return scm_i_exact_rational_floor_divide (x, y, qp, rp);
1643 else
1644 return two_valued_wta_dispatch_2 (g_scm_floor_divide, x, y, SCM_ARG2,
1645 s_scm_floor_divide, qp, rp);
1646 }
1647 else if (SCM_REALP (x))
1648 {
1649 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
1650 SCM_BIGP (y) || SCM_FRACTIONP (y))
1651 return scm_i_inexact_floor_divide
1652 (SCM_REAL_VALUE (x), scm_to_double (y), qp, rp);
1653 else
1654 return two_valued_wta_dispatch_2 (g_scm_floor_divide, x, y, SCM_ARG2,
1655 s_scm_floor_divide, qp, rp);
1656 }
1657 else if (SCM_FRACTIONP (x))
1658 {
1659 if (SCM_REALP (y))
1660 return scm_i_inexact_floor_divide
1661 (scm_i_fraction2double (x), SCM_REAL_VALUE (y), qp, rp);
1662 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
1663 return scm_i_exact_rational_floor_divide (x, y, qp, rp);
1664 else
1665 return two_valued_wta_dispatch_2 (g_scm_floor_divide, x, y, SCM_ARG2,
1666 s_scm_floor_divide, qp, rp);
1667 }
1668 else
1669 return two_valued_wta_dispatch_2 (g_scm_floor_divide, x, y, SCM_ARG1,
1670 s_scm_floor_divide, qp, rp);
1671 }
1672
1673 static void
1674 scm_i_inexact_floor_divide (double x, double y, SCM *qp, SCM *rp)
1675 {
1676 if (SCM_UNLIKELY (y == 0))
1677 scm_num_overflow (s_scm_floor_divide); /* or return a NaN? */
1678 else
1679 {
1680 double q = floor (x / y);
1681 double r = x - q * y;
1682 *qp = scm_from_double (q);
1683 *rp = scm_from_double (r);
1684 }
1685 }
1686
1687 static void
1688 scm_i_exact_rational_floor_divide (SCM x, SCM y, SCM *qp, SCM *rp)
1689 {
1690 SCM r1;
1691 SCM xd = scm_denominator (x);
1692 SCM yd = scm_denominator (y);
1693
1694 scm_floor_divide (scm_product (scm_numerator (x), yd),
1695 scm_product (scm_numerator (y), xd),
1696 qp, &r1);
1697 *rp = scm_divide (r1, scm_product (xd, yd));
1698 }
1699
1700 static SCM scm_i_inexact_ceiling_quotient (double x, double y);
1701 static SCM scm_i_exact_rational_ceiling_quotient (SCM x, SCM y);
1702
1703 SCM_PRIMITIVE_GENERIC (scm_ceiling_quotient, "ceiling-quotient", 2, 0, 0,
1704 (SCM x, SCM y),
1705 "Return the ceiling of @math{@var{x} / @var{y}}.\n"
1706 "@lisp\n"
1707 "(ceiling-quotient 123 10) @result{} 13\n"
1708 "(ceiling-quotient 123 -10) @result{} -12\n"
1709 "(ceiling-quotient -123 10) @result{} -12\n"
1710 "(ceiling-quotient -123 -10) @result{} 13\n"
1711 "(ceiling-quotient -123.2 -63.5) @result{} 2.0\n"
1712 "(ceiling-quotient 16/3 -10/7) @result{} -3\n"
1713 "@end lisp")
1714 #define FUNC_NAME s_scm_ceiling_quotient
1715 {
1716 if (SCM_LIKELY (SCM_I_INUMP (x)))
1717 {
1718 scm_t_inum xx = SCM_I_INUM (x);
1719 if (SCM_LIKELY (SCM_I_INUMP (y)))
1720 {
1721 scm_t_inum yy = SCM_I_INUM (y);
1722 if (SCM_UNLIKELY (yy == 0))
1723 scm_num_overflow (s_scm_ceiling_quotient);
1724 else
1725 {
1726 scm_t_inum xx1 = xx;
1727 scm_t_inum qq;
1728 if (SCM_LIKELY (yy > 0))
1729 {
1730 if (SCM_LIKELY (xx >= 0))
1731 xx1 = xx + yy - 1;
1732 }
1733 else if (xx < 0)
1734 xx1 = xx + yy + 1;
1735 qq = xx1 / yy;
1736 if (SCM_LIKELY (SCM_FIXABLE (qq)))
1737 return SCM_I_MAKINUM (qq);
1738 else
1739 return scm_i_inum2big (qq);
1740 }
1741 }
1742 else if (SCM_BIGP (y))
1743 {
1744 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
1745 scm_remember_upto_here_1 (y);
1746 if (SCM_LIKELY (sign > 0))
1747 {
1748 if (SCM_LIKELY (xx > 0))
1749 return SCM_INUM1;
1750 else if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
1751 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
1752 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
1753 {
1754 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
1755 scm_remember_upto_here_1 (y);
1756 return SCM_I_MAKINUM (-1);
1757 }
1758 else
1759 return SCM_INUM0;
1760 }
1761 else if (xx >= 0)
1762 return SCM_INUM0;
1763 else
1764 return SCM_INUM1;
1765 }
1766 else if (SCM_REALP (y))
1767 return scm_i_inexact_ceiling_quotient (xx, SCM_REAL_VALUE (y));
1768 else if (SCM_FRACTIONP (y))
1769 return scm_i_exact_rational_ceiling_quotient (x, y);
1770 else
1771 SCM_WTA_DISPATCH_2 (g_scm_ceiling_quotient, x, y, SCM_ARG2,
1772 s_scm_ceiling_quotient);
1773 }
1774 else if (SCM_BIGP (x))
1775 {
1776 if (SCM_LIKELY (SCM_I_INUMP (y)))
1777 {
1778 scm_t_inum yy = SCM_I_INUM (y);
1779 if (SCM_UNLIKELY (yy == 0))
1780 scm_num_overflow (s_scm_ceiling_quotient);
1781 else if (SCM_UNLIKELY (yy == 1))
1782 return x;
1783 else
1784 {
1785 SCM q = scm_i_mkbig ();
1786 if (yy > 0)
1787 mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), yy);
1788 else
1789 {
1790 mpz_fdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), -yy);
1791 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
1792 }
1793 scm_remember_upto_here_1 (x);
1794 return scm_i_normbig (q);
1795 }
1796 }
1797 else if (SCM_BIGP (y))
1798 {
1799 SCM q = scm_i_mkbig ();
1800 mpz_cdiv_q (SCM_I_BIG_MPZ (q),
1801 SCM_I_BIG_MPZ (x),
1802 SCM_I_BIG_MPZ (y));
1803 scm_remember_upto_here_2 (x, y);
1804 return scm_i_normbig (q);
1805 }
1806 else if (SCM_REALP (y))
1807 return scm_i_inexact_ceiling_quotient
1808 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
1809 else if (SCM_FRACTIONP (y))
1810 return scm_i_exact_rational_ceiling_quotient (x, y);
1811 else
1812 SCM_WTA_DISPATCH_2 (g_scm_ceiling_quotient, x, y, SCM_ARG2,
1813 s_scm_ceiling_quotient);
1814 }
1815 else if (SCM_REALP (x))
1816 {
1817 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
1818 SCM_BIGP (y) || SCM_FRACTIONP (y))
1819 return scm_i_inexact_ceiling_quotient
1820 (SCM_REAL_VALUE (x), scm_to_double (y));
1821 else
1822 SCM_WTA_DISPATCH_2 (g_scm_ceiling_quotient, x, y, SCM_ARG2,
1823 s_scm_ceiling_quotient);
1824 }
1825 else if (SCM_FRACTIONP (x))
1826 {
1827 if (SCM_REALP (y))
1828 return scm_i_inexact_ceiling_quotient
1829 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
1830 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
1831 return scm_i_exact_rational_ceiling_quotient (x, y);
1832 else
1833 SCM_WTA_DISPATCH_2 (g_scm_ceiling_quotient, x, y, SCM_ARG2,
1834 s_scm_ceiling_quotient);
1835 }
1836 else
1837 SCM_WTA_DISPATCH_2 (g_scm_ceiling_quotient, x, y, SCM_ARG1,
1838 s_scm_ceiling_quotient);
1839 }
1840 #undef FUNC_NAME
1841
1842 static SCM
1843 scm_i_inexact_ceiling_quotient (double x, double y)
1844 {
1845 if (SCM_UNLIKELY (y == 0))
1846 scm_num_overflow (s_scm_ceiling_quotient); /* or return a NaN? */
1847 else
1848 return scm_from_double (ceil (x / y));
1849 }
1850
1851 static SCM
1852 scm_i_exact_rational_ceiling_quotient (SCM x, SCM y)
1853 {
1854 return scm_ceiling_quotient
1855 (scm_product (scm_numerator (x), scm_denominator (y)),
1856 scm_product (scm_numerator (y), scm_denominator (x)));
1857 }
1858
1859 static SCM scm_i_inexact_ceiling_remainder (double x, double y);
1860 static SCM scm_i_exact_rational_ceiling_remainder (SCM x, SCM y);
1861
1862 SCM_PRIMITIVE_GENERIC (scm_ceiling_remainder, "ceiling-remainder", 2, 0, 0,
1863 (SCM x, SCM y),
1864 "Return the real number @var{r} such that\n"
1865 "@math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
1866 "where @math{@var{q} = ceiling(@var{x} / @var{y})}.\n"
1867 "@lisp\n"
1868 "(ceiling-remainder 123 10) @result{} -7\n"
1869 "(ceiling-remainder 123 -10) @result{} 3\n"
1870 "(ceiling-remainder -123 10) @result{} -3\n"
1871 "(ceiling-remainder -123 -10) @result{} 7\n"
1872 "(ceiling-remainder -123.2 -63.5) @result{} 3.8\n"
1873 "(ceiling-remainder 16/3 -10/7) @result{} 22/21\n"
1874 "@end lisp")
1875 #define FUNC_NAME s_scm_ceiling_remainder
1876 {
1877 if (SCM_LIKELY (SCM_I_INUMP (x)))
1878 {
1879 scm_t_inum xx = SCM_I_INUM (x);
1880 if (SCM_LIKELY (SCM_I_INUMP (y)))
1881 {
1882 scm_t_inum yy = SCM_I_INUM (y);
1883 if (SCM_UNLIKELY (yy == 0))
1884 scm_num_overflow (s_scm_ceiling_remainder);
1885 else
1886 {
1887 scm_t_inum rr = xx % yy;
1888 int needs_adjustment;
1889
1890 if (SCM_LIKELY (yy > 0))
1891 needs_adjustment = (rr > 0);
1892 else
1893 needs_adjustment = (rr < 0);
1894
1895 if (needs_adjustment)
1896 rr -= yy;
1897 return SCM_I_MAKINUM (rr);
1898 }
1899 }
1900 else if (SCM_BIGP (y))
1901 {
1902 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
1903 scm_remember_upto_here_1 (y);
1904 if (SCM_LIKELY (sign > 0))
1905 {
1906 if (SCM_LIKELY (xx > 0))
1907 {
1908 SCM r = scm_i_mkbig ();
1909 mpz_sub_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), xx);
1910 scm_remember_upto_here_1 (y);
1911 mpz_neg (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r));
1912 return scm_i_normbig (r);
1913 }
1914 else if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
1915 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
1916 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
1917 {
1918 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
1919 scm_remember_upto_here_1 (y);
1920 return SCM_INUM0;
1921 }
1922 else
1923 return x;
1924 }
1925 else if (xx >= 0)
1926 return x;
1927 else
1928 {
1929 SCM r = scm_i_mkbig ();
1930 mpz_add_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), -xx);
1931 scm_remember_upto_here_1 (y);
1932 mpz_neg (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r));
1933 return scm_i_normbig (r);
1934 }
1935 }
1936 else if (SCM_REALP (y))
1937 return scm_i_inexact_ceiling_remainder (xx, SCM_REAL_VALUE (y));
1938 else if (SCM_FRACTIONP (y))
1939 return scm_i_exact_rational_ceiling_remainder (x, y);
1940 else
1941 SCM_WTA_DISPATCH_2 (g_scm_ceiling_remainder, x, y, SCM_ARG2,
1942 s_scm_ceiling_remainder);
1943 }
1944 else if (SCM_BIGP (x))
1945 {
1946 if (SCM_LIKELY (SCM_I_INUMP (y)))
1947 {
1948 scm_t_inum yy = SCM_I_INUM (y);
1949 if (SCM_UNLIKELY (yy == 0))
1950 scm_num_overflow (s_scm_ceiling_remainder);
1951 else
1952 {
1953 scm_t_inum rr;
1954 if (yy > 0)
1955 rr = -mpz_cdiv_ui (SCM_I_BIG_MPZ (x), yy);
1956 else
1957 rr = mpz_fdiv_ui (SCM_I_BIG_MPZ (x), -yy);
1958 scm_remember_upto_here_1 (x);
1959 return SCM_I_MAKINUM (rr);
1960 }
1961 }
1962 else if (SCM_BIGP (y))
1963 {
1964 SCM r = scm_i_mkbig ();
1965 mpz_cdiv_r (SCM_I_BIG_MPZ (r),
1966 SCM_I_BIG_MPZ (x),
1967 SCM_I_BIG_MPZ (y));
1968 scm_remember_upto_here_2 (x, y);
1969 return scm_i_normbig (r);
1970 }
1971 else if (SCM_REALP (y))
1972 return scm_i_inexact_ceiling_remainder
1973 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
1974 else if (SCM_FRACTIONP (y))
1975 return scm_i_exact_rational_ceiling_remainder (x, y);
1976 else
1977 SCM_WTA_DISPATCH_2 (g_scm_ceiling_remainder, x, y, SCM_ARG2,
1978 s_scm_ceiling_remainder);
1979 }
1980 else if (SCM_REALP (x))
1981 {
1982 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
1983 SCM_BIGP (y) || SCM_FRACTIONP (y))
1984 return scm_i_inexact_ceiling_remainder
1985 (SCM_REAL_VALUE (x), scm_to_double (y));
1986 else
1987 SCM_WTA_DISPATCH_2 (g_scm_ceiling_remainder, x, y, SCM_ARG2,
1988 s_scm_ceiling_remainder);
1989 }
1990 else if (SCM_FRACTIONP (x))
1991 {
1992 if (SCM_REALP (y))
1993 return scm_i_inexact_ceiling_remainder
1994 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
1995 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
1996 return scm_i_exact_rational_ceiling_remainder (x, y);
1997 else
1998 SCM_WTA_DISPATCH_2 (g_scm_ceiling_remainder, x, y, SCM_ARG2,
1999 s_scm_ceiling_remainder);
2000 }
2001 else
2002 SCM_WTA_DISPATCH_2 (g_scm_ceiling_remainder, x, y, SCM_ARG1,
2003 s_scm_ceiling_remainder);
2004 }
2005 #undef FUNC_NAME
2006
2007 static SCM
2008 scm_i_inexact_ceiling_remainder (double x, double y)
2009 {
2010 /* Although it would be more efficient to use fmod here, we can't
2011 because it would in some cases produce results inconsistent with
2012 scm_i_inexact_ceiling_quotient, such that x != q * y + r (not even
2013 close). In particular, when x is very close to a multiple of y,
2014 then r might be either 0.0 or -y, but those two cases must
2015 correspond to different choices of q. If r = 0.0 then q must be
2016 x/y, and if r = -y then q must be x/y+1. If quotient chooses one
2017 and remainder chooses the other, it would be bad. */
2018 if (SCM_UNLIKELY (y == 0))
2019 scm_num_overflow (s_scm_ceiling_remainder); /* or return a NaN? */
2020 else
2021 return scm_from_double (x - y * ceil (x / y));
2022 }
2023
2024 static SCM
2025 scm_i_exact_rational_ceiling_remainder (SCM x, SCM y)
2026 {
2027 SCM xd = scm_denominator (x);
2028 SCM yd = scm_denominator (y);
2029 SCM r1 = scm_ceiling_remainder (scm_product (scm_numerator (x), yd),
2030 scm_product (scm_numerator (y), xd));
2031 return scm_divide (r1, scm_product (xd, yd));
2032 }
2033
2034 static void scm_i_inexact_ceiling_divide (double x, double y,
2035 SCM *qp, SCM *rp);
2036 static void scm_i_exact_rational_ceiling_divide (SCM x, SCM y,
2037 SCM *qp, SCM *rp);
2038
2039 SCM_PRIMITIVE_GENERIC (scm_i_ceiling_divide, "ceiling/", 2, 0, 0,
2040 (SCM x, SCM y),
2041 "Return the integer @var{q} and the real number @var{r}\n"
2042 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
2043 "and @math{@var{q} = ceiling(@var{x} / @var{y})}.\n"
2044 "@lisp\n"
2045 "(ceiling/ 123 10) @result{} 13 and -7\n"
2046 "(ceiling/ 123 -10) @result{} -12 and 3\n"
2047 "(ceiling/ -123 10) @result{} -12 and -3\n"
2048 "(ceiling/ -123 -10) @result{} 13 and 7\n"
2049 "(ceiling/ -123.2 -63.5) @result{} 2.0 and 3.8\n"
2050 "(ceiling/ 16/3 -10/7) @result{} -3 and 22/21\n"
2051 "@end lisp")
2052 #define FUNC_NAME s_scm_i_ceiling_divide
2053 {
2054 SCM q, r;
2055
2056 scm_ceiling_divide(x, y, &q, &r);
2057 return scm_values (scm_list_2 (q, r));
2058 }
2059 #undef FUNC_NAME
2060
2061 #define s_scm_ceiling_divide s_scm_i_ceiling_divide
2062 #define g_scm_ceiling_divide g_scm_i_ceiling_divide
2063
2064 void
2065 scm_ceiling_divide (SCM x, SCM y, SCM *qp, SCM *rp)
2066 {
2067 if (SCM_LIKELY (SCM_I_INUMP (x)))
2068 {
2069 scm_t_inum xx = SCM_I_INUM (x);
2070 if (SCM_LIKELY (SCM_I_INUMP (y)))
2071 {
2072 scm_t_inum yy = SCM_I_INUM (y);
2073 if (SCM_UNLIKELY (yy == 0))
2074 scm_num_overflow (s_scm_ceiling_divide);
2075 else
2076 {
2077 scm_t_inum qq = xx / yy;
2078 scm_t_inum rr = xx % yy;
2079 int needs_adjustment;
2080
2081 if (SCM_LIKELY (yy > 0))
2082 needs_adjustment = (rr > 0);
2083 else
2084 needs_adjustment = (rr < 0);
2085
2086 if (needs_adjustment)
2087 {
2088 rr -= yy;
2089 qq++;
2090 }
2091 if (SCM_LIKELY (SCM_FIXABLE (qq)))
2092 *qp = SCM_I_MAKINUM (qq);
2093 else
2094 *qp = scm_i_inum2big (qq);
2095 *rp = SCM_I_MAKINUM (rr);
2096 }
2097 return;
2098 }
2099 else if (SCM_BIGP (y))
2100 {
2101 int sign = mpz_sgn (SCM_I_BIG_MPZ (y));
2102 scm_remember_upto_here_1 (y);
2103 if (SCM_LIKELY (sign > 0))
2104 {
2105 if (SCM_LIKELY (xx > 0))
2106 {
2107 SCM r = scm_i_mkbig ();
2108 mpz_sub_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), xx);
2109 scm_remember_upto_here_1 (y);
2110 mpz_neg (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r));
2111 *qp = SCM_INUM1;
2112 *rp = scm_i_normbig (r);
2113 }
2114 else if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
2115 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
2116 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
2117 {
2118 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
2119 scm_remember_upto_here_1 (y);
2120 *qp = SCM_I_MAKINUM (-1);
2121 *rp = SCM_INUM0;
2122 }
2123 else
2124 {
2125 *qp = SCM_INUM0;
2126 *rp = x;
2127 }
2128 }
2129 else if (xx >= 0)
2130 {
2131 *qp = SCM_INUM0;
2132 *rp = x;
2133 }
2134 else
2135 {
2136 SCM r = scm_i_mkbig ();
2137 mpz_add_ui (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y), -xx);
2138 scm_remember_upto_here_1 (y);
2139 mpz_neg (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r));
2140 *qp = SCM_INUM1;
2141 *rp = scm_i_normbig (r);
2142 }
2143 return;
2144 }
2145 else if (SCM_REALP (y))
2146 return scm_i_inexact_ceiling_divide (xx, SCM_REAL_VALUE (y), qp, rp);
2147 else if (SCM_FRACTIONP (y))
2148 return scm_i_exact_rational_ceiling_divide (x, y, qp, rp);
2149 else
2150 return two_valued_wta_dispatch_2 (g_scm_ceiling_divide, x, y, SCM_ARG2,
2151 s_scm_ceiling_divide, qp, rp);
2152 }
2153 else if (SCM_BIGP (x))
2154 {
2155 if (SCM_LIKELY (SCM_I_INUMP (y)))
2156 {
2157 scm_t_inum yy = SCM_I_INUM (y);
2158 if (SCM_UNLIKELY (yy == 0))
2159 scm_num_overflow (s_scm_ceiling_divide);
2160 else
2161 {
2162 SCM q = scm_i_mkbig ();
2163 SCM r = scm_i_mkbig ();
2164 if (yy > 0)
2165 mpz_cdiv_qr_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2166 SCM_I_BIG_MPZ (x), yy);
2167 else
2168 {
2169 mpz_fdiv_qr_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2170 SCM_I_BIG_MPZ (x), -yy);
2171 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
2172 }
2173 scm_remember_upto_here_1 (x);
2174 *qp = scm_i_normbig (q);
2175 *rp = scm_i_normbig (r);
2176 }
2177 return;
2178 }
2179 else if (SCM_BIGP (y))
2180 {
2181 SCM q = scm_i_mkbig ();
2182 SCM r = scm_i_mkbig ();
2183 mpz_cdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2184 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
2185 scm_remember_upto_here_2 (x, y);
2186 *qp = scm_i_normbig (q);
2187 *rp = scm_i_normbig (r);
2188 return;
2189 }
2190 else if (SCM_REALP (y))
2191 return scm_i_inexact_ceiling_divide
2192 (scm_i_big2dbl (x), SCM_REAL_VALUE (y), qp, rp);
2193 else if (SCM_FRACTIONP (y))
2194 return scm_i_exact_rational_ceiling_divide (x, y, qp, rp);
2195 else
2196 return two_valued_wta_dispatch_2 (g_scm_ceiling_divide, x, y, SCM_ARG2,
2197 s_scm_ceiling_divide, qp, rp);
2198 }
2199 else if (SCM_REALP (x))
2200 {
2201 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
2202 SCM_BIGP (y) || SCM_FRACTIONP (y))
2203 return scm_i_inexact_ceiling_divide
2204 (SCM_REAL_VALUE (x), scm_to_double (y), qp, rp);
2205 else
2206 return two_valued_wta_dispatch_2 (g_scm_ceiling_divide, x, y, SCM_ARG2,
2207 s_scm_ceiling_divide, qp, rp);
2208 }
2209 else if (SCM_FRACTIONP (x))
2210 {
2211 if (SCM_REALP (y))
2212 return scm_i_inexact_ceiling_divide
2213 (scm_i_fraction2double (x), SCM_REAL_VALUE (y), qp, rp);
2214 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
2215 return scm_i_exact_rational_ceiling_divide (x, y, qp, rp);
2216 else
2217 return two_valued_wta_dispatch_2 (g_scm_ceiling_divide, x, y, SCM_ARG2,
2218 s_scm_ceiling_divide, qp, rp);
2219 }
2220 else
2221 return two_valued_wta_dispatch_2 (g_scm_ceiling_divide, x, y, SCM_ARG1,
2222 s_scm_ceiling_divide, qp, rp);
2223 }
2224
2225 static void
2226 scm_i_inexact_ceiling_divide (double x, double y, SCM *qp, SCM *rp)
2227 {
2228 if (SCM_UNLIKELY (y == 0))
2229 scm_num_overflow (s_scm_ceiling_divide); /* or return a NaN? */
2230 else
2231 {
2232 double q = ceil (x / y);
2233 double r = x - q * y;
2234 *qp = scm_from_double (q);
2235 *rp = scm_from_double (r);
2236 }
2237 }
2238
2239 static void
2240 scm_i_exact_rational_ceiling_divide (SCM x, SCM y, SCM *qp, SCM *rp)
2241 {
2242 SCM r1;
2243 SCM xd = scm_denominator (x);
2244 SCM yd = scm_denominator (y);
2245
2246 scm_ceiling_divide (scm_product (scm_numerator (x), yd),
2247 scm_product (scm_numerator (y), xd),
2248 qp, &r1);
2249 *rp = scm_divide (r1, scm_product (xd, yd));
2250 }
2251
2252 static SCM scm_i_inexact_truncate_quotient (double x, double y);
2253 static SCM scm_i_exact_rational_truncate_quotient (SCM x, SCM y);
2254
2255 SCM_PRIMITIVE_GENERIC (scm_truncate_quotient, "truncate-quotient", 2, 0, 0,
2256 (SCM x, SCM y),
2257 "Return @math{@var{x} / @var{y}} rounded toward zero.\n"
2258 "@lisp\n"
2259 "(truncate-quotient 123 10) @result{} 12\n"
2260 "(truncate-quotient 123 -10) @result{} -12\n"
2261 "(truncate-quotient -123 10) @result{} -12\n"
2262 "(truncate-quotient -123 -10) @result{} 12\n"
2263 "(truncate-quotient -123.2 -63.5) @result{} 1.0\n"
2264 "(truncate-quotient 16/3 -10/7) @result{} -3\n"
2265 "@end lisp")
2266 #define FUNC_NAME s_scm_truncate_quotient
2267 {
2268 if (SCM_LIKELY (SCM_I_INUMP (x)))
2269 {
2270 scm_t_inum xx = SCM_I_INUM (x);
2271 if (SCM_LIKELY (SCM_I_INUMP (y)))
2272 {
2273 scm_t_inum yy = SCM_I_INUM (y);
2274 if (SCM_UNLIKELY (yy == 0))
2275 scm_num_overflow (s_scm_truncate_quotient);
2276 else
2277 {
2278 scm_t_inum qq = xx / yy;
2279 if (SCM_LIKELY (SCM_FIXABLE (qq)))
2280 return SCM_I_MAKINUM (qq);
2281 else
2282 return scm_i_inum2big (qq);
2283 }
2284 }
2285 else if (SCM_BIGP (y))
2286 {
2287 if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
2288 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
2289 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
2290 {
2291 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
2292 scm_remember_upto_here_1 (y);
2293 return SCM_I_MAKINUM (-1);
2294 }
2295 else
2296 return SCM_INUM0;
2297 }
2298 else if (SCM_REALP (y))
2299 return scm_i_inexact_truncate_quotient (xx, SCM_REAL_VALUE (y));
2300 else if (SCM_FRACTIONP (y))
2301 return scm_i_exact_rational_truncate_quotient (x, y);
2302 else
2303 SCM_WTA_DISPATCH_2 (g_scm_truncate_quotient, x, y, SCM_ARG2,
2304 s_scm_truncate_quotient);
2305 }
2306 else if (SCM_BIGP (x))
2307 {
2308 if (SCM_LIKELY (SCM_I_INUMP (y)))
2309 {
2310 scm_t_inum yy = SCM_I_INUM (y);
2311 if (SCM_UNLIKELY (yy == 0))
2312 scm_num_overflow (s_scm_truncate_quotient);
2313 else if (SCM_UNLIKELY (yy == 1))
2314 return x;
2315 else
2316 {
2317 SCM q = scm_i_mkbig ();
2318 if (yy > 0)
2319 mpz_tdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), yy);
2320 else
2321 {
2322 mpz_tdiv_q_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (x), -yy);
2323 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
2324 }
2325 scm_remember_upto_here_1 (x);
2326 return scm_i_normbig (q);
2327 }
2328 }
2329 else if (SCM_BIGP (y))
2330 {
2331 SCM q = scm_i_mkbig ();
2332 mpz_tdiv_q (SCM_I_BIG_MPZ (q),
2333 SCM_I_BIG_MPZ (x),
2334 SCM_I_BIG_MPZ (y));
2335 scm_remember_upto_here_2 (x, y);
2336 return scm_i_normbig (q);
2337 }
2338 else if (SCM_REALP (y))
2339 return scm_i_inexact_truncate_quotient
2340 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
2341 else if (SCM_FRACTIONP (y))
2342 return scm_i_exact_rational_truncate_quotient (x, y);
2343 else
2344 SCM_WTA_DISPATCH_2 (g_scm_truncate_quotient, x, y, SCM_ARG2,
2345 s_scm_truncate_quotient);
2346 }
2347 else if (SCM_REALP (x))
2348 {
2349 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
2350 SCM_BIGP (y) || SCM_FRACTIONP (y))
2351 return scm_i_inexact_truncate_quotient
2352 (SCM_REAL_VALUE (x), scm_to_double (y));
2353 else
2354 SCM_WTA_DISPATCH_2 (g_scm_truncate_quotient, x, y, SCM_ARG2,
2355 s_scm_truncate_quotient);
2356 }
2357 else if (SCM_FRACTIONP (x))
2358 {
2359 if (SCM_REALP (y))
2360 return scm_i_inexact_truncate_quotient
2361 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
2362 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
2363 return scm_i_exact_rational_truncate_quotient (x, y);
2364 else
2365 SCM_WTA_DISPATCH_2 (g_scm_truncate_quotient, x, y, SCM_ARG2,
2366 s_scm_truncate_quotient);
2367 }
2368 else
2369 SCM_WTA_DISPATCH_2 (g_scm_truncate_quotient, x, y, SCM_ARG1,
2370 s_scm_truncate_quotient);
2371 }
2372 #undef FUNC_NAME
2373
2374 static SCM
2375 scm_i_inexact_truncate_quotient (double x, double y)
2376 {
2377 if (SCM_UNLIKELY (y == 0))
2378 scm_num_overflow (s_scm_truncate_quotient); /* or return a NaN? */
2379 else
2380 return scm_from_double (trunc (x / y));
2381 }
2382
2383 static SCM
2384 scm_i_exact_rational_truncate_quotient (SCM x, SCM y)
2385 {
2386 return scm_truncate_quotient
2387 (scm_product (scm_numerator (x), scm_denominator (y)),
2388 scm_product (scm_numerator (y), scm_denominator (x)));
2389 }
2390
2391 static SCM scm_i_inexact_truncate_remainder (double x, double y);
2392 static SCM scm_i_exact_rational_truncate_remainder (SCM x, SCM y);
2393
2394 SCM_PRIMITIVE_GENERIC (scm_truncate_remainder, "truncate-remainder", 2, 0, 0,
2395 (SCM x, SCM y),
2396 "Return the real number @var{r} such that\n"
2397 "@math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
2398 "where @math{@var{q} = truncate(@var{x} / @var{y})}.\n"
2399 "@lisp\n"
2400 "(truncate-remainder 123 10) @result{} 3\n"
2401 "(truncate-remainder 123 -10) @result{} 3\n"
2402 "(truncate-remainder -123 10) @result{} -3\n"
2403 "(truncate-remainder -123 -10) @result{} -3\n"
2404 "(truncate-remainder -123.2 -63.5) @result{} -59.7\n"
2405 "(truncate-remainder 16/3 -10/7) @result{} 22/21\n"
2406 "@end lisp")
2407 #define FUNC_NAME s_scm_truncate_remainder
2408 {
2409 if (SCM_LIKELY (SCM_I_INUMP (x)))
2410 {
2411 scm_t_inum xx = SCM_I_INUM (x);
2412 if (SCM_LIKELY (SCM_I_INUMP (y)))
2413 {
2414 scm_t_inum yy = SCM_I_INUM (y);
2415 if (SCM_UNLIKELY (yy == 0))
2416 scm_num_overflow (s_scm_truncate_remainder);
2417 else
2418 return SCM_I_MAKINUM (xx % yy);
2419 }
2420 else if (SCM_BIGP (y))
2421 {
2422 if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
2423 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
2424 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
2425 {
2426 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
2427 scm_remember_upto_here_1 (y);
2428 return SCM_INUM0;
2429 }
2430 else
2431 return x;
2432 }
2433 else if (SCM_REALP (y))
2434 return scm_i_inexact_truncate_remainder (xx, SCM_REAL_VALUE (y));
2435 else if (SCM_FRACTIONP (y))
2436 return scm_i_exact_rational_truncate_remainder (x, y);
2437 else
2438 SCM_WTA_DISPATCH_2 (g_scm_truncate_remainder, x, y, SCM_ARG2,
2439 s_scm_truncate_remainder);
2440 }
2441 else if (SCM_BIGP (x))
2442 {
2443 if (SCM_LIKELY (SCM_I_INUMP (y)))
2444 {
2445 scm_t_inum yy = SCM_I_INUM (y);
2446 if (SCM_UNLIKELY (yy == 0))
2447 scm_num_overflow (s_scm_truncate_remainder);
2448 else
2449 {
2450 scm_t_inum rr = (mpz_tdiv_ui (SCM_I_BIG_MPZ (x),
2451 (yy > 0) ? yy : -yy)
2452 * mpz_sgn (SCM_I_BIG_MPZ (x)));
2453 scm_remember_upto_here_1 (x);
2454 return SCM_I_MAKINUM (rr);
2455 }
2456 }
2457 else if (SCM_BIGP (y))
2458 {
2459 SCM r = scm_i_mkbig ();
2460 mpz_tdiv_r (SCM_I_BIG_MPZ (r),
2461 SCM_I_BIG_MPZ (x),
2462 SCM_I_BIG_MPZ (y));
2463 scm_remember_upto_here_2 (x, y);
2464 return scm_i_normbig (r);
2465 }
2466 else if (SCM_REALP (y))
2467 return scm_i_inexact_truncate_remainder
2468 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
2469 else if (SCM_FRACTIONP (y))
2470 return scm_i_exact_rational_truncate_remainder (x, y);
2471 else
2472 SCM_WTA_DISPATCH_2 (g_scm_truncate_remainder, x, y, SCM_ARG2,
2473 s_scm_truncate_remainder);
2474 }
2475 else if (SCM_REALP (x))
2476 {
2477 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
2478 SCM_BIGP (y) || SCM_FRACTIONP (y))
2479 return scm_i_inexact_truncate_remainder
2480 (SCM_REAL_VALUE (x), scm_to_double (y));
2481 else
2482 SCM_WTA_DISPATCH_2 (g_scm_truncate_remainder, x, y, SCM_ARG2,
2483 s_scm_truncate_remainder);
2484 }
2485 else if (SCM_FRACTIONP (x))
2486 {
2487 if (SCM_REALP (y))
2488 return scm_i_inexact_truncate_remainder
2489 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
2490 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
2491 return scm_i_exact_rational_truncate_remainder (x, y);
2492 else
2493 SCM_WTA_DISPATCH_2 (g_scm_truncate_remainder, x, y, SCM_ARG2,
2494 s_scm_truncate_remainder);
2495 }
2496 else
2497 SCM_WTA_DISPATCH_2 (g_scm_truncate_remainder, x, y, SCM_ARG1,
2498 s_scm_truncate_remainder);
2499 }
2500 #undef FUNC_NAME
2501
2502 static SCM
2503 scm_i_inexact_truncate_remainder (double x, double y)
2504 {
2505 /* Although it would be more efficient to use fmod here, we can't
2506 because it would in some cases produce results inconsistent with
2507 scm_i_inexact_truncate_quotient, such that x != q * y + r (not even
2508 close). In particular, when x is very close to a multiple of y,
2509 then r might be either 0.0 or sgn(x)*|y|, but those two cases must
2510 correspond to different choices of q. If quotient chooses one and
2511 remainder chooses the other, it would be bad. */
2512 if (SCM_UNLIKELY (y == 0))
2513 scm_num_overflow (s_scm_truncate_remainder); /* or return a NaN? */
2514 else
2515 return scm_from_double (x - y * trunc (x / y));
2516 }
2517
2518 static SCM
2519 scm_i_exact_rational_truncate_remainder (SCM x, SCM y)
2520 {
2521 SCM xd = scm_denominator (x);
2522 SCM yd = scm_denominator (y);
2523 SCM r1 = scm_truncate_remainder (scm_product (scm_numerator (x), yd),
2524 scm_product (scm_numerator (y), xd));
2525 return scm_divide (r1, scm_product (xd, yd));
2526 }
2527
2528
2529 static void scm_i_inexact_truncate_divide (double x, double y,
2530 SCM *qp, SCM *rp);
2531 static void scm_i_exact_rational_truncate_divide (SCM x, SCM y,
2532 SCM *qp, SCM *rp);
2533
2534 SCM_PRIMITIVE_GENERIC (scm_i_truncate_divide, "truncate/", 2, 0, 0,
2535 (SCM x, SCM y),
2536 "Return the integer @var{q} and the real number @var{r}\n"
2537 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
2538 "and @math{@var{q} = truncate(@var{x} / @var{y})}.\n"
2539 "@lisp\n"
2540 "(truncate/ 123 10) @result{} 12 and 3\n"
2541 "(truncate/ 123 -10) @result{} -12 and 3\n"
2542 "(truncate/ -123 10) @result{} -12 and -3\n"
2543 "(truncate/ -123 -10) @result{} 12 and -3\n"
2544 "(truncate/ -123.2 -63.5) @result{} 1.0 and -59.7\n"
2545 "(truncate/ 16/3 -10/7) @result{} -3 and 22/21\n"
2546 "@end lisp")
2547 #define FUNC_NAME s_scm_i_truncate_divide
2548 {
2549 SCM q, r;
2550
2551 scm_truncate_divide(x, y, &q, &r);
2552 return scm_values (scm_list_2 (q, r));
2553 }
2554 #undef FUNC_NAME
2555
2556 #define s_scm_truncate_divide s_scm_i_truncate_divide
2557 #define g_scm_truncate_divide g_scm_i_truncate_divide
2558
2559 void
2560 scm_truncate_divide (SCM x, SCM y, SCM *qp, SCM *rp)
2561 {
2562 if (SCM_LIKELY (SCM_I_INUMP (x)))
2563 {
2564 scm_t_inum xx = SCM_I_INUM (x);
2565 if (SCM_LIKELY (SCM_I_INUMP (y)))
2566 {
2567 scm_t_inum yy = SCM_I_INUM (y);
2568 if (SCM_UNLIKELY (yy == 0))
2569 scm_num_overflow (s_scm_truncate_divide);
2570 else
2571 {
2572 scm_t_inum qq = xx / yy;
2573 scm_t_inum rr = xx % yy;
2574 if (SCM_LIKELY (SCM_FIXABLE (qq)))
2575 *qp = SCM_I_MAKINUM (qq);
2576 else
2577 *qp = scm_i_inum2big (qq);
2578 *rp = SCM_I_MAKINUM (rr);
2579 }
2580 return;
2581 }
2582 else if (SCM_BIGP (y))
2583 {
2584 if (SCM_UNLIKELY (xx == SCM_MOST_NEGATIVE_FIXNUM)
2585 && SCM_UNLIKELY (mpz_cmp_ui (SCM_I_BIG_MPZ (y),
2586 - SCM_MOST_NEGATIVE_FIXNUM) == 0))
2587 {
2588 /* Special case: x == fixnum-min && y == abs (fixnum-min) */
2589 scm_remember_upto_here_1 (y);
2590 *qp = SCM_I_MAKINUM (-1);
2591 *rp = SCM_INUM0;
2592 }
2593 else
2594 {
2595 *qp = SCM_INUM0;
2596 *rp = x;
2597 }
2598 return;
2599 }
2600 else if (SCM_REALP (y))
2601 return scm_i_inexact_truncate_divide (xx, SCM_REAL_VALUE (y), qp, rp);
2602 else if (SCM_FRACTIONP (y))
2603 return scm_i_exact_rational_truncate_divide (x, y, qp, rp);
2604 else
2605 return two_valued_wta_dispatch_2
2606 (g_scm_truncate_divide, x, y, SCM_ARG2,
2607 s_scm_truncate_divide, qp, rp);
2608 }
2609 else if (SCM_BIGP (x))
2610 {
2611 if (SCM_LIKELY (SCM_I_INUMP (y)))
2612 {
2613 scm_t_inum yy = SCM_I_INUM (y);
2614 if (SCM_UNLIKELY (yy == 0))
2615 scm_num_overflow (s_scm_truncate_divide);
2616 else
2617 {
2618 SCM q = scm_i_mkbig ();
2619 scm_t_inum rr;
2620 if (yy > 0)
2621 rr = mpz_tdiv_q_ui (SCM_I_BIG_MPZ (q),
2622 SCM_I_BIG_MPZ (x), yy);
2623 else
2624 {
2625 rr = mpz_tdiv_q_ui (SCM_I_BIG_MPZ (q),
2626 SCM_I_BIG_MPZ (x), -yy);
2627 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
2628 }
2629 rr *= mpz_sgn (SCM_I_BIG_MPZ (x));
2630 scm_remember_upto_here_1 (x);
2631 *qp = scm_i_normbig (q);
2632 *rp = SCM_I_MAKINUM (rr);
2633 }
2634 return;
2635 }
2636 else if (SCM_BIGP (y))
2637 {
2638 SCM q = scm_i_mkbig ();
2639 SCM r = scm_i_mkbig ();
2640 mpz_tdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2641 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
2642 scm_remember_upto_here_2 (x, y);
2643 *qp = scm_i_normbig (q);
2644 *rp = scm_i_normbig (r);
2645 }
2646 else if (SCM_REALP (y))
2647 return scm_i_inexact_truncate_divide
2648 (scm_i_big2dbl (x), SCM_REAL_VALUE (y), qp, rp);
2649 else if (SCM_FRACTIONP (y))
2650 return scm_i_exact_rational_truncate_divide (x, y, qp, rp);
2651 else
2652 return two_valued_wta_dispatch_2
2653 (g_scm_truncate_divide, x, y, SCM_ARG2,
2654 s_scm_truncate_divide, qp, rp);
2655 }
2656 else if (SCM_REALP (x))
2657 {
2658 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
2659 SCM_BIGP (y) || SCM_FRACTIONP (y))
2660 return scm_i_inexact_truncate_divide
2661 (SCM_REAL_VALUE (x), scm_to_double (y), qp, rp);
2662 else
2663 return two_valued_wta_dispatch_2
2664 (g_scm_truncate_divide, x, y, SCM_ARG2,
2665 s_scm_truncate_divide, qp, rp);
2666 }
2667 else if (SCM_FRACTIONP (x))
2668 {
2669 if (SCM_REALP (y))
2670 return scm_i_inexact_truncate_divide
2671 (scm_i_fraction2double (x), SCM_REAL_VALUE (y), qp, rp);
2672 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
2673 return scm_i_exact_rational_truncate_divide (x, y, qp, rp);
2674 else
2675 return two_valued_wta_dispatch_2
2676 (g_scm_truncate_divide, x, y, SCM_ARG2,
2677 s_scm_truncate_divide, qp, rp);
2678 }
2679 else
2680 return two_valued_wta_dispatch_2 (g_scm_truncate_divide, x, y, SCM_ARG1,
2681 s_scm_truncate_divide, qp, rp);
2682 }
2683
2684 static void
2685 scm_i_inexact_truncate_divide (double x, double y, SCM *qp, SCM *rp)
2686 {
2687 if (SCM_UNLIKELY (y == 0))
2688 scm_num_overflow (s_scm_truncate_divide); /* or return a NaN? */
2689 else
2690 {
2691 double q = trunc (x / y);
2692 double r = x - q * y;
2693 *qp = scm_from_double (q);
2694 *rp = scm_from_double (r);
2695 }
2696 }
2697
2698 static void
2699 scm_i_exact_rational_truncate_divide (SCM x, SCM y, SCM *qp, SCM *rp)
2700 {
2701 SCM r1;
2702 SCM xd = scm_denominator (x);
2703 SCM yd = scm_denominator (y);
2704
2705 scm_truncate_divide (scm_product (scm_numerator (x), yd),
2706 scm_product (scm_numerator (y), xd),
2707 qp, &r1);
2708 *rp = scm_divide (r1, scm_product (xd, yd));
2709 }
2710
2711 static SCM scm_i_inexact_centered_quotient (double x, double y);
2712 static SCM scm_i_bigint_centered_quotient (SCM x, SCM y);
2713 static SCM scm_i_exact_rational_centered_quotient (SCM x, SCM y);
2714
2715 SCM_PRIMITIVE_GENERIC (scm_centered_quotient, "centered-quotient", 2, 0, 0,
2716 (SCM x, SCM y),
2717 "Return the integer @var{q} such that\n"
2718 "@math{@var{x} = @var{q}*@var{y} + @var{r}} where\n"
2719 "@math{-abs(@var{y}/2) <= @var{r} < abs(@var{y}/2)}.\n"
2720 "@lisp\n"
2721 "(centered-quotient 123 10) @result{} 12\n"
2722 "(centered-quotient 123 -10) @result{} -12\n"
2723 "(centered-quotient -123 10) @result{} -12\n"
2724 "(centered-quotient -123 -10) @result{} 12\n"
2725 "(centered-quotient -123.2 -63.5) @result{} 2.0\n"
2726 "(centered-quotient 16/3 -10/7) @result{} -4\n"
2727 "@end lisp")
2728 #define FUNC_NAME s_scm_centered_quotient
2729 {
2730 if (SCM_LIKELY (SCM_I_INUMP (x)))
2731 {
2732 scm_t_inum xx = SCM_I_INUM (x);
2733 if (SCM_LIKELY (SCM_I_INUMP (y)))
2734 {
2735 scm_t_inum yy = SCM_I_INUM (y);
2736 if (SCM_UNLIKELY (yy == 0))
2737 scm_num_overflow (s_scm_centered_quotient);
2738 else
2739 {
2740 scm_t_inum qq = xx / yy;
2741 scm_t_inum rr = xx % yy;
2742 if (SCM_LIKELY (xx > 0))
2743 {
2744 if (SCM_LIKELY (yy > 0))
2745 {
2746 if (rr >= (yy + 1) / 2)
2747 qq++;
2748 }
2749 else
2750 {
2751 if (rr >= (1 - yy) / 2)
2752 qq--;
2753 }
2754 }
2755 else
2756 {
2757 if (SCM_LIKELY (yy > 0))
2758 {
2759 if (rr < -yy / 2)
2760 qq--;
2761 }
2762 else
2763 {
2764 if (rr < yy / 2)
2765 qq++;
2766 }
2767 }
2768 if (SCM_LIKELY (SCM_FIXABLE (qq)))
2769 return SCM_I_MAKINUM (qq);
2770 else
2771 return scm_i_inum2big (qq);
2772 }
2773 }
2774 else if (SCM_BIGP (y))
2775 {
2776 /* Pass a denormalized bignum version of x (even though it
2777 can fit in a fixnum) to scm_i_bigint_centered_quotient */
2778 return scm_i_bigint_centered_quotient (scm_i_long2big (xx), y);
2779 }
2780 else if (SCM_REALP (y))
2781 return scm_i_inexact_centered_quotient (xx, SCM_REAL_VALUE (y));
2782 else if (SCM_FRACTIONP (y))
2783 return scm_i_exact_rational_centered_quotient (x, y);
2784 else
2785 SCM_WTA_DISPATCH_2 (g_scm_centered_quotient, x, y, SCM_ARG2,
2786 s_scm_centered_quotient);
2787 }
2788 else if (SCM_BIGP (x))
2789 {
2790 if (SCM_LIKELY (SCM_I_INUMP (y)))
2791 {
2792 scm_t_inum yy = SCM_I_INUM (y);
2793 if (SCM_UNLIKELY (yy == 0))
2794 scm_num_overflow (s_scm_centered_quotient);
2795 else if (SCM_UNLIKELY (yy == 1))
2796 return x;
2797 else
2798 {
2799 SCM q = scm_i_mkbig ();
2800 scm_t_inum rr;
2801 /* Arrange for rr to initially be non-positive,
2802 because that simplifies the test to see
2803 if it is within the needed bounds. */
2804 if (yy > 0)
2805 {
2806 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
2807 SCM_I_BIG_MPZ (x), yy);
2808 scm_remember_upto_here_1 (x);
2809 if (rr < -yy / 2)
2810 mpz_sub_ui (SCM_I_BIG_MPZ (q),
2811 SCM_I_BIG_MPZ (q), 1);
2812 }
2813 else
2814 {
2815 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
2816 SCM_I_BIG_MPZ (x), -yy);
2817 scm_remember_upto_here_1 (x);
2818 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
2819 if (rr < yy / 2)
2820 mpz_add_ui (SCM_I_BIG_MPZ (q),
2821 SCM_I_BIG_MPZ (q), 1);
2822 }
2823 return scm_i_normbig (q);
2824 }
2825 }
2826 else if (SCM_BIGP (y))
2827 return scm_i_bigint_centered_quotient (x, y);
2828 else if (SCM_REALP (y))
2829 return scm_i_inexact_centered_quotient
2830 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
2831 else if (SCM_FRACTIONP (y))
2832 return scm_i_exact_rational_centered_quotient (x, y);
2833 else
2834 SCM_WTA_DISPATCH_2 (g_scm_centered_quotient, x, y, SCM_ARG2,
2835 s_scm_centered_quotient);
2836 }
2837 else if (SCM_REALP (x))
2838 {
2839 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
2840 SCM_BIGP (y) || SCM_FRACTIONP (y))
2841 return scm_i_inexact_centered_quotient
2842 (SCM_REAL_VALUE (x), scm_to_double (y));
2843 else
2844 SCM_WTA_DISPATCH_2 (g_scm_centered_quotient, x, y, SCM_ARG2,
2845 s_scm_centered_quotient);
2846 }
2847 else if (SCM_FRACTIONP (x))
2848 {
2849 if (SCM_REALP (y))
2850 return scm_i_inexact_centered_quotient
2851 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
2852 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
2853 return scm_i_exact_rational_centered_quotient (x, y);
2854 else
2855 SCM_WTA_DISPATCH_2 (g_scm_centered_quotient, x, y, SCM_ARG2,
2856 s_scm_centered_quotient);
2857 }
2858 else
2859 SCM_WTA_DISPATCH_2 (g_scm_centered_quotient, x, y, SCM_ARG1,
2860 s_scm_centered_quotient);
2861 }
2862 #undef FUNC_NAME
2863
2864 static SCM
2865 scm_i_inexact_centered_quotient (double x, double y)
2866 {
2867 if (SCM_LIKELY (y > 0))
2868 return scm_from_double (floor (x/y + 0.5));
2869 else if (SCM_LIKELY (y < 0))
2870 return scm_from_double (ceil (x/y - 0.5));
2871 else if (y == 0)
2872 scm_num_overflow (s_scm_centered_quotient); /* or return a NaN? */
2873 else
2874 return scm_nan ();
2875 }
2876
2877 /* Assumes that both x and y are bigints, though
2878 x might be able to fit into a fixnum. */
2879 static SCM
2880 scm_i_bigint_centered_quotient (SCM x, SCM y)
2881 {
2882 SCM q, r, min_r;
2883
2884 /* Note that x might be small enough to fit into a
2885 fixnum, so we must not let it escape into the wild */
2886 q = scm_i_mkbig ();
2887 r = scm_i_mkbig ();
2888
2889 /* min_r will eventually become -abs(y)/2 */
2890 min_r = scm_i_mkbig ();
2891 mpz_tdiv_q_2exp (SCM_I_BIG_MPZ (min_r),
2892 SCM_I_BIG_MPZ (y), 1);
2893
2894 /* Arrange for rr to initially be non-positive,
2895 because that simplifies the test to see
2896 if it is within the needed bounds. */
2897 if (mpz_sgn (SCM_I_BIG_MPZ (y)) > 0)
2898 {
2899 mpz_cdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2900 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
2901 scm_remember_upto_here_2 (x, y);
2902 mpz_neg (SCM_I_BIG_MPZ (min_r), SCM_I_BIG_MPZ (min_r));
2903 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
2904 mpz_sub_ui (SCM_I_BIG_MPZ (q),
2905 SCM_I_BIG_MPZ (q), 1);
2906 }
2907 else
2908 {
2909 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
2910 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
2911 scm_remember_upto_here_2 (x, y);
2912 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
2913 mpz_add_ui (SCM_I_BIG_MPZ (q),
2914 SCM_I_BIG_MPZ (q), 1);
2915 }
2916 scm_remember_upto_here_2 (r, min_r);
2917 return scm_i_normbig (q);
2918 }
2919
2920 static SCM
2921 scm_i_exact_rational_centered_quotient (SCM x, SCM y)
2922 {
2923 return scm_centered_quotient
2924 (scm_product (scm_numerator (x), scm_denominator (y)),
2925 scm_product (scm_numerator (y), scm_denominator (x)));
2926 }
2927
2928 static SCM scm_i_inexact_centered_remainder (double x, double y);
2929 static SCM scm_i_bigint_centered_remainder (SCM x, SCM y);
2930 static SCM scm_i_exact_rational_centered_remainder (SCM x, SCM y);
2931
2932 SCM_PRIMITIVE_GENERIC (scm_centered_remainder, "centered-remainder", 2, 0, 0,
2933 (SCM x, SCM y),
2934 "Return the real number @var{r} such that\n"
2935 "@math{-abs(@var{y}/2) <= @var{r} < abs(@var{y}/2)}\n"
2936 "and @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
2937 "for some integer @var{q}.\n"
2938 "@lisp\n"
2939 "(centered-remainder 123 10) @result{} 3\n"
2940 "(centered-remainder 123 -10) @result{} 3\n"
2941 "(centered-remainder -123 10) @result{} -3\n"
2942 "(centered-remainder -123 -10) @result{} -3\n"
2943 "(centered-remainder -123.2 -63.5) @result{} 3.8\n"
2944 "(centered-remainder 16/3 -10/7) @result{} -8/21\n"
2945 "@end lisp")
2946 #define FUNC_NAME s_scm_centered_remainder
2947 {
2948 if (SCM_LIKELY (SCM_I_INUMP (x)))
2949 {
2950 scm_t_inum xx = SCM_I_INUM (x);
2951 if (SCM_LIKELY (SCM_I_INUMP (y)))
2952 {
2953 scm_t_inum yy = SCM_I_INUM (y);
2954 if (SCM_UNLIKELY (yy == 0))
2955 scm_num_overflow (s_scm_centered_remainder);
2956 else
2957 {
2958 scm_t_inum rr = xx % yy;
2959 if (SCM_LIKELY (xx > 0))
2960 {
2961 if (SCM_LIKELY (yy > 0))
2962 {
2963 if (rr >= (yy + 1) / 2)
2964 rr -= yy;
2965 }
2966 else
2967 {
2968 if (rr >= (1 - yy) / 2)
2969 rr += yy;
2970 }
2971 }
2972 else
2973 {
2974 if (SCM_LIKELY (yy > 0))
2975 {
2976 if (rr < -yy / 2)
2977 rr += yy;
2978 }
2979 else
2980 {
2981 if (rr < yy / 2)
2982 rr -= yy;
2983 }
2984 }
2985 return SCM_I_MAKINUM (rr);
2986 }
2987 }
2988 else if (SCM_BIGP (y))
2989 {
2990 /* Pass a denormalized bignum version of x (even though it
2991 can fit in a fixnum) to scm_i_bigint_centered_remainder */
2992 return scm_i_bigint_centered_remainder (scm_i_long2big (xx), y);
2993 }
2994 else if (SCM_REALP (y))
2995 return scm_i_inexact_centered_remainder (xx, SCM_REAL_VALUE (y));
2996 else if (SCM_FRACTIONP (y))
2997 return scm_i_exact_rational_centered_remainder (x, y);
2998 else
2999 SCM_WTA_DISPATCH_2 (g_scm_centered_remainder, x, y, SCM_ARG2,
3000 s_scm_centered_remainder);
3001 }
3002 else if (SCM_BIGP (x))
3003 {
3004 if (SCM_LIKELY (SCM_I_INUMP (y)))
3005 {
3006 scm_t_inum yy = SCM_I_INUM (y);
3007 if (SCM_UNLIKELY (yy == 0))
3008 scm_num_overflow (s_scm_centered_remainder);
3009 else
3010 {
3011 scm_t_inum rr;
3012 /* Arrange for rr to initially be non-positive,
3013 because that simplifies the test to see
3014 if it is within the needed bounds. */
3015 if (yy > 0)
3016 {
3017 rr = - mpz_cdiv_ui (SCM_I_BIG_MPZ (x), yy);
3018 scm_remember_upto_here_1 (x);
3019 if (rr < -yy / 2)
3020 rr += yy;
3021 }
3022 else
3023 {
3024 rr = - mpz_cdiv_ui (SCM_I_BIG_MPZ (x), -yy);
3025 scm_remember_upto_here_1 (x);
3026 if (rr < yy / 2)
3027 rr -= yy;
3028 }
3029 return SCM_I_MAKINUM (rr);
3030 }
3031 }
3032 else if (SCM_BIGP (y))
3033 return scm_i_bigint_centered_remainder (x, y);
3034 else if (SCM_REALP (y))
3035 return scm_i_inexact_centered_remainder
3036 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
3037 else if (SCM_FRACTIONP (y))
3038 return scm_i_exact_rational_centered_remainder (x, y);
3039 else
3040 SCM_WTA_DISPATCH_2 (g_scm_centered_remainder, x, y, SCM_ARG2,
3041 s_scm_centered_remainder);
3042 }
3043 else if (SCM_REALP (x))
3044 {
3045 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
3046 SCM_BIGP (y) || SCM_FRACTIONP (y))
3047 return scm_i_inexact_centered_remainder
3048 (SCM_REAL_VALUE (x), scm_to_double (y));
3049 else
3050 SCM_WTA_DISPATCH_2 (g_scm_centered_remainder, x, y, SCM_ARG2,
3051 s_scm_centered_remainder);
3052 }
3053 else if (SCM_FRACTIONP (x))
3054 {
3055 if (SCM_REALP (y))
3056 return scm_i_inexact_centered_remainder
3057 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
3058 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
3059 return scm_i_exact_rational_centered_remainder (x, y);
3060 else
3061 SCM_WTA_DISPATCH_2 (g_scm_centered_remainder, x, y, SCM_ARG2,
3062 s_scm_centered_remainder);
3063 }
3064 else
3065 SCM_WTA_DISPATCH_2 (g_scm_centered_remainder, x, y, SCM_ARG1,
3066 s_scm_centered_remainder);
3067 }
3068 #undef FUNC_NAME
3069
3070 static SCM
3071 scm_i_inexact_centered_remainder (double x, double y)
3072 {
3073 double q;
3074
3075 /* Although it would be more efficient to use fmod here, we can't
3076 because it would in some cases produce results inconsistent with
3077 scm_i_inexact_centered_quotient, such that x != r + q * y (not even
3078 close). In particular, when x-y/2 is very close to a multiple of
3079 y, then r might be either -abs(y/2) or abs(y/2)-epsilon, but those
3080 two cases must correspond to different choices of q. If quotient
3081 chooses one and remainder chooses the other, it would be bad. */
3082 if (SCM_LIKELY (y > 0))
3083 q = floor (x/y + 0.5);
3084 else if (SCM_LIKELY (y < 0))
3085 q = ceil (x/y - 0.5);
3086 else if (y == 0)
3087 scm_num_overflow (s_scm_centered_remainder); /* or return a NaN? */
3088 else
3089 return scm_nan ();
3090 return scm_from_double (x - q * y);
3091 }
3092
3093 /* Assumes that both x and y are bigints, though
3094 x might be able to fit into a fixnum. */
3095 static SCM
3096 scm_i_bigint_centered_remainder (SCM x, SCM y)
3097 {
3098 SCM r, min_r;
3099
3100 /* Note that x might be small enough to fit into a
3101 fixnum, so we must not let it escape into the wild */
3102 r = scm_i_mkbig ();
3103
3104 /* min_r will eventually become -abs(y)/2 */
3105 min_r = scm_i_mkbig ();
3106 mpz_tdiv_q_2exp (SCM_I_BIG_MPZ (min_r),
3107 SCM_I_BIG_MPZ (y), 1);
3108
3109 /* Arrange for rr to initially be non-positive,
3110 because that simplifies the test to see
3111 if it is within the needed bounds. */
3112 if (mpz_sgn (SCM_I_BIG_MPZ (y)) > 0)
3113 {
3114 mpz_cdiv_r (SCM_I_BIG_MPZ (r),
3115 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3116 mpz_neg (SCM_I_BIG_MPZ (min_r), SCM_I_BIG_MPZ (min_r));
3117 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
3118 mpz_add (SCM_I_BIG_MPZ (r),
3119 SCM_I_BIG_MPZ (r),
3120 SCM_I_BIG_MPZ (y));
3121 }
3122 else
3123 {
3124 mpz_fdiv_r (SCM_I_BIG_MPZ (r),
3125 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3126 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
3127 mpz_sub (SCM_I_BIG_MPZ (r),
3128 SCM_I_BIG_MPZ (r),
3129 SCM_I_BIG_MPZ (y));
3130 }
3131 scm_remember_upto_here_2 (x, y);
3132 return scm_i_normbig (r);
3133 }
3134
3135 static SCM
3136 scm_i_exact_rational_centered_remainder (SCM x, SCM y)
3137 {
3138 SCM xd = scm_denominator (x);
3139 SCM yd = scm_denominator (y);
3140 SCM r1 = scm_centered_remainder (scm_product (scm_numerator (x), yd),
3141 scm_product (scm_numerator (y), xd));
3142 return scm_divide (r1, scm_product (xd, yd));
3143 }
3144
3145
3146 static void scm_i_inexact_centered_divide (double x, double y,
3147 SCM *qp, SCM *rp);
3148 static void scm_i_bigint_centered_divide (SCM x, SCM y, SCM *qp, SCM *rp);
3149 static void scm_i_exact_rational_centered_divide (SCM x, SCM y,
3150 SCM *qp, SCM *rp);
3151
3152 SCM_PRIMITIVE_GENERIC (scm_i_centered_divide, "centered/", 2, 0, 0,
3153 (SCM x, SCM y),
3154 "Return the integer @var{q} and the real number @var{r}\n"
3155 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
3156 "and @math{-abs(@var{y}/2) <= @var{r} < abs(@var{y}/2)}.\n"
3157 "@lisp\n"
3158 "(centered/ 123 10) @result{} 12 and 3\n"
3159 "(centered/ 123 -10) @result{} -12 and 3\n"
3160 "(centered/ -123 10) @result{} -12 and -3\n"
3161 "(centered/ -123 -10) @result{} 12 and -3\n"
3162 "(centered/ -123.2 -63.5) @result{} 2.0 and 3.8\n"
3163 "(centered/ 16/3 -10/7) @result{} -4 and -8/21\n"
3164 "@end lisp")
3165 #define FUNC_NAME s_scm_i_centered_divide
3166 {
3167 SCM q, r;
3168
3169 scm_centered_divide(x, y, &q, &r);
3170 return scm_values (scm_list_2 (q, r));
3171 }
3172 #undef FUNC_NAME
3173
3174 #define s_scm_centered_divide s_scm_i_centered_divide
3175 #define g_scm_centered_divide g_scm_i_centered_divide
3176
3177 void
3178 scm_centered_divide (SCM x, SCM y, SCM *qp, SCM *rp)
3179 {
3180 if (SCM_LIKELY (SCM_I_INUMP (x)))
3181 {
3182 scm_t_inum xx = SCM_I_INUM (x);
3183 if (SCM_LIKELY (SCM_I_INUMP (y)))
3184 {
3185 scm_t_inum yy = SCM_I_INUM (y);
3186 if (SCM_UNLIKELY (yy == 0))
3187 scm_num_overflow (s_scm_centered_divide);
3188 else
3189 {
3190 scm_t_inum qq = xx / yy;
3191 scm_t_inum rr = xx % yy;
3192 if (SCM_LIKELY (xx > 0))
3193 {
3194 if (SCM_LIKELY (yy > 0))
3195 {
3196 if (rr >= (yy + 1) / 2)
3197 { qq++; rr -= yy; }
3198 }
3199 else
3200 {
3201 if (rr >= (1 - yy) / 2)
3202 { qq--; rr += yy; }
3203 }
3204 }
3205 else
3206 {
3207 if (SCM_LIKELY (yy > 0))
3208 {
3209 if (rr < -yy / 2)
3210 { qq--; rr += yy; }
3211 }
3212 else
3213 {
3214 if (rr < yy / 2)
3215 { qq++; rr -= yy; }
3216 }
3217 }
3218 if (SCM_LIKELY (SCM_FIXABLE (qq)))
3219 *qp = SCM_I_MAKINUM (qq);
3220 else
3221 *qp = scm_i_inum2big (qq);
3222 *rp = SCM_I_MAKINUM (rr);
3223 }
3224 return;
3225 }
3226 else if (SCM_BIGP (y))
3227 {
3228 /* Pass a denormalized bignum version of x (even though it
3229 can fit in a fixnum) to scm_i_bigint_centered_divide */
3230 return scm_i_bigint_centered_divide (scm_i_long2big (xx), y, qp, rp);
3231 }
3232 else if (SCM_REALP (y))
3233 return scm_i_inexact_centered_divide (xx, SCM_REAL_VALUE (y), qp, rp);
3234 else if (SCM_FRACTIONP (y))
3235 return scm_i_exact_rational_centered_divide (x, y, qp, rp);
3236 else
3237 return two_valued_wta_dispatch_2
3238 (g_scm_centered_divide, x, y, SCM_ARG2,
3239 s_scm_centered_divide, qp, rp);
3240 }
3241 else if (SCM_BIGP (x))
3242 {
3243 if (SCM_LIKELY (SCM_I_INUMP (y)))
3244 {
3245 scm_t_inum yy = SCM_I_INUM (y);
3246 if (SCM_UNLIKELY (yy == 0))
3247 scm_num_overflow (s_scm_centered_divide);
3248 else
3249 {
3250 SCM q = scm_i_mkbig ();
3251 scm_t_inum rr;
3252 /* Arrange for rr to initially be non-positive,
3253 because that simplifies the test to see
3254 if it is within the needed bounds. */
3255 if (yy > 0)
3256 {
3257 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
3258 SCM_I_BIG_MPZ (x), yy);
3259 scm_remember_upto_here_1 (x);
3260 if (rr < -yy / 2)
3261 {
3262 mpz_sub_ui (SCM_I_BIG_MPZ (q),
3263 SCM_I_BIG_MPZ (q), 1);
3264 rr += yy;
3265 }
3266 }
3267 else
3268 {
3269 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
3270 SCM_I_BIG_MPZ (x), -yy);
3271 scm_remember_upto_here_1 (x);
3272 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
3273 if (rr < yy / 2)
3274 {
3275 mpz_add_ui (SCM_I_BIG_MPZ (q),
3276 SCM_I_BIG_MPZ (q), 1);
3277 rr -= yy;
3278 }
3279 }
3280 *qp = scm_i_normbig (q);
3281 *rp = SCM_I_MAKINUM (rr);
3282 }
3283 return;
3284 }
3285 else if (SCM_BIGP (y))
3286 return scm_i_bigint_centered_divide (x, y, qp, rp);
3287 else if (SCM_REALP (y))
3288 return scm_i_inexact_centered_divide
3289 (scm_i_big2dbl (x), SCM_REAL_VALUE (y), qp, rp);
3290 else if (SCM_FRACTIONP (y))
3291 return scm_i_exact_rational_centered_divide (x, y, qp, rp);
3292 else
3293 return two_valued_wta_dispatch_2
3294 (g_scm_centered_divide, x, y, SCM_ARG2,
3295 s_scm_centered_divide, qp, rp);
3296 }
3297 else if (SCM_REALP (x))
3298 {
3299 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
3300 SCM_BIGP (y) || SCM_FRACTIONP (y))
3301 return scm_i_inexact_centered_divide
3302 (SCM_REAL_VALUE (x), scm_to_double (y), qp, rp);
3303 else
3304 return two_valued_wta_dispatch_2
3305 (g_scm_centered_divide, x, y, SCM_ARG2,
3306 s_scm_centered_divide, qp, rp);
3307 }
3308 else if (SCM_FRACTIONP (x))
3309 {
3310 if (SCM_REALP (y))
3311 return scm_i_inexact_centered_divide
3312 (scm_i_fraction2double (x), SCM_REAL_VALUE (y), qp, rp);
3313 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
3314 return scm_i_exact_rational_centered_divide (x, y, qp, rp);
3315 else
3316 return two_valued_wta_dispatch_2
3317 (g_scm_centered_divide, x, y, SCM_ARG2,
3318 s_scm_centered_divide, qp, rp);
3319 }
3320 else
3321 return two_valued_wta_dispatch_2 (g_scm_centered_divide, x, y, SCM_ARG1,
3322 s_scm_centered_divide, qp, rp);
3323 }
3324
3325 static void
3326 scm_i_inexact_centered_divide (double x, double y, SCM *qp, SCM *rp)
3327 {
3328 double q, r;
3329
3330 if (SCM_LIKELY (y > 0))
3331 q = floor (x/y + 0.5);
3332 else if (SCM_LIKELY (y < 0))
3333 q = ceil (x/y - 0.5);
3334 else if (y == 0)
3335 scm_num_overflow (s_scm_centered_divide); /* or return a NaN? */
3336 else
3337 q = guile_NaN;
3338 r = x - q * y;
3339 *qp = scm_from_double (q);
3340 *rp = scm_from_double (r);
3341 }
3342
3343 /* Assumes that both x and y are bigints, though
3344 x might be able to fit into a fixnum. */
3345 static void
3346 scm_i_bigint_centered_divide (SCM x, SCM y, SCM *qp, SCM *rp)
3347 {
3348 SCM q, r, min_r;
3349
3350 /* Note that x might be small enough to fit into a
3351 fixnum, so we must not let it escape into the wild */
3352 q = scm_i_mkbig ();
3353 r = scm_i_mkbig ();
3354
3355 /* min_r will eventually become -abs(y/2) */
3356 min_r = scm_i_mkbig ();
3357 mpz_tdiv_q_2exp (SCM_I_BIG_MPZ (min_r),
3358 SCM_I_BIG_MPZ (y), 1);
3359
3360 /* Arrange for rr to initially be non-positive,
3361 because that simplifies the test to see
3362 if it is within the needed bounds. */
3363 if (mpz_sgn (SCM_I_BIG_MPZ (y)) > 0)
3364 {
3365 mpz_cdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
3366 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3367 mpz_neg (SCM_I_BIG_MPZ (min_r), SCM_I_BIG_MPZ (min_r));
3368 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
3369 {
3370 mpz_sub_ui (SCM_I_BIG_MPZ (q),
3371 SCM_I_BIG_MPZ (q), 1);
3372 mpz_add (SCM_I_BIG_MPZ (r),
3373 SCM_I_BIG_MPZ (r),
3374 SCM_I_BIG_MPZ (y));
3375 }
3376 }
3377 else
3378 {
3379 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
3380 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3381 if (mpz_cmp (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (min_r)) < 0)
3382 {
3383 mpz_add_ui (SCM_I_BIG_MPZ (q),
3384 SCM_I_BIG_MPZ (q), 1);
3385 mpz_sub (SCM_I_BIG_MPZ (r),
3386 SCM_I_BIG_MPZ (r),
3387 SCM_I_BIG_MPZ (y));
3388 }
3389 }
3390 scm_remember_upto_here_2 (x, y);
3391 *qp = scm_i_normbig (q);
3392 *rp = scm_i_normbig (r);
3393 }
3394
3395 static void
3396 scm_i_exact_rational_centered_divide (SCM x, SCM y, SCM *qp, SCM *rp)
3397 {
3398 SCM r1;
3399 SCM xd = scm_denominator (x);
3400 SCM yd = scm_denominator (y);
3401
3402 scm_centered_divide (scm_product (scm_numerator (x), yd),
3403 scm_product (scm_numerator (y), xd),
3404 qp, &r1);
3405 *rp = scm_divide (r1, scm_product (xd, yd));
3406 }
3407
3408 static SCM scm_i_inexact_round_quotient (double x, double y);
3409 static SCM scm_i_bigint_round_quotient (SCM x, SCM y);
3410 static SCM scm_i_exact_rational_round_quotient (SCM x, SCM y);
3411
3412 SCM_PRIMITIVE_GENERIC (scm_round_quotient, "round-quotient", 2, 0, 0,
3413 (SCM x, SCM y),
3414 "Return @math{@var{x} / @var{y}} to the nearest integer,\n"
3415 "with ties going to the nearest even integer.\n"
3416 "@lisp\n"
3417 "(round-quotient 123 10) @result{} 12\n"
3418 "(round-quotient 123 -10) @result{} -12\n"
3419 "(round-quotient -123 10) @result{} -12\n"
3420 "(round-quotient -123 -10) @result{} 12\n"
3421 "(round-quotient 125 10) @result{} 12\n"
3422 "(round-quotient 127 10) @result{} 13\n"
3423 "(round-quotient 135 10) @result{} 14\n"
3424 "(round-quotient -123.2 -63.5) @result{} 2.0\n"
3425 "(round-quotient 16/3 -10/7) @result{} -4\n"
3426 "@end lisp")
3427 #define FUNC_NAME s_scm_round_quotient
3428 {
3429 if (SCM_LIKELY (SCM_I_INUMP (x)))
3430 {
3431 scm_t_inum xx = SCM_I_INUM (x);
3432 if (SCM_LIKELY (SCM_I_INUMP (y)))
3433 {
3434 scm_t_inum yy = SCM_I_INUM (y);
3435 if (SCM_UNLIKELY (yy == 0))
3436 scm_num_overflow (s_scm_round_quotient);
3437 else
3438 {
3439 scm_t_inum qq = xx / yy;
3440 scm_t_inum rr = xx % yy;
3441 scm_t_inum ay = yy;
3442 scm_t_inum r2 = 2 * rr;
3443
3444 if (SCM_LIKELY (yy < 0))
3445 {
3446 ay = -ay;
3447 r2 = -r2;
3448 }
3449
3450 if (qq & 1L)
3451 {
3452 if (r2 >= ay)
3453 qq++;
3454 else if (r2 <= -ay)
3455 qq--;
3456 }
3457 else
3458 {
3459 if (r2 > ay)
3460 qq++;
3461 else if (r2 < -ay)
3462 qq--;
3463 }
3464 if (SCM_LIKELY (SCM_FIXABLE (qq)))
3465 return SCM_I_MAKINUM (qq);
3466 else
3467 return scm_i_inum2big (qq);
3468 }
3469 }
3470 else if (SCM_BIGP (y))
3471 {
3472 /* Pass a denormalized bignum version of x (even though it
3473 can fit in a fixnum) to scm_i_bigint_round_quotient */
3474 return scm_i_bigint_round_quotient (scm_i_long2big (xx), y);
3475 }
3476 else if (SCM_REALP (y))
3477 return scm_i_inexact_round_quotient (xx, SCM_REAL_VALUE (y));
3478 else if (SCM_FRACTIONP (y))
3479 return scm_i_exact_rational_round_quotient (x, y);
3480 else
3481 SCM_WTA_DISPATCH_2 (g_scm_round_quotient, x, y, SCM_ARG2,
3482 s_scm_round_quotient);
3483 }
3484 else if (SCM_BIGP (x))
3485 {
3486 if (SCM_LIKELY (SCM_I_INUMP (y)))
3487 {
3488 scm_t_inum yy = SCM_I_INUM (y);
3489 if (SCM_UNLIKELY (yy == 0))
3490 scm_num_overflow (s_scm_round_quotient);
3491 else if (SCM_UNLIKELY (yy == 1))
3492 return x;
3493 else
3494 {
3495 SCM q = scm_i_mkbig ();
3496 scm_t_inum rr;
3497 int needs_adjustment;
3498
3499 if (yy > 0)
3500 {
3501 rr = mpz_fdiv_q_ui (SCM_I_BIG_MPZ (q),
3502 SCM_I_BIG_MPZ (x), yy);
3503 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3504 needs_adjustment = (2*rr >= yy);
3505 else
3506 needs_adjustment = (2*rr > yy);
3507 }
3508 else
3509 {
3510 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
3511 SCM_I_BIG_MPZ (x), -yy);
3512 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
3513 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3514 needs_adjustment = (2*rr <= yy);
3515 else
3516 needs_adjustment = (2*rr < yy);
3517 }
3518 scm_remember_upto_here_1 (x);
3519 if (needs_adjustment)
3520 mpz_add_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q), 1);
3521 return scm_i_normbig (q);
3522 }
3523 }
3524 else if (SCM_BIGP (y))
3525 return scm_i_bigint_round_quotient (x, y);
3526 else if (SCM_REALP (y))
3527 return scm_i_inexact_round_quotient
3528 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
3529 else if (SCM_FRACTIONP (y))
3530 return scm_i_exact_rational_round_quotient (x, y);
3531 else
3532 SCM_WTA_DISPATCH_2 (g_scm_round_quotient, x, y, SCM_ARG2,
3533 s_scm_round_quotient);
3534 }
3535 else if (SCM_REALP (x))
3536 {
3537 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
3538 SCM_BIGP (y) || SCM_FRACTIONP (y))
3539 return scm_i_inexact_round_quotient
3540 (SCM_REAL_VALUE (x), scm_to_double (y));
3541 else
3542 SCM_WTA_DISPATCH_2 (g_scm_round_quotient, x, y, SCM_ARG2,
3543 s_scm_round_quotient);
3544 }
3545 else if (SCM_FRACTIONP (x))
3546 {
3547 if (SCM_REALP (y))
3548 return scm_i_inexact_round_quotient
3549 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
3550 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
3551 return scm_i_exact_rational_round_quotient (x, y);
3552 else
3553 SCM_WTA_DISPATCH_2 (g_scm_round_quotient, x, y, SCM_ARG2,
3554 s_scm_round_quotient);
3555 }
3556 else
3557 SCM_WTA_DISPATCH_2 (g_scm_round_quotient, x, y, SCM_ARG1,
3558 s_scm_round_quotient);
3559 }
3560 #undef FUNC_NAME
3561
3562 static SCM
3563 scm_i_inexact_round_quotient (double x, double y)
3564 {
3565 if (SCM_UNLIKELY (y == 0))
3566 scm_num_overflow (s_scm_round_quotient); /* or return a NaN? */
3567 else
3568 return scm_from_double (scm_c_round (x / y));
3569 }
3570
3571 /* Assumes that both x and y are bigints, though
3572 x might be able to fit into a fixnum. */
3573 static SCM
3574 scm_i_bigint_round_quotient (SCM x, SCM y)
3575 {
3576 SCM q, r, r2;
3577 int cmp, needs_adjustment;
3578
3579 /* Note that x might be small enough to fit into a
3580 fixnum, so we must not let it escape into the wild */
3581 q = scm_i_mkbig ();
3582 r = scm_i_mkbig ();
3583 r2 = scm_i_mkbig ();
3584
3585 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
3586 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3587 mpz_mul_2exp (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (r), 1); /* r2 = 2*r */
3588 scm_remember_upto_here_2 (x, r);
3589
3590 cmp = mpz_cmpabs (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (y));
3591 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3592 needs_adjustment = (cmp >= 0);
3593 else
3594 needs_adjustment = (cmp > 0);
3595 scm_remember_upto_here_2 (r2, y);
3596
3597 if (needs_adjustment)
3598 mpz_add_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q), 1);
3599
3600 return scm_i_normbig (q);
3601 }
3602
3603 static SCM
3604 scm_i_exact_rational_round_quotient (SCM x, SCM y)
3605 {
3606 return scm_round_quotient
3607 (scm_product (scm_numerator (x), scm_denominator (y)),
3608 scm_product (scm_numerator (y), scm_denominator (x)));
3609 }
3610
3611 static SCM scm_i_inexact_round_remainder (double x, double y);
3612 static SCM scm_i_bigint_round_remainder (SCM x, SCM y);
3613 static SCM scm_i_exact_rational_round_remainder (SCM x, SCM y);
3614
3615 SCM_PRIMITIVE_GENERIC (scm_round_remainder, "round-remainder", 2, 0, 0,
3616 (SCM x, SCM y),
3617 "Return the real number @var{r} such that\n"
3618 "@math{@var{x} = @var{q}*@var{y} + @var{r}}, where\n"
3619 "@var{q} is @math{@var{x} / @var{y}} rounded to the\n"
3620 "nearest integer, with ties going to the nearest\n"
3621 "even integer.\n"
3622 "@lisp\n"
3623 "(round-remainder 123 10) @result{} 3\n"
3624 "(round-remainder 123 -10) @result{} 3\n"
3625 "(round-remainder -123 10) @result{} -3\n"
3626 "(round-remainder -123 -10) @result{} -3\n"
3627 "(round-remainder 125 10) @result{} 5\n"
3628 "(round-remainder 127 10) @result{} -3\n"
3629 "(round-remainder 135 10) @result{} -5\n"
3630 "(round-remainder -123.2 -63.5) @result{} 3.8\n"
3631 "(round-remainder 16/3 -10/7) @result{} -8/21\n"
3632 "@end lisp")
3633 #define FUNC_NAME s_scm_round_remainder
3634 {
3635 if (SCM_LIKELY (SCM_I_INUMP (x)))
3636 {
3637 scm_t_inum xx = SCM_I_INUM (x);
3638 if (SCM_LIKELY (SCM_I_INUMP (y)))
3639 {
3640 scm_t_inum yy = SCM_I_INUM (y);
3641 if (SCM_UNLIKELY (yy == 0))
3642 scm_num_overflow (s_scm_round_remainder);
3643 else
3644 {
3645 scm_t_inum qq = xx / yy;
3646 scm_t_inum rr = xx % yy;
3647 scm_t_inum ay = yy;
3648 scm_t_inum r2 = 2 * rr;
3649
3650 if (SCM_LIKELY (yy < 0))
3651 {
3652 ay = -ay;
3653 r2 = -r2;
3654 }
3655
3656 if (qq & 1L)
3657 {
3658 if (r2 >= ay)
3659 rr -= yy;
3660 else if (r2 <= -ay)
3661 rr += yy;
3662 }
3663 else
3664 {
3665 if (r2 > ay)
3666 rr -= yy;
3667 else if (r2 < -ay)
3668 rr += yy;
3669 }
3670 return SCM_I_MAKINUM (rr);
3671 }
3672 }
3673 else if (SCM_BIGP (y))
3674 {
3675 /* Pass a denormalized bignum version of x (even though it
3676 can fit in a fixnum) to scm_i_bigint_round_remainder */
3677 return scm_i_bigint_round_remainder
3678 (scm_i_long2big (xx), y);
3679 }
3680 else if (SCM_REALP (y))
3681 return scm_i_inexact_round_remainder (xx, SCM_REAL_VALUE (y));
3682 else if (SCM_FRACTIONP (y))
3683 return scm_i_exact_rational_round_remainder (x, y);
3684 else
3685 SCM_WTA_DISPATCH_2 (g_scm_round_remainder, x, y, SCM_ARG2,
3686 s_scm_round_remainder);
3687 }
3688 else if (SCM_BIGP (x))
3689 {
3690 if (SCM_LIKELY (SCM_I_INUMP (y)))
3691 {
3692 scm_t_inum yy = SCM_I_INUM (y);
3693 if (SCM_UNLIKELY (yy == 0))
3694 scm_num_overflow (s_scm_round_remainder);
3695 else
3696 {
3697 SCM q = scm_i_mkbig ();
3698 scm_t_inum rr;
3699 int needs_adjustment;
3700
3701 if (yy > 0)
3702 {
3703 rr = mpz_fdiv_q_ui (SCM_I_BIG_MPZ (q),
3704 SCM_I_BIG_MPZ (x), yy);
3705 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3706 needs_adjustment = (2*rr >= yy);
3707 else
3708 needs_adjustment = (2*rr > yy);
3709 }
3710 else
3711 {
3712 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
3713 SCM_I_BIG_MPZ (x), -yy);
3714 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3715 needs_adjustment = (2*rr <= yy);
3716 else
3717 needs_adjustment = (2*rr < yy);
3718 }
3719 scm_remember_upto_here_2 (x, q);
3720 if (needs_adjustment)
3721 rr -= yy;
3722 return SCM_I_MAKINUM (rr);
3723 }
3724 }
3725 else if (SCM_BIGP (y))
3726 return scm_i_bigint_round_remainder (x, y);
3727 else if (SCM_REALP (y))
3728 return scm_i_inexact_round_remainder
3729 (scm_i_big2dbl (x), SCM_REAL_VALUE (y));
3730 else if (SCM_FRACTIONP (y))
3731 return scm_i_exact_rational_round_remainder (x, y);
3732 else
3733 SCM_WTA_DISPATCH_2 (g_scm_round_remainder, x, y, SCM_ARG2,
3734 s_scm_round_remainder);
3735 }
3736 else if (SCM_REALP (x))
3737 {
3738 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
3739 SCM_BIGP (y) || SCM_FRACTIONP (y))
3740 return scm_i_inexact_round_remainder
3741 (SCM_REAL_VALUE (x), scm_to_double (y));
3742 else
3743 SCM_WTA_DISPATCH_2 (g_scm_round_remainder, x, y, SCM_ARG2,
3744 s_scm_round_remainder);
3745 }
3746 else if (SCM_FRACTIONP (x))
3747 {
3748 if (SCM_REALP (y))
3749 return scm_i_inexact_round_remainder
3750 (scm_i_fraction2double (x), SCM_REAL_VALUE (y));
3751 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
3752 return scm_i_exact_rational_round_remainder (x, y);
3753 else
3754 SCM_WTA_DISPATCH_2 (g_scm_round_remainder, x, y, SCM_ARG2,
3755 s_scm_round_remainder);
3756 }
3757 else
3758 SCM_WTA_DISPATCH_2 (g_scm_round_remainder, x, y, SCM_ARG1,
3759 s_scm_round_remainder);
3760 }
3761 #undef FUNC_NAME
3762
3763 static SCM
3764 scm_i_inexact_round_remainder (double x, double y)
3765 {
3766 /* Although it would be more efficient to use fmod here, we can't
3767 because it would in some cases produce results inconsistent with
3768 scm_i_inexact_round_quotient, such that x != r + q * y (not even
3769 close). In particular, when x-y/2 is very close to a multiple of
3770 y, then r might be either -abs(y/2) or abs(y/2), but those two
3771 cases must correspond to different choices of q. If quotient
3772 chooses one and remainder chooses the other, it would be bad. */
3773
3774 if (SCM_UNLIKELY (y == 0))
3775 scm_num_overflow (s_scm_round_remainder); /* or return a NaN? */
3776 else
3777 {
3778 double q = scm_c_round (x / y);
3779 return scm_from_double (x - q * y);
3780 }
3781 }
3782
3783 /* Assumes that both x and y are bigints, though
3784 x might be able to fit into a fixnum. */
3785 static SCM
3786 scm_i_bigint_round_remainder (SCM x, SCM y)
3787 {
3788 SCM q, r, r2;
3789 int cmp, needs_adjustment;
3790
3791 /* Note that x might be small enough to fit into a
3792 fixnum, so we must not let it escape into the wild */
3793 q = scm_i_mkbig ();
3794 r = scm_i_mkbig ();
3795 r2 = scm_i_mkbig ();
3796
3797 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
3798 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
3799 scm_remember_upto_here_1 (x);
3800 mpz_mul_2exp (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (r), 1); /* r2 = 2*r */
3801
3802 cmp = mpz_cmpabs (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (y));
3803 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3804 needs_adjustment = (cmp >= 0);
3805 else
3806 needs_adjustment = (cmp > 0);
3807 scm_remember_upto_here_2 (q, r2);
3808
3809 if (needs_adjustment)
3810 mpz_sub (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y));
3811
3812 scm_remember_upto_here_1 (y);
3813 return scm_i_normbig (r);
3814 }
3815
3816 static SCM
3817 scm_i_exact_rational_round_remainder (SCM x, SCM y)
3818 {
3819 SCM xd = scm_denominator (x);
3820 SCM yd = scm_denominator (y);
3821 SCM r1 = scm_round_remainder (scm_product (scm_numerator (x), yd),
3822 scm_product (scm_numerator (y), xd));
3823 return scm_divide (r1, scm_product (xd, yd));
3824 }
3825
3826
3827 static void scm_i_inexact_round_divide (double x, double y, SCM *qp, SCM *rp);
3828 static void scm_i_bigint_round_divide (SCM x, SCM y, SCM *qp, SCM *rp);
3829 static void scm_i_exact_rational_round_divide (SCM x, SCM y, SCM *qp, SCM *rp);
3830
3831 SCM_PRIMITIVE_GENERIC (scm_i_round_divide, "round/", 2, 0, 0,
3832 (SCM x, SCM y),
3833 "Return the integer @var{q} and the real number @var{r}\n"
3834 "such that @math{@var{x} = @var{q}*@var{y} + @var{r}}\n"
3835 "and @var{q} is @math{@var{x} / @var{y}} rounded to the\n"
3836 "nearest integer, with ties going to the nearest even integer.\n"
3837 "@lisp\n"
3838 "(round/ 123 10) @result{} 12 and 3\n"
3839 "(round/ 123 -10) @result{} -12 and 3\n"
3840 "(round/ -123 10) @result{} -12 and -3\n"
3841 "(round/ -123 -10) @result{} 12 and -3\n"
3842 "(round/ 125 10) @result{} 12 and 5\n"
3843 "(round/ 127 10) @result{} 13 and -3\n"
3844 "(round/ 135 10) @result{} 14 and -5\n"
3845 "(round/ -123.2 -63.5) @result{} 2.0 and 3.8\n"
3846 "(round/ 16/3 -10/7) @result{} -4 and -8/21\n"
3847 "@end lisp")
3848 #define FUNC_NAME s_scm_i_round_divide
3849 {
3850 SCM q, r;
3851
3852 scm_round_divide(x, y, &q, &r);
3853 return scm_values (scm_list_2 (q, r));
3854 }
3855 #undef FUNC_NAME
3856
3857 #define s_scm_round_divide s_scm_i_round_divide
3858 #define g_scm_round_divide g_scm_i_round_divide
3859
3860 void
3861 scm_round_divide (SCM x, SCM y, SCM *qp, SCM *rp)
3862 {
3863 if (SCM_LIKELY (SCM_I_INUMP (x)))
3864 {
3865 scm_t_inum xx = SCM_I_INUM (x);
3866 if (SCM_LIKELY (SCM_I_INUMP (y)))
3867 {
3868 scm_t_inum yy = SCM_I_INUM (y);
3869 if (SCM_UNLIKELY (yy == 0))
3870 scm_num_overflow (s_scm_round_divide);
3871 else
3872 {
3873 scm_t_inum qq = xx / yy;
3874 scm_t_inum rr = xx % yy;
3875 scm_t_inum ay = yy;
3876 scm_t_inum r2 = 2 * rr;
3877
3878 if (SCM_LIKELY (yy < 0))
3879 {
3880 ay = -ay;
3881 r2 = -r2;
3882 }
3883
3884 if (qq & 1L)
3885 {
3886 if (r2 >= ay)
3887 { qq++; rr -= yy; }
3888 else if (r2 <= -ay)
3889 { qq--; rr += yy; }
3890 }
3891 else
3892 {
3893 if (r2 > ay)
3894 { qq++; rr -= yy; }
3895 else if (r2 < -ay)
3896 { qq--; rr += yy; }
3897 }
3898 if (SCM_LIKELY (SCM_FIXABLE (qq)))
3899 *qp = SCM_I_MAKINUM (qq);
3900 else
3901 *qp = scm_i_inum2big (qq);
3902 *rp = SCM_I_MAKINUM (rr);
3903 }
3904 return;
3905 }
3906 else if (SCM_BIGP (y))
3907 {
3908 /* Pass a denormalized bignum version of x (even though it
3909 can fit in a fixnum) to scm_i_bigint_round_divide */
3910 return scm_i_bigint_round_divide
3911 (scm_i_long2big (SCM_I_INUM (x)), y, qp, rp);
3912 }
3913 else if (SCM_REALP (y))
3914 return scm_i_inexact_round_divide (xx, SCM_REAL_VALUE (y), qp, rp);
3915 else if (SCM_FRACTIONP (y))
3916 return scm_i_exact_rational_round_divide (x, y, qp, rp);
3917 else
3918 return two_valued_wta_dispatch_2 (g_scm_round_divide, x, y, SCM_ARG2,
3919 s_scm_round_divide, qp, rp);
3920 }
3921 else if (SCM_BIGP (x))
3922 {
3923 if (SCM_LIKELY (SCM_I_INUMP (y)))
3924 {
3925 scm_t_inum yy = SCM_I_INUM (y);
3926 if (SCM_UNLIKELY (yy == 0))
3927 scm_num_overflow (s_scm_round_divide);
3928 else
3929 {
3930 SCM q = scm_i_mkbig ();
3931 scm_t_inum rr;
3932 int needs_adjustment;
3933
3934 if (yy > 0)
3935 {
3936 rr = mpz_fdiv_q_ui (SCM_I_BIG_MPZ (q),
3937 SCM_I_BIG_MPZ (x), yy);
3938 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3939 needs_adjustment = (2*rr >= yy);
3940 else
3941 needs_adjustment = (2*rr > yy);
3942 }
3943 else
3944 {
3945 rr = - mpz_cdiv_q_ui (SCM_I_BIG_MPZ (q),
3946 SCM_I_BIG_MPZ (x), -yy);
3947 mpz_neg (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q));
3948 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
3949 needs_adjustment = (2*rr <= yy);
3950 else
3951 needs_adjustment = (2*rr < yy);
3952 }
3953 scm_remember_upto_here_1 (x);
3954 if (needs_adjustment)
3955 {
3956 mpz_add_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q), 1);
3957 rr -= yy;
3958 }
3959 *qp = scm_i_normbig (q);
3960 *rp = SCM_I_MAKINUM (rr);
3961 }
3962 return;
3963 }
3964 else if (SCM_BIGP (y))
3965 return scm_i_bigint_round_divide (x, y, qp, rp);
3966 else if (SCM_REALP (y))
3967 return scm_i_inexact_round_divide
3968 (scm_i_big2dbl (x), SCM_REAL_VALUE (y), qp, rp);
3969 else if (SCM_FRACTIONP (y))
3970 return scm_i_exact_rational_round_divide (x, y, qp, rp);
3971 else
3972 return two_valued_wta_dispatch_2 (g_scm_round_divide, x, y, SCM_ARG2,
3973 s_scm_round_divide, qp, rp);
3974 }
3975 else if (SCM_REALP (x))
3976 {
3977 if (SCM_REALP (y) || SCM_I_INUMP (y) ||
3978 SCM_BIGP (y) || SCM_FRACTIONP (y))
3979 return scm_i_inexact_round_divide
3980 (SCM_REAL_VALUE (x), scm_to_double (y), qp, rp);
3981 else
3982 return two_valued_wta_dispatch_2 (g_scm_round_divide, x, y, SCM_ARG2,
3983 s_scm_round_divide, qp, rp);
3984 }
3985 else if (SCM_FRACTIONP (x))
3986 {
3987 if (SCM_REALP (y))
3988 return scm_i_inexact_round_divide
3989 (scm_i_fraction2double (x), SCM_REAL_VALUE (y), qp, rp);
3990 else if (SCM_I_INUMP (y) || SCM_BIGP (y) || SCM_FRACTIONP (y))
3991 return scm_i_exact_rational_round_divide (x, y, qp, rp);
3992 else
3993 return two_valued_wta_dispatch_2 (g_scm_round_divide, x, y, SCM_ARG2,
3994 s_scm_round_divide, qp, rp);
3995 }
3996 else
3997 return two_valued_wta_dispatch_2 (g_scm_round_divide, x, y, SCM_ARG1,
3998 s_scm_round_divide, qp, rp);
3999 }
4000
4001 static void
4002 scm_i_inexact_round_divide (double x, double y, SCM *qp, SCM *rp)
4003 {
4004 if (SCM_UNLIKELY (y == 0))
4005 scm_num_overflow (s_scm_round_divide); /* or return a NaN? */
4006 else
4007 {
4008 double q = scm_c_round (x / y);
4009 double r = x - q * y;
4010 *qp = scm_from_double (q);
4011 *rp = scm_from_double (r);
4012 }
4013 }
4014
4015 /* Assumes that both x and y are bigints, though
4016 x might be able to fit into a fixnum. */
4017 static void
4018 scm_i_bigint_round_divide (SCM x, SCM y, SCM *qp, SCM *rp)
4019 {
4020 SCM q, r, r2;
4021 int cmp, needs_adjustment;
4022
4023 /* Note that x might be small enough to fit into a
4024 fixnum, so we must not let it escape into the wild */
4025 q = scm_i_mkbig ();
4026 r = scm_i_mkbig ();
4027 r2 = scm_i_mkbig ();
4028
4029 mpz_fdiv_qr (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (r),
4030 SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
4031 scm_remember_upto_here_1 (x);
4032 mpz_mul_2exp (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (r), 1); /* r2 = 2*r */
4033
4034 cmp = mpz_cmpabs (SCM_I_BIG_MPZ (r2), SCM_I_BIG_MPZ (y));
4035 if (mpz_odd_p (SCM_I_BIG_MPZ (q)))
4036 needs_adjustment = (cmp >= 0);
4037 else
4038 needs_adjustment = (cmp > 0);
4039
4040 if (needs_adjustment)
4041 {
4042 mpz_add_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q), 1);
4043 mpz_sub (SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (y));
4044 }
4045
4046 scm_remember_upto_here_2 (r2, y);
4047 *qp = scm_i_normbig (q);
4048 *rp = scm_i_normbig (r);
4049 }
4050
4051 static void
4052 scm_i_exact_rational_round_divide (SCM x, SCM y, SCM *qp, SCM *rp)
4053 {
4054 SCM r1;
4055 SCM xd = scm_denominator (x);
4056 SCM yd = scm_denominator (y);
4057
4058 scm_round_divide (scm_product (scm_numerator (x), yd),
4059 scm_product (scm_numerator (y), xd),
4060 qp, &r1);
4061 *rp = scm_divide (r1, scm_product (xd, yd));
4062 }
4063
4064
4065 SCM_PRIMITIVE_GENERIC (scm_i_gcd, "gcd", 0, 2, 1,
4066 (SCM x, SCM y, SCM rest),
4067 "Return the greatest common divisor of all parameter values.\n"
4068 "If called without arguments, 0 is returned.")
4069 #define FUNC_NAME s_scm_i_gcd
4070 {
4071 while (!scm_is_null (rest))
4072 { x = scm_gcd (x, y);
4073 y = scm_car (rest);
4074 rest = scm_cdr (rest);
4075 }
4076 return scm_gcd (x, y);
4077 }
4078 #undef FUNC_NAME
4079
4080 #define s_gcd s_scm_i_gcd
4081 #define g_gcd g_scm_i_gcd
4082
4083 SCM
4084 scm_gcd (SCM x, SCM y)
4085 {
4086 if (SCM_UNLIKELY (SCM_UNBNDP (y)))
4087 return SCM_UNBNDP (x) ? SCM_INUM0 : scm_abs (x);
4088
4089 if (SCM_LIKELY (SCM_I_INUMP (x)))
4090 {
4091 if (SCM_LIKELY (SCM_I_INUMP (y)))
4092 {
4093 scm_t_inum xx = SCM_I_INUM (x);
4094 scm_t_inum yy = SCM_I_INUM (y);
4095 scm_t_inum u = xx < 0 ? -xx : xx;
4096 scm_t_inum v = yy < 0 ? -yy : yy;
4097 scm_t_inum result;
4098 if (SCM_UNLIKELY (xx == 0))
4099 result = v;
4100 else if (SCM_UNLIKELY (yy == 0))
4101 result = u;
4102 else
4103 {
4104 int k = 0;
4105 /* Determine a common factor 2^k */
4106 while (((u | v) & 1) == 0)
4107 {
4108 k++;
4109 u >>= 1;
4110 v >>= 1;
4111 }
4112 /* Now, any factor 2^n can be eliminated */
4113 if ((u & 1) == 0)
4114 while ((u & 1) == 0)
4115 u >>= 1;
4116 else
4117 while ((v & 1) == 0)
4118 v >>= 1;
4119 /* Both u and v are now odd. Subtract the smaller one
4120 from the larger one to produce an even number, remove
4121 more factors of two, and repeat. */
4122 while (u != v)
4123 {
4124 if (u > v)
4125 {
4126 u -= v;
4127 while ((u & 1) == 0)
4128 u >>= 1;
4129 }
4130 else
4131 {
4132 v -= u;
4133 while ((v & 1) == 0)
4134 v >>= 1;
4135 }
4136 }
4137 result = u << k;
4138 }
4139 return (SCM_POSFIXABLE (result)
4140 ? SCM_I_MAKINUM (result)
4141 : scm_i_inum2big (result));
4142 }
4143 else if (SCM_BIGP (y))
4144 {
4145 SCM_SWAP (x, y);
4146 goto big_inum;
4147 }
4148 else if (SCM_REALP (y) && scm_is_integer (y))
4149 goto handle_inexacts;
4150 else
4151 SCM_WTA_DISPATCH_2 (g_gcd, x, y, SCM_ARG2, s_gcd);
4152 }
4153 else if (SCM_BIGP (x))
4154 {
4155 if (SCM_I_INUMP (y))
4156 {
4157 scm_t_bits result;
4158 scm_t_inum yy;
4159 big_inum:
4160 yy = SCM_I_INUM (y);
4161 if (yy == 0)
4162 return scm_abs (x);
4163 if (yy < 0)
4164 yy = -yy;
4165 result = mpz_gcd_ui (NULL, SCM_I_BIG_MPZ (x), yy);
4166 scm_remember_upto_here_1 (x);
4167 return (SCM_POSFIXABLE (result)
4168 ? SCM_I_MAKINUM (result)
4169 : scm_from_unsigned_integer (result));
4170 }
4171 else if (SCM_BIGP (y))
4172 {
4173 SCM result = scm_i_mkbig ();
4174 mpz_gcd (SCM_I_BIG_MPZ (result),
4175 SCM_I_BIG_MPZ (x),
4176 SCM_I_BIG_MPZ (y));
4177 scm_remember_upto_here_2 (x, y);
4178 return scm_i_normbig (result);
4179 }
4180 else if (SCM_REALP (y) && scm_is_integer (y))
4181 goto handle_inexacts;
4182 else
4183 SCM_WTA_DISPATCH_2 (g_gcd, x, y, SCM_ARG2, s_gcd);
4184 }
4185 else if (SCM_REALP (x) && scm_is_integer (x))
4186 {
4187 if (SCM_I_INUMP (y) || SCM_BIGP (y)
4188 || (SCM_REALP (y) && scm_is_integer (y)))
4189 {
4190 handle_inexacts:
4191 return scm_exact_to_inexact (scm_gcd (scm_inexact_to_exact (x),
4192 scm_inexact_to_exact (y)));
4193 }
4194 else
4195 SCM_WTA_DISPATCH_2 (g_gcd, x, y, SCM_ARG2, s_gcd);
4196 }
4197 else
4198 SCM_WTA_DISPATCH_2 (g_gcd, x, y, SCM_ARG1, s_gcd);
4199 }
4200
4201 SCM_PRIMITIVE_GENERIC (scm_i_lcm, "lcm", 0, 2, 1,
4202 (SCM x, SCM y, SCM rest),
4203 "Return the least common multiple of the arguments.\n"
4204 "If called without arguments, 1 is returned.")
4205 #define FUNC_NAME s_scm_i_lcm
4206 {
4207 while (!scm_is_null (rest))
4208 { x = scm_lcm (x, y);
4209 y = scm_car (rest);
4210 rest = scm_cdr (rest);
4211 }
4212 return scm_lcm (x, y);
4213 }
4214 #undef FUNC_NAME
4215
4216 #define s_lcm s_scm_i_lcm
4217 #define g_lcm g_scm_i_lcm
4218
4219 SCM
4220 scm_lcm (SCM n1, SCM n2)
4221 {
4222 if (SCM_UNLIKELY (SCM_UNBNDP (n2)))
4223 return SCM_UNBNDP (n1) ? SCM_INUM1 : scm_abs (n1);
4224
4225 if (SCM_LIKELY (SCM_I_INUMP (n1)))
4226 {
4227 if (SCM_LIKELY (SCM_I_INUMP (n2)))
4228 {
4229 SCM d = scm_gcd (n1, n2);
4230 if (scm_is_eq (d, SCM_INUM0))
4231 return d;
4232 else
4233 return scm_abs (scm_product (n1, scm_quotient (n2, d)));
4234 }
4235 else if (SCM_LIKELY (SCM_BIGP (n2)))
4236 {
4237 /* inum n1, big n2 */
4238 inumbig:
4239 {
4240 SCM result = scm_i_mkbig ();
4241 scm_t_inum nn1 = SCM_I_INUM (n1);
4242 if (nn1 == 0) return SCM_INUM0;
4243 if (nn1 < 0) nn1 = - nn1;
4244 mpz_lcm_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (n2), nn1);
4245 scm_remember_upto_here_1 (n2);
4246 return result;
4247 }
4248 }
4249 else if (SCM_REALP (n2) && scm_is_integer (n2))
4250 goto handle_inexacts;
4251 else
4252 SCM_WTA_DISPATCH_2 (g_lcm, n1, n2, SCM_ARG2, s_lcm);
4253 }
4254 else if (SCM_LIKELY (SCM_BIGP (n1)))
4255 {
4256 /* big n1 */
4257 if (SCM_I_INUMP (n2))
4258 {
4259 SCM_SWAP (n1, n2);
4260 goto inumbig;
4261 }
4262 else if (SCM_LIKELY (SCM_BIGP (n2)))
4263 {
4264 SCM result = scm_i_mkbig ();
4265 mpz_lcm(SCM_I_BIG_MPZ (result),
4266 SCM_I_BIG_MPZ (n1),
4267 SCM_I_BIG_MPZ (n2));
4268 scm_remember_upto_here_2(n1, n2);
4269 /* shouldn't need to normalize b/c lcm of 2 bigs should be big */
4270 return result;
4271 }
4272 else if (SCM_REALP (n2) && scm_is_integer (n2))
4273 goto handle_inexacts;
4274 else
4275 SCM_WTA_DISPATCH_2 (g_lcm, n1, n2, SCM_ARG2, s_lcm);
4276 }
4277 else if (SCM_REALP (n1) && scm_is_integer (n1))
4278 {
4279 if (SCM_I_INUMP (n2) || SCM_BIGP (n2)
4280 || (SCM_REALP (n2) && scm_is_integer (n2)))
4281 {
4282 handle_inexacts:
4283 return scm_exact_to_inexact (scm_lcm (scm_inexact_to_exact (n1),
4284 scm_inexact_to_exact (n2)));
4285 }
4286 else
4287 SCM_WTA_DISPATCH_2 (g_lcm, n1, n2, SCM_ARG2, s_lcm);
4288 }
4289 else
4290 SCM_WTA_DISPATCH_2 (g_lcm, n1, n2, SCM_ARG1, s_lcm);
4291 }
4292
4293 /* Emulating 2's complement bignums with sign magnitude arithmetic:
4294
4295 Logand:
4296 X Y Result Method:
4297 (len)
4298 + + + x (map digit:logand X Y)
4299 + - + x (map digit:logand X (lognot (+ -1 Y)))
4300 - + + y (map digit:logand (lognot (+ -1 X)) Y)
4301 - - - (+ 1 (map digit:logior (+ -1 X) (+ -1 Y)))
4302
4303 Logior:
4304 X Y Result Method:
4305
4306 + + + (map digit:logior X Y)
4307 + - - y (+ 1 (map digit:logand (lognot X) (+ -1 Y)))
4308 - + - x (+ 1 (map digit:logand (+ -1 X) (lognot Y)))
4309 - - - x (+ 1 (map digit:logand (+ -1 X) (+ -1 Y)))
4310
4311 Logxor:
4312 X Y Result Method:
4313
4314 + + + (map digit:logxor X Y)
4315 + - - (+ 1 (map digit:logxor X (+ -1 Y)))
4316 - + - (+ 1 (map digit:logxor (+ -1 X) Y))
4317 - - + (map digit:logxor (+ -1 X) (+ -1 Y))
4318
4319 Logtest:
4320 X Y Result
4321
4322 + + (any digit:logand X Y)
4323 + - (any digit:logand X (lognot (+ -1 Y)))
4324 - + (any digit:logand (lognot (+ -1 X)) Y)
4325 - - #t
4326
4327 */
4328
4329 SCM_DEFINE (scm_i_logand, "logand", 0, 2, 1,
4330 (SCM x, SCM y, SCM rest),
4331 "Return the bitwise AND of the integer arguments.\n\n"
4332 "@lisp\n"
4333 "(logand) @result{} -1\n"
4334 "(logand 7) @result{} 7\n"
4335 "(logand #b111 #b011 #b001) @result{} 1\n"
4336 "@end lisp")
4337 #define FUNC_NAME s_scm_i_logand
4338 {
4339 while (!scm_is_null (rest))
4340 { x = scm_logand (x, y);
4341 y = scm_car (rest);
4342 rest = scm_cdr (rest);
4343 }
4344 return scm_logand (x, y);
4345 }
4346 #undef FUNC_NAME
4347
4348 #define s_scm_logand s_scm_i_logand
4349
4350 SCM scm_logand (SCM n1, SCM n2)
4351 #define FUNC_NAME s_scm_logand
4352 {
4353 scm_t_inum nn1;
4354
4355 if (SCM_UNBNDP (n2))
4356 {
4357 if (SCM_UNBNDP (n1))
4358 return SCM_I_MAKINUM (-1);
4359 else if (!SCM_NUMBERP (n1))
4360 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4361 else if (SCM_NUMBERP (n1))
4362 return n1;
4363 else
4364 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4365 }
4366
4367 if (SCM_I_INUMP (n1))
4368 {
4369 nn1 = SCM_I_INUM (n1);
4370 if (SCM_I_INUMP (n2))
4371 {
4372 scm_t_inum nn2 = SCM_I_INUM (n2);
4373 return SCM_I_MAKINUM (nn1 & nn2);
4374 }
4375 else if SCM_BIGP (n2)
4376 {
4377 intbig:
4378 if (nn1 == 0)
4379 return SCM_INUM0;
4380 {
4381 SCM result_z = scm_i_mkbig ();
4382 mpz_t nn1_z;
4383 mpz_init_set_si (nn1_z, nn1);
4384 mpz_and (SCM_I_BIG_MPZ (result_z), nn1_z, SCM_I_BIG_MPZ (n2));
4385 scm_remember_upto_here_1 (n2);
4386 mpz_clear (nn1_z);
4387 return scm_i_normbig (result_z);
4388 }
4389 }
4390 else
4391 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4392 }
4393 else if (SCM_BIGP (n1))
4394 {
4395 if (SCM_I_INUMP (n2))
4396 {
4397 SCM_SWAP (n1, n2);
4398 nn1 = SCM_I_INUM (n1);
4399 goto intbig;
4400 }
4401 else if (SCM_BIGP (n2))
4402 {
4403 SCM result_z = scm_i_mkbig ();
4404 mpz_and (SCM_I_BIG_MPZ (result_z),
4405 SCM_I_BIG_MPZ (n1),
4406 SCM_I_BIG_MPZ (n2));
4407 scm_remember_upto_here_2 (n1, n2);
4408 return scm_i_normbig (result_z);
4409 }
4410 else
4411 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4412 }
4413 else
4414 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4415 }
4416 #undef FUNC_NAME
4417
4418
4419 SCM_DEFINE (scm_i_logior, "logior", 0, 2, 1,
4420 (SCM x, SCM y, SCM rest),
4421 "Return the bitwise OR of the integer arguments.\n\n"
4422 "@lisp\n"
4423 "(logior) @result{} 0\n"
4424 "(logior 7) @result{} 7\n"
4425 "(logior #b000 #b001 #b011) @result{} 3\n"
4426 "@end lisp")
4427 #define FUNC_NAME s_scm_i_logior
4428 {
4429 while (!scm_is_null (rest))
4430 { x = scm_logior (x, y);
4431 y = scm_car (rest);
4432 rest = scm_cdr (rest);
4433 }
4434 return scm_logior (x, y);
4435 }
4436 #undef FUNC_NAME
4437
4438 #define s_scm_logior s_scm_i_logior
4439
4440 SCM scm_logior (SCM n1, SCM n2)
4441 #define FUNC_NAME s_scm_logior
4442 {
4443 scm_t_inum nn1;
4444
4445 if (SCM_UNBNDP (n2))
4446 {
4447 if (SCM_UNBNDP (n1))
4448 return SCM_INUM0;
4449 else if (SCM_NUMBERP (n1))
4450 return n1;
4451 else
4452 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4453 }
4454
4455 if (SCM_I_INUMP (n1))
4456 {
4457 nn1 = SCM_I_INUM (n1);
4458 if (SCM_I_INUMP (n2))
4459 {
4460 long nn2 = SCM_I_INUM (n2);
4461 return SCM_I_MAKINUM (nn1 | nn2);
4462 }
4463 else if (SCM_BIGP (n2))
4464 {
4465 intbig:
4466 if (nn1 == 0)
4467 return n2;
4468 {
4469 SCM result_z = scm_i_mkbig ();
4470 mpz_t nn1_z;
4471 mpz_init_set_si (nn1_z, nn1);
4472 mpz_ior (SCM_I_BIG_MPZ (result_z), nn1_z, SCM_I_BIG_MPZ (n2));
4473 scm_remember_upto_here_1 (n2);
4474 mpz_clear (nn1_z);
4475 return scm_i_normbig (result_z);
4476 }
4477 }
4478 else
4479 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4480 }
4481 else if (SCM_BIGP (n1))
4482 {
4483 if (SCM_I_INUMP (n2))
4484 {
4485 SCM_SWAP (n1, n2);
4486 nn1 = SCM_I_INUM (n1);
4487 goto intbig;
4488 }
4489 else if (SCM_BIGP (n2))
4490 {
4491 SCM result_z = scm_i_mkbig ();
4492 mpz_ior (SCM_I_BIG_MPZ (result_z),
4493 SCM_I_BIG_MPZ (n1),
4494 SCM_I_BIG_MPZ (n2));
4495 scm_remember_upto_here_2 (n1, n2);
4496 return scm_i_normbig (result_z);
4497 }
4498 else
4499 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4500 }
4501 else
4502 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4503 }
4504 #undef FUNC_NAME
4505
4506
4507 SCM_DEFINE (scm_i_logxor, "logxor", 0, 2, 1,
4508 (SCM x, SCM y, SCM rest),
4509 "Return the bitwise XOR of the integer arguments. A bit is\n"
4510 "set in the result if it is set in an odd number of arguments.\n"
4511 "@lisp\n"
4512 "(logxor) @result{} 0\n"
4513 "(logxor 7) @result{} 7\n"
4514 "(logxor #b000 #b001 #b011) @result{} 2\n"
4515 "(logxor #b000 #b001 #b011 #b011) @result{} 1\n"
4516 "@end lisp")
4517 #define FUNC_NAME s_scm_i_logxor
4518 {
4519 while (!scm_is_null (rest))
4520 { x = scm_logxor (x, y);
4521 y = scm_car (rest);
4522 rest = scm_cdr (rest);
4523 }
4524 return scm_logxor (x, y);
4525 }
4526 #undef FUNC_NAME
4527
4528 #define s_scm_logxor s_scm_i_logxor
4529
4530 SCM scm_logxor (SCM n1, SCM n2)
4531 #define FUNC_NAME s_scm_logxor
4532 {
4533 scm_t_inum nn1;
4534
4535 if (SCM_UNBNDP (n2))
4536 {
4537 if (SCM_UNBNDP (n1))
4538 return SCM_INUM0;
4539 else if (SCM_NUMBERP (n1))
4540 return n1;
4541 else
4542 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4543 }
4544
4545 if (SCM_I_INUMP (n1))
4546 {
4547 nn1 = SCM_I_INUM (n1);
4548 if (SCM_I_INUMP (n2))
4549 {
4550 scm_t_inum nn2 = SCM_I_INUM (n2);
4551 return SCM_I_MAKINUM (nn1 ^ nn2);
4552 }
4553 else if (SCM_BIGP (n2))
4554 {
4555 intbig:
4556 {
4557 SCM result_z = scm_i_mkbig ();
4558 mpz_t nn1_z;
4559 mpz_init_set_si (nn1_z, nn1);
4560 mpz_xor (SCM_I_BIG_MPZ (result_z), nn1_z, SCM_I_BIG_MPZ (n2));
4561 scm_remember_upto_here_1 (n2);
4562 mpz_clear (nn1_z);
4563 return scm_i_normbig (result_z);
4564 }
4565 }
4566 else
4567 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4568 }
4569 else if (SCM_BIGP (n1))
4570 {
4571 if (SCM_I_INUMP (n2))
4572 {
4573 SCM_SWAP (n1, n2);
4574 nn1 = SCM_I_INUM (n1);
4575 goto intbig;
4576 }
4577 else if (SCM_BIGP (n2))
4578 {
4579 SCM result_z = scm_i_mkbig ();
4580 mpz_xor (SCM_I_BIG_MPZ (result_z),
4581 SCM_I_BIG_MPZ (n1),
4582 SCM_I_BIG_MPZ (n2));
4583 scm_remember_upto_here_2 (n1, n2);
4584 return scm_i_normbig (result_z);
4585 }
4586 else
4587 SCM_WRONG_TYPE_ARG (SCM_ARG2, n2);
4588 }
4589 else
4590 SCM_WRONG_TYPE_ARG (SCM_ARG1, n1);
4591 }
4592 #undef FUNC_NAME
4593
4594
4595 SCM_DEFINE (scm_logtest, "logtest", 2, 0, 0,
4596 (SCM j, SCM k),
4597 "Test whether @var{j} and @var{k} have any 1 bits in common.\n"
4598 "This is equivalent to @code{(not (zero? (logand j k)))}, but\n"
4599 "without actually calculating the @code{logand}, just testing\n"
4600 "for non-zero.\n"
4601 "\n"
4602 "@lisp\n"
4603 "(logtest #b0100 #b1011) @result{} #f\n"
4604 "(logtest #b0100 #b0111) @result{} #t\n"
4605 "@end lisp")
4606 #define FUNC_NAME s_scm_logtest
4607 {
4608 scm_t_inum nj;
4609
4610 if (SCM_I_INUMP (j))
4611 {
4612 nj = SCM_I_INUM (j);
4613 if (SCM_I_INUMP (k))
4614 {
4615 scm_t_inum nk = SCM_I_INUM (k);
4616 return scm_from_bool (nj & nk);
4617 }
4618 else if (SCM_BIGP (k))
4619 {
4620 intbig:
4621 if (nj == 0)
4622 return SCM_BOOL_F;
4623 {
4624 SCM result;
4625 mpz_t nj_z;
4626 mpz_init_set_si (nj_z, nj);
4627 mpz_and (nj_z, nj_z, SCM_I_BIG_MPZ (k));
4628 scm_remember_upto_here_1 (k);
4629 result = scm_from_bool (mpz_sgn (nj_z) != 0);
4630 mpz_clear (nj_z);
4631 return result;
4632 }
4633 }
4634 else
4635 SCM_WRONG_TYPE_ARG (SCM_ARG2, k);
4636 }
4637 else if (SCM_BIGP (j))
4638 {
4639 if (SCM_I_INUMP (k))
4640 {
4641 SCM_SWAP (j, k);
4642 nj = SCM_I_INUM (j);
4643 goto intbig;
4644 }
4645 else if (SCM_BIGP (k))
4646 {
4647 SCM result;
4648 mpz_t result_z;
4649 mpz_init (result_z);
4650 mpz_and (result_z,
4651 SCM_I_BIG_MPZ (j),
4652 SCM_I_BIG_MPZ (k));
4653 scm_remember_upto_here_2 (j, k);
4654 result = scm_from_bool (mpz_sgn (result_z) != 0);
4655 mpz_clear (result_z);
4656 return result;
4657 }
4658 else
4659 SCM_WRONG_TYPE_ARG (SCM_ARG2, k);
4660 }
4661 else
4662 SCM_WRONG_TYPE_ARG (SCM_ARG1, j);
4663 }
4664 #undef FUNC_NAME
4665
4666
4667 SCM_DEFINE (scm_logbit_p, "logbit?", 2, 0, 0,
4668 (SCM index, SCM j),
4669 "Test whether bit number @var{index} in @var{j} is set.\n"
4670 "@var{index} starts from 0 for the least significant bit.\n"
4671 "\n"
4672 "@lisp\n"
4673 "(logbit? 0 #b1101) @result{} #t\n"
4674 "(logbit? 1 #b1101) @result{} #f\n"
4675 "(logbit? 2 #b1101) @result{} #t\n"
4676 "(logbit? 3 #b1101) @result{} #t\n"
4677 "(logbit? 4 #b1101) @result{} #f\n"
4678 "@end lisp")
4679 #define FUNC_NAME s_scm_logbit_p
4680 {
4681 unsigned long int iindex;
4682 iindex = scm_to_ulong (index);
4683
4684 if (SCM_I_INUMP (j))
4685 {
4686 /* bits above what's in an inum follow the sign bit */
4687 iindex = min (iindex, SCM_LONG_BIT - 1);
4688 return scm_from_bool ((1L << iindex) & SCM_I_INUM (j));
4689 }
4690 else if (SCM_BIGP (j))
4691 {
4692 int val = mpz_tstbit (SCM_I_BIG_MPZ (j), iindex);
4693 scm_remember_upto_here_1 (j);
4694 return scm_from_bool (val);
4695 }
4696 else
4697 SCM_WRONG_TYPE_ARG (SCM_ARG2, j);
4698 }
4699 #undef FUNC_NAME
4700
4701
4702 SCM_DEFINE (scm_lognot, "lognot", 1, 0, 0,
4703 (SCM n),
4704 "Return the integer which is the ones-complement of the integer\n"
4705 "argument.\n"
4706 "\n"
4707 "@lisp\n"
4708 "(number->string (lognot #b10000000) 2)\n"
4709 " @result{} \"-10000001\"\n"
4710 "(number->string (lognot #b0) 2)\n"
4711 " @result{} \"-1\"\n"
4712 "@end lisp")
4713 #define FUNC_NAME s_scm_lognot
4714 {
4715 if (SCM_I_INUMP (n)) {
4716 /* No overflow here, just need to toggle all the bits making up the inum.
4717 Enhancement: No need to strip the tag and add it back, could just xor
4718 a block of 1 bits, if that worked with the various debug versions of
4719 the SCM typedef. */
4720 return SCM_I_MAKINUM (~ SCM_I_INUM (n));
4721
4722 } else if (SCM_BIGP (n)) {
4723 SCM result = scm_i_mkbig ();
4724 mpz_com (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (n));
4725 scm_remember_upto_here_1 (n);
4726 return result;
4727
4728 } else {
4729 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
4730 }
4731 }
4732 #undef FUNC_NAME
4733
4734 /* returns 0 if IN is not an integer. OUT must already be
4735 initialized. */
4736 static int
4737 coerce_to_big (SCM in, mpz_t out)
4738 {
4739 if (SCM_BIGP (in))
4740 mpz_set (out, SCM_I_BIG_MPZ (in));
4741 else if (SCM_I_INUMP (in))
4742 mpz_set_si (out, SCM_I_INUM (in));
4743 else
4744 return 0;
4745
4746 return 1;
4747 }
4748
4749 SCM_DEFINE (scm_modulo_expt, "modulo-expt", 3, 0, 0,
4750 (SCM n, SCM k, SCM m),
4751 "Return @var{n} raised to the integer exponent\n"
4752 "@var{k}, modulo @var{m}.\n"
4753 "\n"
4754 "@lisp\n"
4755 "(modulo-expt 2 3 5)\n"
4756 " @result{} 3\n"
4757 "@end lisp")
4758 #define FUNC_NAME s_scm_modulo_expt
4759 {
4760 mpz_t n_tmp;
4761 mpz_t k_tmp;
4762 mpz_t m_tmp;
4763
4764 /* There are two classes of error we might encounter --
4765 1) Math errors, which we'll report by calling scm_num_overflow,
4766 and
4767 2) wrong-type errors, which of course we'll report by calling
4768 SCM_WRONG_TYPE_ARG.
4769 We don't report those errors immediately, however; instead we do
4770 some cleanup first. These variables tell us which error (if
4771 any) we should report after cleaning up.
4772 */
4773 int report_overflow = 0;
4774
4775 int position_of_wrong_type = 0;
4776 SCM value_of_wrong_type = SCM_INUM0;
4777
4778 SCM result = SCM_UNDEFINED;
4779
4780 mpz_init (n_tmp);
4781 mpz_init (k_tmp);
4782 mpz_init (m_tmp);
4783
4784 if (scm_is_eq (m, SCM_INUM0))
4785 {
4786 report_overflow = 1;
4787 goto cleanup;
4788 }
4789
4790 if (!coerce_to_big (n, n_tmp))
4791 {
4792 value_of_wrong_type = n;
4793 position_of_wrong_type = 1;
4794 goto cleanup;
4795 }
4796
4797 if (!coerce_to_big (k, k_tmp))
4798 {
4799 value_of_wrong_type = k;
4800 position_of_wrong_type = 2;
4801 goto cleanup;
4802 }
4803
4804 if (!coerce_to_big (m, m_tmp))
4805 {
4806 value_of_wrong_type = m;
4807 position_of_wrong_type = 3;
4808 goto cleanup;
4809 }
4810
4811 /* if the exponent K is negative, and we simply call mpz_powm, we
4812 will get a divide-by-zero exception when an inverse 1/n mod m
4813 doesn't exist (or is not unique). Since exceptions are hard to
4814 handle, we'll attempt the inversion "by hand" -- that way, we get
4815 a simple failure code, which is easy to handle. */
4816
4817 if (-1 == mpz_sgn (k_tmp))
4818 {
4819 if (!mpz_invert (n_tmp, n_tmp, m_tmp))
4820 {
4821 report_overflow = 1;
4822 goto cleanup;
4823 }
4824 mpz_neg (k_tmp, k_tmp);
4825 }
4826
4827 result = scm_i_mkbig ();
4828 mpz_powm (SCM_I_BIG_MPZ (result),
4829 n_tmp,
4830 k_tmp,
4831 m_tmp);
4832
4833 if (mpz_sgn (m_tmp) < 0 && mpz_sgn (SCM_I_BIG_MPZ (result)) != 0)
4834 mpz_add (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result), m_tmp);
4835
4836 cleanup:
4837 mpz_clear (m_tmp);
4838 mpz_clear (k_tmp);
4839 mpz_clear (n_tmp);
4840
4841 if (report_overflow)
4842 scm_num_overflow (FUNC_NAME);
4843
4844 if (position_of_wrong_type)
4845 SCM_WRONG_TYPE_ARG (position_of_wrong_type,
4846 value_of_wrong_type);
4847
4848 return scm_i_normbig (result);
4849 }
4850 #undef FUNC_NAME
4851
4852 SCM_DEFINE (scm_integer_expt, "integer-expt", 2, 0, 0,
4853 (SCM n, SCM k),
4854 "Return @var{n} raised to the power @var{k}. @var{k} must be an\n"
4855 "exact integer, @var{n} can be any number.\n"
4856 "\n"
4857 "Negative @var{k} is supported, and results in\n"
4858 "@math{1/@var{n}^abs(@var{k})} in the usual way.\n"
4859 "@math{@var{n}^0} is 1, as usual, and that\n"
4860 "includes @math{0^0} is 1.\n"
4861 "\n"
4862 "@lisp\n"
4863 "(integer-expt 2 5) @result{} 32\n"
4864 "(integer-expt -3 3) @result{} -27\n"
4865 "(integer-expt 5 -3) @result{} 1/125\n"
4866 "(integer-expt 0 0) @result{} 1\n"
4867 "@end lisp")
4868 #define FUNC_NAME s_scm_integer_expt
4869 {
4870 scm_t_inum i2 = 0;
4871 SCM z_i2 = SCM_BOOL_F;
4872 int i2_is_big = 0;
4873 SCM acc = SCM_I_MAKINUM (1L);
4874
4875 /* Specifically refrain from checking the type of the first argument.
4876 This allows us to exponentiate any object that can be multiplied.
4877 If we must raise to a negative power, we must also be able to
4878 take its reciprocal. */
4879 if (!SCM_LIKELY (SCM_I_INUMP (k)) && !SCM_LIKELY (SCM_BIGP (k)))
4880 SCM_WRONG_TYPE_ARG (2, k);
4881
4882 if (SCM_UNLIKELY (scm_is_eq (k, SCM_INUM0)))
4883 return SCM_INUM1; /* n^(exact0) is exact 1, regardless of n */
4884 else if (SCM_UNLIKELY (scm_is_eq (n, SCM_I_MAKINUM (-1L))))
4885 return scm_is_false (scm_even_p (k)) ? n : SCM_INUM1;
4886 /* The next check is necessary only because R6RS specifies different
4887 behavior for 0^(-k) than for (/ 0). If n is not a scheme number,
4888 we simply skip this case and move on. */
4889 else if (SCM_NUMBERP (n) && scm_is_true (scm_zero_p (n)))
4890 {
4891 /* k cannot be 0 at this point, because we
4892 have already checked for that case above */
4893 if (scm_is_true (scm_positive_p (k)))
4894 return n;
4895 else /* return NaN for (0 ^ k) for negative k per R6RS */
4896 return scm_nan ();
4897 }
4898 else if (SCM_FRACTIONP (n))
4899 {
4900 /* Optimize the fraction case by (a/b)^k ==> (a^k)/(b^k), to avoid
4901 needless reduction of intermediate products to lowest terms.
4902 If a and b have no common factors, then a^k and b^k have no
4903 common factors. Use 'scm_i_make_ratio_already_reduced' to
4904 construct the final result, so that no gcd computations are
4905 needed to exponentiate a fraction. */
4906 if (scm_is_true (scm_positive_p (k)))
4907 return scm_i_make_ratio_already_reduced
4908 (scm_integer_expt (SCM_FRACTION_NUMERATOR (n), k),
4909 scm_integer_expt (SCM_FRACTION_DENOMINATOR (n), k));
4910 else
4911 {
4912 k = scm_difference (k, SCM_UNDEFINED);
4913 return scm_i_make_ratio_already_reduced
4914 (scm_integer_expt (SCM_FRACTION_DENOMINATOR (n), k),
4915 scm_integer_expt (SCM_FRACTION_NUMERATOR (n), k));
4916 }
4917 }
4918
4919 if (SCM_I_INUMP (k))
4920 i2 = SCM_I_INUM (k);
4921 else if (SCM_BIGP (k))
4922 {
4923 z_i2 = scm_i_clonebig (k, 1);
4924 scm_remember_upto_here_1 (k);
4925 i2_is_big = 1;
4926 }
4927 else
4928 SCM_WRONG_TYPE_ARG (2, k);
4929
4930 if (i2_is_big)
4931 {
4932 if (mpz_sgn(SCM_I_BIG_MPZ (z_i2)) == -1)
4933 {
4934 mpz_neg (SCM_I_BIG_MPZ (z_i2), SCM_I_BIG_MPZ (z_i2));
4935 n = scm_divide (n, SCM_UNDEFINED);
4936 }
4937 while (1)
4938 {
4939 if (mpz_sgn(SCM_I_BIG_MPZ (z_i2)) == 0)
4940 {
4941 return acc;
4942 }
4943 if (mpz_cmp_ui(SCM_I_BIG_MPZ (z_i2), 1) == 0)
4944 {
4945 return scm_product (acc, n);
4946 }
4947 if (mpz_tstbit(SCM_I_BIG_MPZ (z_i2), 0))
4948 acc = scm_product (acc, n);
4949 n = scm_product (n, n);
4950 mpz_fdiv_q_2exp (SCM_I_BIG_MPZ (z_i2), SCM_I_BIG_MPZ (z_i2), 1);
4951 }
4952 }
4953 else
4954 {
4955 if (i2 < 0)
4956 {
4957 i2 = -i2;
4958 n = scm_divide (n, SCM_UNDEFINED);
4959 }
4960 while (1)
4961 {
4962 if (0 == i2)
4963 return acc;
4964 if (1 == i2)
4965 return scm_product (acc, n);
4966 if (i2 & 1)
4967 acc = scm_product (acc, n);
4968 n = scm_product (n, n);
4969 i2 >>= 1;
4970 }
4971 }
4972 }
4973 #undef FUNC_NAME
4974
4975 /* Efficiently compute (N * 2^COUNT),
4976 where N is an exact integer, and COUNT > 0. */
4977 static SCM
4978 left_shift_exact_integer (SCM n, long count)
4979 {
4980 if (SCM_I_INUMP (n))
4981 {
4982 scm_t_inum nn = SCM_I_INUM (n);
4983
4984 /* Left shift of count >= SCM_I_FIXNUM_BIT-1 will always
4985 overflow a non-zero fixnum. For smaller shifts we check the
4986 bits going into positions above SCM_I_FIXNUM_BIT-1. If they're
4987 all 0s for nn>=0, or all 1s for nn<0 then there's no overflow.
4988 Those bits are "nn >> (SCM_I_FIXNUM_BIT-1 - count)". */
4989
4990 if (nn == 0)
4991 return n;
4992 else if (count < SCM_I_FIXNUM_BIT-1 &&
4993 ((scm_t_bits) (SCM_SRS (nn, (SCM_I_FIXNUM_BIT-1 - count)) + 1)
4994 <= 1))
4995 return SCM_I_MAKINUM (nn << count);
4996 else
4997 {
4998 SCM result = scm_i_inum2big (nn);
4999 mpz_mul_2exp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result),
5000 count);
5001 return result;
5002 }
5003 }
5004 else if (SCM_BIGP (n))
5005 {
5006 SCM result = scm_i_mkbig ();
5007 mpz_mul_2exp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (n), count);
5008 scm_remember_upto_here_1 (n);
5009 return result;
5010 }
5011 else
5012 scm_syserror ("left_shift_exact_integer");
5013 }
5014
5015 /* Efficiently compute floor (N / 2^COUNT),
5016 where N is an exact integer and COUNT > 0. */
5017 static SCM
5018 floor_right_shift_exact_integer (SCM n, long count)
5019 {
5020 if (SCM_I_INUMP (n))
5021 {
5022 scm_t_inum nn = SCM_I_INUM (n);
5023
5024 if (count >= SCM_I_FIXNUM_BIT)
5025 return (nn >= 0 ? SCM_INUM0 : SCM_I_MAKINUM (-1));
5026 else
5027 return SCM_I_MAKINUM (SCM_SRS (nn, count));
5028 }
5029 else if (SCM_BIGP (n))
5030 {
5031 SCM result = scm_i_mkbig ();
5032 mpz_fdiv_q_2exp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (n),
5033 count);
5034 scm_remember_upto_here_1 (n);
5035 return scm_i_normbig (result);
5036 }
5037 else
5038 scm_syserror ("floor_right_shift_exact_integer");
5039 }
5040
5041 /* Efficiently compute round (N / 2^COUNT),
5042 where N is an exact integer and COUNT > 0. */
5043 static SCM
5044 round_right_shift_exact_integer (SCM n, long count)
5045 {
5046 if (SCM_I_INUMP (n))
5047 {
5048 if (count >= SCM_I_FIXNUM_BIT)
5049 return SCM_INUM0;
5050 else
5051 {
5052 scm_t_inum nn = SCM_I_INUM (n);
5053 scm_t_inum qq = SCM_SRS (nn, count);
5054
5055 if (0 == (nn & (1L << (count-1))))
5056 return SCM_I_MAKINUM (qq); /* round down */
5057 else if (nn & ((1L << (count-1)) - 1))
5058 return SCM_I_MAKINUM (qq + 1); /* round up */
5059 else
5060 return SCM_I_MAKINUM ((~1L) & (qq + 1)); /* round to even */
5061 }
5062 }
5063 else if (SCM_BIGP (n))
5064 {
5065 SCM q = scm_i_mkbig ();
5066
5067 mpz_fdiv_q_2exp (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (n), count);
5068 if (mpz_tstbit (SCM_I_BIG_MPZ (n), count-1)
5069 && (mpz_odd_p (SCM_I_BIG_MPZ (q))
5070 || (mpz_scan1 (SCM_I_BIG_MPZ (n), 0) < count-1)))
5071 mpz_add_ui (SCM_I_BIG_MPZ (q), SCM_I_BIG_MPZ (q), 1);
5072 scm_remember_upto_here_1 (n);
5073 return scm_i_normbig (q);
5074 }
5075 else
5076 scm_syserror ("round_right_shift_exact_integer");
5077 }
5078
5079 SCM_DEFINE (scm_ash, "ash", 2, 0, 0,
5080 (SCM n, SCM count),
5081 "Return @math{floor(@var{n} * 2^@var{count})}.\n"
5082 "@var{n} and @var{count} must be exact integers.\n"
5083 "\n"
5084 "With @var{n} viewed as an infinite-precision twos-complement\n"
5085 "integer, @code{ash} means a left shift introducing zero bits\n"
5086 "when @var{count} is positive, or a right shift dropping bits\n"
5087 "when @var{count} is negative. This is an ``arithmetic'' shift.\n"
5088 "\n"
5089 "@lisp\n"
5090 "(number->string (ash #b1 3) 2) @result{} \"1000\"\n"
5091 "(number->string (ash #b1010 -1) 2) @result{} \"101\"\n"
5092 "\n"
5093 ";; -23 is bits ...11101001, -6 is bits ...111010\n"
5094 "(ash -23 -2) @result{} -6\n"
5095 "@end lisp")
5096 #define FUNC_NAME s_scm_ash
5097 {
5098 if (SCM_I_INUMP (n) || SCM_BIGP (n))
5099 {
5100 long bits_to_shift = scm_to_long (count);
5101
5102 if (bits_to_shift > 0)
5103 return left_shift_exact_integer (n, bits_to_shift);
5104 else if (SCM_LIKELY (bits_to_shift < 0))
5105 return floor_right_shift_exact_integer (n, -bits_to_shift);
5106 else
5107 return n;
5108 }
5109 else
5110 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
5111 }
5112 #undef FUNC_NAME
5113
5114 SCM_DEFINE (scm_round_ash, "round-ash", 2, 0, 0,
5115 (SCM n, SCM count),
5116 "Return @math{round(@var{n} * 2^@var{count})}.\n"
5117 "@var{n} and @var{count} must be exact integers.\n"
5118 "\n"
5119 "With @var{n} viewed as an infinite-precision twos-complement\n"
5120 "integer, @code{round-ash} means a left shift introducing zero\n"
5121 "bits when @var{count} is positive, or a right shift rounding\n"
5122 "to the nearest integer (with ties going to the nearest even\n"
5123 "integer) when @var{count} is negative. This is a rounded\n"
5124 "``arithmetic'' shift.\n"
5125 "\n"
5126 "@lisp\n"
5127 "(number->string (round-ash #b1 3) 2) @result{} \"1000\"\n"
5128 "(number->string (round-ash #b1010 -1) 2) @result{} \"101\"\n"
5129 "(number->string (round-ash #b1010 -2) 2) @result{} \"10\"\n"
5130 "(number->string (round-ash #b1011 -2) 2) @result{} \"11\"\n"
5131 "(number->string (round-ash #b1101 -2) 2) @result{} \"11\"\n"
5132 "(number->string (round-ash #b1110 -2) 2) @result{} \"100\"\n"
5133 "@end lisp")
5134 #define FUNC_NAME s_scm_round_ash
5135 {
5136 if (SCM_I_INUMP (n) || SCM_BIGP (n))
5137 {
5138 long bits_to_shift = scm_to_long (count);
5139
5140 if (bits_to_shift > 0)
5141 return left_shift_exact_integer (n, bits_to_shift);
5142 else if (SCM_LIKELY (bits_to_shift < 0))
5143 return round_right_shift_exact_integer (n, -bits_to_shift);
5144 else
5145 return n;
5146 }
5147 else
5148 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
5149 }
5150 #undef FUNC_NAME
5151
5152
5153 SCM_DEFINE (scm_bit_extract, "bit-extract", 3, 0, 0,
5154 (SCM n, SCM start, SCM end),
5155 "Return the integer composed of the @var{start} (inclusive)\n"
5156 "through @var{end} (exclusive) bits of @var{n}. The\n"
5157 "@var{start}th bit becomes the 0-th bit in the result.\n"
5158 "\n"
5159 "@lisp\n"
5160 "(number->string (bit-extract #b1101101010 0 4) 2)\n"
5161 " @result{} \"1010\"\n"
5162 "(number->string (bit-extract #b1101101010 4 9) 2)\n"
5163 " @result{} \"10110\"\n"
5164 "@end lisp")
5165 #define FUNC_NAME s_scm_bit_extract
5166 {
5167 unsigned long int istart, iend, bits;
5168 istart = scm_to_ulong (start);
5169 iend = scm_to_ulong (end);
5170 SCM_ASSERT_RANGE (3, end, (iend >= istart));
5171
5172 /* how many bits to keep */
5173 bits = iend - istart;
5174
5175 if (SCM_I_INUMP (n))
5176 {
5177 scm_t_inum in = SCM_I_INUM (n);
5178
5179 /* When istart>=SCM_I_FIXNUM_BIT we can just limit the shift to
5180 SCM_I_FIXNUM_BIT-1 to get either 0 or -1 per the sign of "in". */
5181 in = SCM_SRS (in, min (istart, SCM_I_FIXNUM_BIT-1));
5182
5183 if (in < 0 && bits >= SCM_I_FIXNUM_BIT)
5184 {
5185 /* Since we emulate two's complement encoded numbers, this
5186 * special case requires us to produce a result that has
5187 * more bits than can be stored in a fixnum.
5188 */
5189 SCM result = scm_i_inum2big (in);
5190 mpz_fdiv_r_2exp (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result),
5191 bits);
5192 return result;
5193 }
5194
5195 /* mask down to requisite bits */
5196 bits = min (bits, SCM_I_FIXNUM_BIT);
5197 return SCM_I_MAKINUM (in & ((1L << bits) - 1));
5198 }
5199 else if (SCM_BIGP (n))
5200 {
5201 SCM result;
5202 if (bits == 1)
5203 {
5204 result = SCM_I_MAKINUM (mpz_tstbit (SCM_I_BIG_MPZ (n), istart));
5205 }
5206 else
5207 {
5208 /* ENHANCE-ME: It'd be nice not to allocate a new bignum when
5209 bits<SCM_I_FIXNUM_BIT. Would want some help from GMP to get
5210 such bits into a ulong. */
5211 result = scm_i_mkbig ();
5212 mpz_fdiv_q_2exp (SCM_I_BIG_MPZ(result), SCM_I_BIG_MPZ(n), istart);
5213 mpz_fdiv_r_2exp (SCM_I_BIG_MPZ(result), SCM_I_BIG_MPZ(result), bits);
5214 result = scm_i_normbig (result);
5215 }
5216 scm_remember_upto_here_1 (n);
5217 return result;
5218 }
5219 else
5220 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
5221 }
5222 #undef FUNC_NAME
5223
5224
5225 static const char scm_logtab[] = {
5226 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
5227 };
5228
5229 SCM_DEFINE (scm_logcount, "logcount", 1, 0, 0,
5230 (SCM n),
5231 "Return the number of bits in integer @var{n}. If integer is\n"
5232 "positive, the 1-bits in its binary representation are counted.\n"
5233 "If negative, the 0-bits in its two's-complement binary\n"
5234 "representation are counted. If 0, 0 is returned.\n"
5235 "\n"
5236 "@lisp\n"
5237 "(logcount #b10101010)\n"
5238 " @result{} 4\n"
5239 "(logcount 0)\n"
5240 " @result{} 0\n"
5241 "(logcount -2)\n"
5242 " @result{} 1\n"
5243 "@end lisp")
5244 #define FUNC_NAME s_scm_logcount
5245 {
5246 if (SCM_I_INUMP (n))
5247 {
5248 unsigned long c = 0;
5249 scm_t_inum nn = SCM_I_INUM (n);
5250 if (nn < 0)
5251 nn = -1 - nn;
5252 while (nn)
5253 {
5254 c += scm_logtab[15 & nn];
5255 nn >>= 4;
5256 }
5257 return SCM_I_MAKINUM (c);
5258 }
5259 else if (SCM_BIGP (n))
5260 {
5261 unsigned long count;
5262 if (mpz_sgn (SCM_I_BIG_MPZ (n)) >= 0)
5263 count = mpz_popcount (SCM_I_BIG_MPZ (n));
5264 else
5265 count = mpz_hamdist (SCM_I_BIG_MPZ (n), z_negative_one);
5266 scm_remember_upto_here_1 (n);
5267 return SCM_I_MAKINUM (count);
5268 }
5269 else
5270 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
5271 }
5272 #undef FUNC_NAME
5273
5274
5275 static const char scm_ilentab[] = {
5276 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4
5277 };
5278
5279
5280 SCM_DEFINE (scm_integer_length, "integer-length", 1, 0, 0,
5281 (SCM n),
5282 "Return the number of bits necessary to represent @var{n}.\n"
5283 "\n"
5284 "@lisp\n"
5285 "(integer-length #b10101010)\n"
5286 " @result{} 8\n"
5287 "(integer-length 0)\n"
5288 " @result{} 0\n"
5289 "(integer-length #b1111)\n"
5290 " @result{} 4\n"
5291 "@end lisp")
5292 #define FUNC_NAME s_scm_integer_length
5293 {
5294 if (SCM_I_INUMP (n))
5295 {
5296 unsigned long c = 0;
5297 unsigned int l = 4;
5298 scm_t_inum nn = SCM_I_INUM (n);
5299 if (nn < 0)
5300 nn = -1 - nn;
5301 while (nn)
5302 {
5303 c += 4;
5304 l = scm_ilentab [15 & nn];
5305 nn >>= 4;
5306 }
5307 return SCM_I_MAKINUM (c - 4 + l);
5308 }
5309 else if (SCM_BIGP (n))
5310 {
5311 /* mpz_sizeinbase looks at the absolute value of negatives, whereas we
5312 want a ones-complement. If n is ...111100..00 then mpz_sizeinbase is
5313 1 too big, so check for that and adjust. */
5314 size_t size = mpz_sizeinbase (SCM_I_BIG_MPZ (n), 2);
5315 if (mpz_sgn (SCM_I_BIG_MPZ (n)) < 0
5316 && mpz_scan0 (SCM_I_BIG_MPZ (n), /* no 0 bits above the lowest 1 */
5317 mpz_scan1 (SCM_I_BIG_MPZ (n), 0)) == ULONG_MAX)
5318 size--;
5319 scm_remember_upto_here_1 (n);
5320 return SCM_I_MAKINUM (size);
5321 }
5322 else
5323 SCM_WRONG_TYPE_ARG (SCM_ARG1, n);
5324 }
5325 #undef FUNC_NAME
5326
5327 /*** NUMBERS -> STRINGS ***/
5328 #define SCM_MAX_DBL_RADIX 36
5329
5330 /* use this array as a way to generate a single digit */
5331 static const char number_chars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
5332
5333 static mpz_t dbl_minimum_normal_mantissa;
5334
5335 static size_t
5336 idbl2str (double dbl, char *a, int radix)
5337 {
5338 int ch = 0;
5339
5340 if (radix < 2 || radix > SCM_MAX_DBL_RADIX)
5341 /* revert to existing behavior */
5342 radix = 10;
5343
5344 if (isinf (dbl))
5345 {
5346 strcpy (a, (dbl > 0.0) ? "+inf.0" : "-inf.0");
5347 return 6;
5348 }
5349 else if (dbl > 0.0)
5350 ;
5351 else if (dbl < 0.0)
5352 {
5353 dbl = -dbl;
5354 a[ch++] = '-';
5355 }
5356 else if (dbl == 0.0)
5357 {
5358 if (!double_is_non_negative_zero (dbl))
5359 a[ch++] = '-';
5360 strcpy (a + ch, "0.0");
5361 return ch + 3;
5362 }
5363 else if (isnan (dbl))
5364 {
5365 strcpy (a, "+nan.0");
5366 return 6;
5367 }
5368
5369 /* Algorithm taken from "Printing Floating-Point Numbers Quickly and
5370 Accurately" by Robert G. Burger and R. Kent Dybvig */
5371 {
5372 int e, k;
5373 mpz_t f, r, s, mplus, mminus, hi, digit;
5374 int f_is_even, f_is_odd;
5375 int expon;
5376 int show_exp = 0;
5377
5378 mpz_inits (f, r, s, mplus, mminus, hi, digit, NULL);
5379 mpz_set_d (f, ldexp (frexp (dbl, &e), DBL_MANT_DIG));
5380 if (e < DBL_MIN_EXP)
5381 {
5382 mpz_tdiv_q_2exp (f, f, DBL_MIN_EXP - e);
5383 e = DBL_MIN_EXP;
5384 }
5385 e -= DBL_MANT_DIG;
5386
5387 f_is_even = !mpz_odd_p (f);
5388 f_is_odd = !f_is_even;
5389
5390 /* Initialize r, s, mplus, and mminus according
5391 to Table 1 from the paper. */
5392 if (e < 0)
5393 {
5394 mpz_set_ui (mminus, 1);
5395 if (mpz_cmp (f, dbl_minimum_normal_mantissa) != 0
5396 || e == DBL_MIN_EXP - DBL_MANT_DIG)
5397 {
5398 mpz_set_ui (mplus, 1);
5399 mpz_mul_2exp (r, f, 1);
5400 mpz_mul_2exp (s, mminus, 1 - e);
5401 }
5402 else
5403 {
5404 mpz_set_ui (mplus, 2);
5405 mpz_mul_2exp (r, f, 2);
5406 mpz_mul_2exp (s, mminus, 2 - e);
5407 }
5408 }
5409 else
5410 {
5411 mpz_set_ui (mminus, 1);
5412 mpz_mul_2exp (mminus, mminus, e);
5413 if (mpz_cmp (f, dbl_minimum_normal_mantissa) != 0)
5414 {
5415 mpz_set (mplus, mminus);
5416 mpz_mul_2exp (r, f, 1 + e);
5417 mpz_set_ui (s, 2);
5418 }
5419 else
5420 {
5421 mpz_mul_2exp (mplus, mminus, 1);
5422 mpz_mul_2exp (r, f, 2 + e);
5423 mpz_set_ui (s, 4);
5424 }
5425 }
5426
5427 /* Find the smallest k such that:
5428 (r + mplus) / s < radix^k (if f is even)
5429 (r + mplus) / s <= radix^k (if f is odd) */
5430 {
5431 /* IMPROVE-ME: Make an initial guess to speed this up */
5432 mpz_add (hi, r, mplus);
5433 k = 0;
5434 while (mpz_cmp (hi, s) >= f_is_odd)
5435 {
5436 mpz_mul_ui (s, s, radix);
5437 k++;
5438 }
5439 if (k == 0)
5440 {
5441 mpz_mul_ui (hi, hi, radix);
5442 while (mpz_cmp (hi, s) < f_is_odd)
5443 {
5444 mpz_mul_ui (r, r, radix);
5445 mpz_mul_ui (mplus, mplus, radix);
5446 mpz_mul_ui (mminus, mminus, radix);
5447 mpz_mul_ui (hi, hi, radix);
5448 k--;
5449 }
5450 }
5451 }
5452
5453 expon = k - 1;
5454 if (k <= 0)
5455 {
5456 if (k <= -3)
5457 {
5458 /* Use scientific notation */
5459 show_exp = 1;
5460 k = 1;
5461 }
5462 else
5463 {
5464 int i;
5465
5466 /* Print leading zeroes */
5467 a[ch++] = '0';
5468 a[ch++] = '.';
5469 for (i = 0; i > k; i--)
5470 a[ch++] = '0';
5471 }
5472 }
5473
5474 for (;;)
5475 {
5476 int end_1_p, end_2_p;
5477 int d;
5478
5479 mpz_mul_ui (mplus, mplus, radix);
5480 mpz_mul_ui (mminus, mminus, radix);
5481 mpz_mul_ui (r, r, radix);
5482 mpz_fdiv_qr (digit, r, r, s);
5483 d = mpz_get_ui (digit);
5484
5485 mpz_add (hi, r, mplus);
5486 end_1_p = (mpz_cmp (r, mminus) < f_is_even);
5487 end_2_p = (mpz_cmp (s, hi) < f_is_even);
5488 if (end_1_p || end_2_p)
5489 {
5490 mpz_mul_2exp (r, r, 1);
5491 if (!end_2_p)
5492 ;
5493 else if (!end_1_p)
5494 d++;
5495 else if (mpz_cmp (r, s) >= !(d & 1))
5496 d++;
5497 a[ch++] = number_chars[d];
5498 if (--k == 0)
5499 a[ch++] = '.';
5500 break;
5501 }
5502 else
5503 {
5504 a[ch++] = number_chars[d];
5505 if (--k == 0)
5506 a[ch++] = '.';
5507 }
5508 }
5509
5510 if (k > 0)
5511 {
5512 if (expon >= 7 && k >= 4 && expon >= k)
5513 {
5514 /* Here we would have to print more than three zeroes
5515 followed by a decimal point and another zero. It
5516 makes more sense to use scientific notation. */
5517
5518 /* Adjust k to what it would have been if we had chosen
5519 scientific notation from the beginning. */
5520 k -= expon;
5521
5522 /* k will now be <= 0, with magnitude equal to the number of
5523 digits that we printed which should now be put after the
5524 decimal point. */
5525
5526 /* Insert a decimal point */
5527 memmove (a + ch + k + 1, a + ch + k, -k);
5528 a[ch + k] = '.';
5529 ch++;
5530
5531 show_exp = 1;
5532 }
5533 else
5534 {
5535 for (; k > 0; k--)
5536 a[ch++] = '0';
5537 a[ch++] = '.';
5538 }
5539 }
5540
5541 if (k == 0)
5542 a[ch++] = '0';
5543
5544 if (show_exp)
5545 {
5546 a[ch++] = 'e';
5547 ch += scm_iint2str (expon, radix, a + ch);
5548 }
5549
5550 mpz_clears (f, r, s, mplus, mminus, hi, digit, NULL);
5551 }
5552 return ch;
5553 }
5554
5555
5556 static size_t
5557 icmplx2str (double real, double imag, char *str, int radix)
5558 {
5559 size_t i;
5560 double sgn;
5561
5562 i = idbl2str (real, str, radix);
5563 #ifdef HAVE_COPYSIGN
5564 sgn = copysign (1.0, imag);
5565 #else
5566 sgn = imag;
5567 #endif
5568 /* Don't output a '+' for negative numbers or for Inf and
5569 NaN. They will provide their own sign. */
5570 if (sgn >= 0 && DOUBLE_IS_FINITE (imag))
5571 str[i++] = '+';
5572 i += idbl2str (imag, &str[i], radix);
5573 str[i++] = 'i';
5574 return i;
5575 }
5576
5577 static size_t
5578 iflo2str (SCM flt, char *str, int radix)
5579 {
5580 size_t i;
5581 if (SCM_REALP (flt))
5582 i = idbl2str (SCM_REAL_VALUE (flt), str, radix);
5583 else
5584 i = icmplx2str (SCM_COMPLEX_REAL (flt), SCM_COMPLEX_IMAG (flt),
5585 str, radix);
5586 return i;
5587 }
5588
5589 /* convert a scm_t_intmax to a string (unterminated). returns the number of
5590 characters in the result.
5591 rad is output base
5592 p is destination: worst case (base 2) is SCM_INTBUFLEN */
5593 size_t
5594 scm_iint2str (scm_t_intmax num, int rad, char *p)
5595 {
5596 if (num < 0)
5597 {
5598 *p++ = '-';
5599 return scm_iuint2str (-num, rad, p) + 1;
5600 }
5601 else
5602 return scm_iuint2str (num, rad, p);
5603 }
5604
5605 /* convert a scm_t_intmax to a string (unterminated). returns the number of
5606 characters in the result.
5607 rad is output base
5608 p is destination: worst case (base 2) is SCM_INTBUFLEN */
5609 size_t
5610 scm_iuint2str (scm_t_uintmax num, int rad, char *p)
5611 {
5612 size_t j = 1;
5613 size_t i;
5614 scm_t_uintmax n = num;
5615
5616 if (rad < 2 || rad > 36)
5617 scm_out_of_range ("scm_iuint2str", scm_from_int (rad));
5618
5619 for (n /= rad; n > 0; n /= rad)
5620 j++;
5621
5622 i = j;
5623 n = num;
5624 while (i--)
5625 {
5626 int d = n % rad;
5627
5628 n /= rad;
5629 p[i] = number_chars[d];
5630 }
5631 return j;
5632 }
5633
5634 SCM_DEFINE (scm_number_to_string, "number->string", 1, 1, 0,
5635 (SCM n, SCM radix),
5636 "Return a string holding the external representation of the\n"
5637 "number @var{n} in the given @var{radix}. If @var{n} is\n"
5638 "inexact, a radix of 10 will be used.")
5639 #define FUNC_NAME s_scm_number_to_string
5640 {
5641 int base;
5642
5643 if (SCM_UNBNDP (radix))
5644 base = 10;
5645 else
5646 base = scm_to_signed_integer (radix, 2, 36);
5647
5648 if (SCM_I_INUMP (n))
5649 {
5650 char num_buf [SCM_INTBUFLEN];
5651 size_t length = scm_iint2str (SCM_I_INUM (n), base, num_buf);
5652 return scm_from_locale_stringn (num_buf, length);
5653 }
5654 else if (SCM_BIGP (n))
5655 {
5656 char *str = mpz_get_str (NULL, base, SCM_I_BIG_MPZ (n));
5657 size_t len = strlen (str);
5658 void (*freefunc) (void *, size_t);
5659 SCM ret;
5660 mp_get_memory_functions (NULL, NULL, &freefunc);
5661 scm_remember_upto_here_1 (n);
5662 ret = scm_from_latin1_stringn (str, len);
5663 freefunc (str, len + 1);
5664 return ret;
5665 }
5666 else if (SCM_FRACTIONP (n))
5667 {
5668 return scm_string_append (scm_list_3 (scm_number_to_string (SCM_FRACTION_NUMERATOR (n), radix),
5669 scm_from_locale_string ("/"),
5670 scm_number_to_string (SCM_FRACTION_DENOMINATOR (n), radix)));
5671 }
5672 else if (SCM_INEXACTP (n))
5673 {
5674 char num_buf [FLOBUFLEN];
5675 return scm_from_locale_stringn (num_buf, iflo2str (n, num_buf, base));
5676 }
5677 else
5678 SCM_WRONG_TYPE_ARG (1, n);
5679 }
5680 #undef FUNC_NAME
5681
5682
5683 /* These print routines used to be stubbed here so that scm_repl.c
5684 wouldn't need SCM_BIGDIG conditionals (pre GMP) */
5685
5686 int
5687 scm_print_real (SCM sexp, SCM port, scm_print_state *pstate SCM_UNUSED)
5688 {
5689 char num_buf[FLOBUFLEN];
5690 scm_lfwrite (num_buf, iflo2str (sexp, num_buf, 10), port);
5691 return !0;
5692 }
5693
5694 void
5695 scm_i_print_double (double val, SCM port)
5696 {
5697 char num_buf[FLOBUFLEN];
5698 scm_lfwrite (num_buf, idbl2str (val, num_buf, 10), port);
5699 }
5700
5701 int
5702 scm_print_complex (SCM sexp, SCM port, scm_print_state *pstate SCM_UNUSED)
5703
5704 {
5705 char num_buf[FLOBUFLEN];
5706 scm_lfwrite (num_buf, iflo2str (sexp, num_buf, 10), port);
5707 return !0;
5708 }
5709
5710 void
5711 scm_i_print_complex (double real, double imag, SCM port)
5712 {
5713 char num_buf[FLOBUFLEN];
5714 scm_lfwrite (num_buf, icmplx2str (real, imag, num_buf, 10), port);
5715 }
5716
5717 int
5718 scm_i_print_fraction (SCM sexp, SCM port, scm_print_state *pstate SCM_UNUSED)
5719 {
5720 SCM str;
5721 str = scm_number_to_string (sexp, SCM_UNDEFINED);
5722 scm_display (str, port);
5723 scm_remember_upto_here_1 (str);
5724 return !0;
5725 }
5726
5727 int
5728 scm_bigprint (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
5729 {
5730 char *str = mpz_get_str (NULL, 10, SCM_I_BIG_MPZ (exp));
5731 size_t len = strlen (str);
5732 void (*freefunc) (void *, size_t);
5733 mp_get_memory_functions (NULL, NULL, &freefunc);
5734 scm_remember_upto_here_1 (exp);
5735 scm_lfwrite (str, len, port);
5736 freefunc (str, len + 1);
5737 return !0;
5738 }
5739 /*** END nums->strs ***/
5740
5741
5742 /*** STRINGS -> NUMBERS ***/
5743
5744 /* The following functions implement the conversion from strings to numbers.
5745 * The implementation somehow follows the grammar for numbers as it is given
5746 * in R5RS. Thus, the functions resemble syntactic units (<ureal R>,
5747 * <uinteger R>, ...) that are used to build up numbers in the grammar. Some
5748 * points should be noted about the implementation:
5749 *
5750 * * Each function keeps a local index variable 'idx' that points at the
5751 * current position within the parsed string. The global index is only
5752 * updated if the function could parse the corresponding syntactic unit
5753 * successfully.
5754 *
5755 * * Similarly, the functions keep track of indicators of inexactness ('#',
5756 * '.' or exponents) using local variables ('hash_seen', 'x').
5757 *
5758 * * Sequences of digits are parsed into temporary variables holding fixnums.
5759 * Only if these fixnums would overflow, the result variables are updated
5760 * using the standard functions scm_add, scm_product, scm_divide etc. Then,
5761 * the temporary variables holding the fixnums are cleared, and the process
5762 * starts over again. If for example fixnums were able to store five decimal
5763 * digits, a number 1234567890 would be parsed in two parts 12345 and 67890,
5764 * and the result was computed as 12345 * 100000 + 67890. In other words,
5765 * only every five digits two bignum operations were performed.
5766 *
5767 * Notes on the handling of exactness specifiers:
5768 *
5769 * When parsing non-real complex numbers, we apply exactness specifiers on
5770 * per-component basis, as is done in PLT Scheme. For complex numbers
5771 * written in rectangular form, exactness specifiers are applied to the
5772 * real and imaginary parts before calling scm_make_rectangular. For
5773 * complex numbers written in polar form, exactness specifiers are applied
5774 * to the magnitude and angle before calling scm_make_polar.
5775 *
5776 * There are two kinds of exactness specifiers: forced and implicit. A
5777 * forced exactness specifier is a "#e" or "#i" prefix at the beginning of
5778 * the entire number, and applies to both components of a complex number.
5779 * "#e" causes each component to be made exact, and "#i" causes each
5780 * component to be made inexact. If no forced exactness specifier is
5781 * present, then the exactness of each component is determined
5782 * independently by the presence or absence of a decimal point or hash mark
5783 * within that component. If a decimal point or hash mark is present, the
5784 * component is made inexact, otherwise it is made exact.
5785 *
5786 * After the exactness specifiers have been applied to each component, they
5787 * are passed to either scm_make_rectangular or scm_make_polar to produce
5788 * the final result. Note that this will result in a real number if the
5789 * imaginary part, magnitude, or angle is an exact 0.
5790 *
5791 * For example, (string->number "#i5.0+0i") does the equivalent of:
5792 *
5793 * (make-rectangular (exact->inexact 5) (exact->inexact 0))
5794 */
5795
5796 enum t_exactness {NO_EXACTNESS, INEXACT, EXACT};
5797
5798 /* R5RS, section 7.1.1, lexical structure of numbers: <uinteger R>. */
5799
5800 /* Caller is responsible for checking that the return value is in range
5801 for the given radix, which should be <= 36. */
5802 static unsigned int
5803 char_decimal_value (scm_t_uint32 c)
5804 {
5805 /* uc_decimal_value returns -1 on error. When cast to an unsigned int,
5806 that's certainly above any valid decimal, so we take advantage of
5807 that to elide some tests. */
5808 unsigned int d = (unsigned int) uc_decimal_value (c);
5809
5810 /* If that failed, try extended hexadecimals, then. Only accept ascii
5811 hexadecimals. */
5812 if (d >= 10U)
5813 {
5814 c = uc_tolower (c);
5815 if (c >= (scm_t_uint32) 'a')
5816 d = c - (scm_t_uint32)'a' + 10U;
5817 }
5818 return d;
5819 }
5820
5821 /* Parse the substring of MEM starting at *P_IDX for an unsigned integer
5822 in base RADIX. Upon success, return the unsigned integer and update
5823 *P_IDX and *P_EXACTNESS accordingly. Return #f on failure. */
5824 static SCM
5825 mem2uinteger (SCM mem, unsigned int *p_idx,
5826 unsigned int radix, enum t_exactness *p_exactness)
5827 {
5828 unsigned int idx = *p_idx;
5829 unsigned int hash_seen = 0;
5830 scm_t_bits shift = 1;
5831 scm_t_bits add = 0;
5832 unsigned int digit_value;
5833 SCM result;
5834 char c;
5835 size_t len = scm_i_string_length (mem);
5836
5837 if (idx == len)
5838 return SCM_BOOL_F;
5839
5840 c = scm_i_string_ref (mem, idx);
5841 digit_value = char_decimal_value (c);
5842 if (digit_value >= radix)
5843 return SCM_BOOL_F;
5844
5845 idx++;
5846 result = SCM_I_MAKINUM (digit_value);
5847 while (idx != len)
5848 {
5849 scm_t_wchar c = scm_i_string_ref (mem, idx);
5850 if (c == '#')
5851 {
5852 hash_seen = 1;
5853 digit_value = 0;
5854 }
5855 else if (hash_seen)
5856 break;
5857 else
5858 {
5859 digit_value = char_decimal_value (c);
5860 /* This check catches non-decimals in addition to out-of-range
5861 decimals. */
5862 if (digit_value >= radix)
5863 break;
5864 }
5865
5866 idx++;
5867 if (SCM_MOST_POSITIVE_FIXNUM / radix < shift)
5868 {
5869 result = scm_product (result, SCM_I_MAKINUM (shift));
5870 if (add > 0)
5871 result = scm_sum (result, SCM_I_MAKINUM (add));
5872
5873 shift = radix;
5874 add = digit_value;
5875 }
5876 else
5877 {
5878 shift = shift * radix;
5879 add = add * radix + digit_value;
5880 }
5881 };
5882
5883 if (shift > 1)
5884 result = scm_product (result, SCM_I_MAKINUM (shift));
5885 if (add > 0)
5886 result = scm_sum (result, SCM_I_MAKINUM (add));
5887
5888 *p_idx = idx;
5889 if (hash_seen)
5890 *p_exactness = INEXACT;
5891
5892 return result;
5893 }
5894
5895
5896 /* R5RS, section 7.1.1, lexical structure of numbers: <decimal 10>. Only
5897 * covers the parts of the rules that start at a potential point. The value
5898 * of the digits up to the point have been parsed by the caller and are given
5899 * in variable result. The content of *p_exactness indicates, whether a hash
5900 * has already been seen in the digits before the point.
5901 */
5902
5903 #define DIGIT2UINT(d) (uc_numeric_value(d).numerator)
5904
5905 static SCM
5906 mem2decimal_from_point (SCM result, SCM mem,
5907 unsigned int *p_idx, enum t_exactness *p_exactness)
5908 {
5909 unsigned int idx = *p_idx;
5910 enum t_exactness x = *p_exactness;
5911 size_t len = scm_i_string_length (mem);
5912
5913 if (idx == len)
5914 return result;
5915
5916 if (scm_i_string_ref (mem, idx) == '.')
5917 {
5918 scm_t_bits shift = 1;
5919 scm_t_bits add = 0;
5920 unsigned int digit_value;
5921 SCM big_shift = SCM_INUM1;
5922
5923 idx++;
5924 while (idx != len)
5925 {
5926 scm_t_wchar c = scm_i_string_ref (mem, idx);
5927 if (uc_is_property_decimal_digit ((scm_t_uint32) c))
5928 {
5929 if (x == INEXACT)
5930 return SCM_BOOL_F;
5931 else
5932 digit_value = DIGIT2UINT (c);
5933 }
5934 else if (c == '#')
5935 {
5936 x = INEXACT;
5937 digit_value = 0;
5938 }
5939 else
5940 break;
5941
5942 idx++;
5943 if (SCM_MOST_POSITIVE_FIXNUM / 10 < shift)
5944 {
5945 big_shift = scm_product (big_shift, SCM_I_MAKINUM (shift));
5946 result = scm_product (result, SCM_I_MAKINUM (shift));
5947 if (add > 0)
5948 result = scm_sum (result, SCM_I_MAKINUM (add));
5949
5950 shift = 10;
5951 add = digit_value;
5952 }
5953 else
5954 {
5955 shift = shift * 10;
5956 add = add * 10 + digit_value;
5957 }
5958 };
5959
5960 if (add > 0)
5961 {
5962 big_shift = scm_product (big_shift, SCM_I_MAKINUM (shift));
5963 result = scm_product (result, SCM_I_MAKINUM (shift));
5964 result = scm_sum (result, SCM_I_MAKINUM (add));
5965 }
5966
5967 result = scm_divide (result, big_shift);
5968
5969 /* We've seen a decimal point, thus the value is implicitly inexact. */
5970 x = INEXACT;
5971 }
5972
5973 if (idx != len)
5974 {
5975 int sign = 1;
5976 unsigned int start;
5977 scm_t_wchar c;
5978 int exponent;
5979 SCM e;
5980
5981 /* R5RS, section 7.1.1, lexical structure of numbers: <suffix> */
5982
5983 switch (scm_i_string_ref (mem, idx))
5984 {
5985 case 'd': case 'D':
5986 case 'e': case 'E':
5987 case 'f': case 'F':
5988 case 'l': case 'L':
5989 case 's': case 'S':
5990 idx++;
5991 if (idx == len)
5992 return SCM_BOOL_F;
5993
5994 start = idx;
5995 c = scm_i_string_ref (mem, idx);
5996 if (c == '-')
5997 {
5998 idx++;
5999 if (idx == len)
6000 return SCM_BOOL_F;
6001
6002 sign = -1;
6003 c = scm_i_string_ref (mem, idx);
6004 }
6005 else if (c == '+')
6006 {
6007 idx++;
6008 if (idx == len)
6009 return SCM_BOOL_F;
6010
6011 sign = 1;
6012 c = scm_i_string_ref (mem, idx);
6013 }
6014 else
6015 sign = 1;
6016
6017 if (!uc_is_property_decimal_digit ((scm_t_uint32) c))
6018 return SCM_BOOL_F;
6019
6020 idx++;
6021 exponent = DIGIT2UINT (c);
6022 while (idx != len)
6023 {
6024 scm_t_wchar c = scm_i_string_ref (mem, idx);
6025 if (uc_is_property_decimal_digit ((scm_t_uint32) c))
6026 {
6027 idx++;
6028 if (exponent <= SCM_MAXEXP)
6029 exponent = exponent * 10 + DIGIT2UINT (c);
6030 }
6031 else
6032 break;
6033 }
6034
6035 if (exponent > ((sign == 1) ? SCM_MAXEXP : SCM_MAXEXP + DBL_DIG + 1))
6036 {
6037 size_t exp_len = idx - start;
6038 SCM exp_string = scm_i_substring_copy (mem, start, start + exp_len);
6039 SCM exp_num = scm_string_to_number (exp_string, SCM_UNDEFINED);
6040 scm_out_of_range ("string->number", exp_num);
6041 }
6042
6043 e = scm_integer_expt (SCM_I_MAKINUM (10), SCM_I_MAKINUM (exponent));
6044 if (sign == 1)
6045 result = scm_product (result, e);
6046 else
6047 result = scm_divide (result, e);
6048
6049 /* We've seen an exponent, thus the value is implicitly inexact. */
6050 x = INEXACT;
6051
6052 break;
6053
6054 default:
6055 break;
6056 }
6057 }
6058
6059 *p_idx = idx;
6060 if (x == INEXACT)
6061 *p_exactness = x;
6062
6063 return result;
6064 }
6065
6066
6067 /* R5RS, section 7.1.1, lexical structure of numbers: <ureal R> */
6068
6069 static SCM
6070 mem2ureal (SCM mem, unsigned int *p_idx,
6071 unsigned int radix, enum t_exactness forced_x,
6072 int allow_inf_or_nan)
6073 {
6074 unsigned int idx = *p_idx;
6075 SCM result;
6076 size_t len = scm_i_string_length (mem);
6077
6078 /* Start off believing that the number will be exact. This changes
6079 to INEXACT if we see a decimal point or a hash. */
6080 enum t_exactness implicit_x = EXACT;
6081
6082 if (idx == len)
6083 return SCM_BOOL_F;
6084
6085 if (allow_inf_or_nan && forced_x != EXACT && idx+5 <= len)
6086 switch (scm_i_string_ref (mem, idx))
6087 {
6088 case 'i': case 'I':
6089 switch (scm_i_string_ref (mem, idx + 1))
6090 {
6091 case 'n': case 'N':
6092 switch (scm_i_string_ref (mem, idx + 2))
6093 {
6094 case 'f': case 'F':
6095 if (scm_i_string_ref (mem, idx + 3) == '.'
6096 && scm_i_string_ref (mem, idx + 4) == '0')
6097 {
6098 *p_idx = idx+5;
6099 return scm_inf ();
6100 }
6101 }
6102 }
6103 case 'n': case 'N':
6104 switch (scm_i_string_ref (mem, idx + 1))
6105 {
6106 case 'a': case 'A':
6107 switch (scm_i_string_ref (mem, idx + 2))
6108 {
6109 case 'n': case 'N':
6110 if (scm_i_string_ref (mem, idx + 3) == '.')
6111 {
6112 /* Cobble up the fractional part. We might want to
6113 set the NaN's mantissa from it. */
6114 idx += 4;
6115 if (!scm_is_eq (mem2uinteger (mem, &idx, 10, &implicit_x),
6116 SCM_INUM0))
6117 {
6118 #if SCM_ENABLE_DEPRECATED == 1
6119 scm_c_issue_deprecation_warning
6120 ("Non-zero suffixes to `+nan.' are deprecated. Use `+nan.0'.");
6121 #else
6122 return SCM_BOOL_F;
6123 #endif
6124 }
6125
6126 *p_idx = idx;
6127 return scm_nan ();
6128 }
6129 }
6130 }
6131 }
6132
6133 if (scm_i_string_ref (mem, idx) == '.')
6134 {
6135 if (radix != 10)
6136 return SCM_BOOL_F;
6137 else if (idx + 1 == len)
6138 return SCM_BOOL_F;
6139 else if (!uc_is_property_decimal_digit ((scm_t_uint32) scm_i_string_ref (mem, idx+1)))
6140 return SCM_BOOL_F;
6141 else
6142 result = mem2decimal_from_point (SCM_INUM0, mem,
6143 p_idx, &implicit_x);
6144 }
6145 else
6146 {
6147 SCM uinteger;
6148
6149 uinteger = mem2uinteger (mem, &idx, radix, &implicit_x);
6150 if (scm_is_false (uinteger))
6151 return SCM_BOOL_F;
6152
6153 if (idx == len)
6154 result = uinteger;
6155 else if (scm_i_string_ref (mem, idx) == '/')
6156 {
6157 SCM divisor;
6158
6159 idx++;
6160 if (idx == len)
6161 return SCM_BOOL_F;
6162
6163 divisor = mem2uinteger (mem, &idx, radix, &implicit_x);
6164 if (scm_is_false (divisor) || scm_is_eq (divisor, SCM_INUM0))
6165 return SCM_BOOL_F;
6166
6167 /* both are int/big here, I assume */
6168 result = scm_i_make_ratio (uinteger, divisor);
6169 }
6170 else if (radix == 10)
6171 {
6172 result = mem2decimal_from_point (uinteger, mem, &idx, &implicit_x);
6173 if (scm_is_false (result))
6174 return SCM_BOOL_F;
6175 }
6176 else
6177 result = uinteger;
6178
6179 *p_idx = idx;
6180 }
6181
6182 switch (forced_x)
6183 {
6184 case EXACT:
6185 if (SCM_INEXACTP (result))
6186 return scm_inexact_to_exact (result);
6187 else
6188 return result;
6189 case INEXACT:
6190 if (SCM_INEXACTP (result))
6191 return result;
6192 else
6193 return scm_exact_to_inexact (result);
6194 case NO_EXACTNESS:
6195 if (implicit_x == INEXACT)
6196 {
6197 if (SCM_INEXACTP (result))
6198 return result;
6199 else
6200 return scm_exact_to_inexact (result);
6201 }
6202 else
6203 return result;
6204 }
6205
6206 /* We should never get here */
6207 scm_syserror ("mem2ureal");
6208 }
6209
6210
6211 /* R5RS, section 7.1.1, lexical structure of numbers: <complex R> */
6212
6213 static SCM
6214 mem2complex (SCM mem, unsigned int idx,
6215 unsigned int radix, enum t_exactness forced_x)
6216 {
6217 scm_t_wchar c;
6218 int sign = 0;
6219 SCM ureal;
6220 size_t len = scm_i_string_length (mem);
6221
6222 if (idx == len)
6223 return SCM_BOOL_F;
6224
6225 c = scm_i_string_ref (mem, idx);
6226 if (c == '+')
6227 {
6228 idx++;
6229 sign = 1;
6230 }
6231 else if (c == '-')
6232 {
6233 idx++;
6234 sign = -1;
6235 }
6236
6237 if (idx == len)
6238 return SCM_BOOL_F;
6239
6240 ureal = mem2ureal (mem, &idx, radix, forced_x, sign != 0);
6241 if (scm_is_false (ureal))
6242 {
6243 /* input must be either +i or -i */
6244
6245 if (sign == 0)
6246 return SCM_BOOL_F;
6247
6248 if (scm_i_string_ref (mem, idx) == 'i'
6249 || scm_i_string_ref (mem, idx) == 'I')
6250 {
6251 idx++;
6252 if (idx != len)
6253 return SCM_BOOL_F;
6254
6255 return scm_make_rectangular (SCM_INUM0, SCM_I_MAKINUM (sign));
6256 }
6257 else
6258 return SCM_BOOL_F;
6259 }
6260 else
6261 {
6262 if (sign == -1 && scm_is_false (scm_nan_p (ureal)))
6263 ureal = scm_difference (ureal, SCM_UNDEFINED);
6264
6265 if (idx == len)
6266 return ureal;
6267
6268 c = scm_i_string_ref (mem, idx);
6269 switch (c)
6270 {
6271 case 'i': case 'I':
6272 /* either +<ureal>i or -<ureal>i */
6273
6274 idx++;
6275 if (sign == 0)
6276 return SCM_BOOL_F;
6277 if (idx != len)
6278 return SCM_BOOL_F;
6279 return scm_make_rectangular (SCM_INUM0, ureal);
6280
6281 case '@':
6282 /* polar input: <real>@<real>. */
6283
6284 idx++;
6285 if (idx == len)
6286 return SCM_BOOL_F;
6287 else
6288 {
6289 int sign;
6290 SCM angle;
6291 SCM result;
6292
6293 c = scm_i_string_ref (mem, idx);
6294 if (c == '+')
6295 {
6296 idx++;
6297 if (idx == len)
6298 return SCM_BOOL_F;
6299 sign = 1;
6300 }
6301 else if (c == '-')
6302 {
6303 idx++;
6304 if (idx == len)
6305 return SCM_BOOL_F;
6306 sign = -1;
6307 }
6308 else
6309 sign = 0;
6310
6311 angle = mem2ureal (mem, &idx, radix, forced_x, sign != 0);
6312 if (scm_is_false (angle))
6313 return SCM_BOOL_F;
6314 if (idx != len)
6315 return SCM_BOOL_F;
6316
6317 if (sign == -1 && scm_is_false (scm_nan_p (ureal)))
6318 angle = scm_difference (angle, SCM_UNDEFINED);
6319
6320 result = scm_make_polar (ureal, angle);
6321 return result;
6322 }
6323 case '+':
6324 case '-':
6325 /* expecting input matching <real>[+-]<ureal>?i */
6326
6327 idx++;
6328 if (idx == len)
6329 return SCM_BOOL_F;
6330 else
6331 {
6332 int sign = (c == '+') ? 1 : -1;
6333 SCM imag = mem2ureal (mem, &idx, radix, forced_x, sign != 0);
6334
6335 if (scm_is_false (imag))
6336 imag = SCM_I_MAKINUM (sign);
6337 else if (sign == -1 && scm_is_false (scm_nan_p (imag)))
6338 imag = scm_difference (imag, SCM_UNDEFINED);
6339
6340 if (idx == len)
6341 return SCM_BOOL_F;
6342 if (scm_i_string_ref (mem, idx) != 'i'
6343 && scm_i_string_ref (mem, idx) != 'I')
6344 return SCM_BOOL_F;
6345
6346 idx++;
6347 if (idx != len)
6348 return SCM_BOOL_F;
6349
6350 return scm_make_rectangular (ureal, imag);
6351 }
6352 default:
6353 return SCM_BOOL_F;
6354 }
6355 }
6356 }
6357
6358
6359 /* R5RS, section 7.1.1, lexical structure of numbers: <number> */
6360
6361 enum t_radix {NO_RADIX=0, DUAL=2, OCT=8, DEC=10, HEX=16};
6362
6363 SCM
6364 scm_i_string_to_number (SCM mem, unsigned int default_radix)
6365 {
6366 unsigned int idx = 0;
6367 unsigned int radix = NO_RADIX;
6368 enum t_exactness forced_x = NO_EXACTNESS;
6369 size_t len = scm_i_string_length (mem);
6370
6371 /* R5RS, section 7.1.1, lexical structure of numbers: <prefix R> */
6372 while (idx + 2 < len && scm_i_string_ref (mem, idx) == '#')
6373 {
6374 switch (scm_i_string_ref (mem, idx + 1))
6375 {
6376 case 'b': case 'B':
6377 if (radix != NO_RADIX)
6378 return SCM_BOOL_F;
6379 radix = DUAL;
6380 break;
6381 case 'd': case 'D':
6382 if (radix != NO_RADIX)
6383 return SCM_BOOL_F;
6384 radix = DEC;
6385 break;
6386 case 'i': case 'I':
6387 if (forced_x != NO_EXACTNESS)
6388 return SCM_BOOL_F;
6389 forced_x = INEXACT;
6390 break;
6391 case 'e': case 'E':
6392 if (forced_x != NO_EXACTNESS)
6393 return SCM_BOOL_F;
6394 forced_x = EXACT;
6395 break;
6396 case 'o': case 'O':
6397 if (radix != NO_RADIX)
6398 return SCM_BOOL_F;
6399 radix = OCT;
6400 break;
6401 case 'x': case 'X':
6402 if (radix != NO_RADIX)
6403 return SCM_BOOL_F;
6404 radix = HEX;
6405 break;
6406 default:
6407 return SCM_BOOL_F;
6408 }
6409 idx += 2;
6410 }
6411
6412 /* R5RS, section 7.1.1, lexical structure of numbers: <complex R> */
6413 if (radix == NO_RADIX)
6414 radix = default_radix;
6415
6416 return mem2complex (mem, idx, radix, forced_x);
6417 }
6418
6419 SCM
6420 scm_c_locale_stringn_to_number (const char* mem, size_t len,
6421 unsigned int default_radix)
6422 {
6423 SCM str = scm_from_locale_stringn (mem, len);
6424
6425 return scm_i_string_to_number (str, default_radix);
6426 }
6427
6428
6429 SCM_DEFINE (scm_string_to_number, "string->number", 1, 1, 0,
6430 (SCM string, SCM radix),
6431 "Return a number of the maximally precise representation\n"
6432 "expressed by the given @var{string}. @var{radix} must be an\n"
6433 "exact integer, either 2, 8, 10, or 16. If supplied, @var{radix}\n"
6434 "is a default radix that may be overridden by an explicit radix\n"
6435 "prefix in @var{string} (e.g. \"#o177\"). If @var{radix} is not\n"
6436 "supplied, then the default radix is 10. If string is not a\n"
6437 "syntactically valid notation for a number, then\n"
6438 "@code{string->number} returns @code{#f}.")
6439 #define FUNC_NAME s_scm_string_to_number
6440 {
6441 SCM answer;
6442 unsigned int base;
6443 SCM_VALIDATE_STRING (1, string);
6444
6445 if (SCM_UNBNDP (radix))
6446 base = 10;
6447 else
6448 base = scm_to_unsigned_integer (radix, 2, INT_MAX);
6449
6450 answer = scm_i_string_to_number (string, base);
6451 scm_remember_upto_here_1 (string);
6452 return answer;
6453 }
6454 #undef FUNC_NAME
6455
6456
6457 /*** END strs->nums ***/
6458
6459
6460 SCM_DEFINE (scm_number_p, "number?", 1, 0, 0,
6461 (SCM x),
6462 "Return @code{#t} if @var{x} is a number, @code{#f}\n"
6463 "otherwise.")
6464 #define FUNC_NAME s_scm_number_p
6465 {
6466 return scm_from_bool (SCM_NUMBERP (x));
6467 }
6468 #undef FUNC_NAME
6469
6470 SCM_DEFINE (scm_complex_p, "complex?", 1, 0, 0,
6471 (SCM x),
6472 "Return @code{#t} if @var{x} is a complex number, @code{#f}\n"
6473 "otherwise. Note that the sets of real, rational and integer\n"
6474 "values form subsets of the set of complex numbers, i. e. the\n"
6475 "predicate will also be fulfilled if @var{x} is a real,\n"
6476 "rational or integer number.")
6477 #define FUNC_NAME s_scm_complex_p
6478 {
6479 /* all numbers are complex. */
6480 return scm_number_p (x);
6481 }
6482 #undef FUNC_NAME
6483
6484 SCM_DEFINE (scm_real_p, "real?", 1, 0, 0,
6485 (SCM x),
6486 "Return @code{#t} if @var{x} is a real number, @code{#f}\n"
6487 "otherwise. Note that the set of integer values forms a subset of\n"
6488 "the set of real numbers, i. e. the predicate will also be\n"
6489 "fulfilled if @var{x} is an integer number.")
6490 #define FUNC_NAME s_scm_real_p
6491 {
6492 return scm_from_bool
6493 (SCM_I_INUMP (x) || SCM_REALP (x) || SCM_BIGP (x) || SCM_FRACTIONP (x));
6494 }
6495 #undef FUNC_NAME
6496
6497 SCM_DEFINE (scm_rational_p, "rational?", 1, 0, 0,
6498 (SCM x),
6499 "Return @code{#t} if @var{x} is a rational number, @code{#f}\n"
6500 "otherwise. Note that the set of integer values forms a subset of\n"
6501 "the set of rational numbers, i. e. the predicate will also be\n"
6502 "fulfilled if @var{x} is an integer number.")
6503 #define FUNC_NAME s_scm_rational_p
6504 {
6505 if (SCM_I_INUMP (x) || SCM_BIGP (x) || SCM_FRACTIONP (x))
6506 return SCM_BOOL_T;
6507 else if (SCM_REALP (x))
6508 /* due to their limited precision, finite floating point numbers are
6509 rational as well. (finite means neither infinity nor a NaN) */
6510 return scm_from_bool (DOUBLE_IS_FINITE (SCM_REAL_VALUE (x)));
6511 else
6512 return SCM_BOOL_F;
6513 }
6514 #undef FUNC_NAME
6515
6516 SCM_DEFINE (scm_integer_p, "integer?", 1, 0, 0,
6517 (SCM x),
6518 "Return @code{#t} if @var{x} is an integer number, @code{#f}\n"
6519 "else.")
6520 #define FUNC_NAME s_scm_integer_p
6521 {
6522 if (SCM_I_INUMP (x) || SCM_BIGP (x))
6523 return SCM_BOOL_T;
6524 else if (SCM_REALP (x))
6525 {
6526 double val = SCM_REAL_VALUE (x);
6527 return scm_from_bool (!isinf (val) && (val == floor (val)));
6528 }
6529 else
6530 return SCM_BOOL_F;
6531 }
6532 #undef FUNC_NAME
6533
6534
6535 SCM scm_i_num_eq_p (SCM, SCM, SCM);
6536 SCM_PRIMITIVE_GENERIC (scm_i_num_eq_p, "=", 0, 2, 1,
6537 (SCM x, SCM y, SCM rest),
6538 "Return @code{#t} if all parameters are numerically equal.")
6539 #define FUNC_NAME s_scm_i_num_eq_p
6540 {
6541 if (SCM_UNBNDP (x) || SCM_UNBNDP (y))
6542 return SCM_BOOL_T;
6543 while (!scm_is_null (rest))
6544 {
6545 if (scm_is_false (scm_num_eq_p (x, y)))
6546 return SCM_BOOL_F;
6547 x = y;
6548 y = scm_car (rest);
6549 rest = scm_cdr (rest);
6550 }
6551 return scm_num_eq_p (x, y);
6552 }
6553 #undef FUNC_NAME
6554 SCM
6555 scm_num_eq_p (SCM x, SCM y)
6556 {
6557 again:
6558 if (SCM_I_INUMP (x))
6559 {
6560 scm_t_signed_bits xx = SCM_I_INUM (x);
6561 if (SCM_I_INUMP (y))
6562 {
6563 scm_t_signed_bits yy = SCM_I_INUM (y);
6564 return scm_from_bool (xx == yy);
6565 }
6566 else if (SCM_BIGP (y))
6567 return SCM_BOOL_F;
6568 else if (SCM_REALP (y))
6569 {
6570 /* On a 32-bit system an inum fits a double, we can cast the inum
6571 to a double and compare.
6572
6573 But on a 64-bit system an inum is bigger than a double and
6574 casting it to a double (call that dxx) will round.
6575 Although dxx will not in general be equal to xx, dxx will
6576 always be an integer and within a factor of 2 of xx, so if
6577 dxx==yy, we know that yy is an integer and fits in
6578 scm_t_signed_bits. So we cast yy to scm_t_signed_bits and
6579 compare with plain xx.
6580
6581 An alternative (for any size system actually) would be to check
6582 yy is an integer (with floor) and is in range of an inum
6583 (compare against appropriate powers of 2) then test
6584 xx==(scm_t_signed_bits)yy. It's just a matter of which
6585 casts/comparisons might be fastest or easiest for the cpu. */
6586
6587 double yy = SCM_REAL_VALUE (y);
6588 return scm_from_bool ((double) xx == yy
6589 && (DBL_MANT_DIG >= SCM_I_FIXNUM_BIT-1
6590 || xx == (scm_t_signed_bits) yy));
6591 }
6592 else if (SCM_COMPLEXP (y))
6593 {
6594 /* see comments with inum/real above */
6595 double ry = SCM_COMPLEX_REAL (y);
6596 return scm_from_bool ((double) xx == ry
6597 && 0.0 == SCM_COMPLEX_IMAG (y)
6598 && (DBL_MANT_DIG >= SCM_I_FIXNUM_BIT-1
6599 || xx == (scm_t_signed_bits) ry));
6600 }
6601 else if (SCM_FRACTIONP (y))
6602 return SCM_BOOL_F;
6603 else
6604 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARGn, s_scm_i_num_eq_p);
6605 }
6606 else if (SCM_BIGP (x))
6607 {
6608 if (SCM_I_INUMP (y))
6609 return SCM_BOOL_F;
6610 else if (SCM_BIGP (y))
6611 {
6612 int cmp = mpz_cmp (SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
6613 scm_remember_upto_here_2 (x, y);
6614 return scm_from_bool (0 == cmp);
6615 }
6616 else if (SCM_REALP (y))
6617 {
6618 int cmp;
6619 if (isnan (SCM_REAL_VALUE (y)))
6620 return SCM_BOOL_F;
6621 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (x), SCM_REAL_VALUE (y));
6622 scm_remember_upto_here_1 (x);
6623 return scm_from_bool (0 == cmp);
6624 }
6625 else if (SCM_COMPLEXP (y))
6626 {
6627 int cmp;
6628 if (0.0 != SCM_COMPLEX_IMAG (y))
6629 return SCM_BOOL_F;
6630 if (isnan (SCM_COMPLEX_REAL (y)))
6631 return SCM_BOOL_F;
6632 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (x), SCM_COMPLEX_REAL (y));
6633 scm_remember_upto_here_1 (x);
6634 return scm_from_bool (0 == cmp);
6635 }
6636 else if (SCM_FRACTIONP (y))
6637 return SCM_BOOL_F;
6638 else
6639 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARGn, s_scm_i_num_eq_p);
6640 }
6641 else if (SCM_REALP (x))
6642 {
6643 double xx = SCM_REAL_VALUE (x);
6644 if (SCM_I_INUMP (y))
6645 {
6646 /* see comments with inum/real above */
6647 scm_t_signed_bits yy = SCM_I_INUM (y);
6648 return scm_from_bool (xx == (double) yy
6649 && (DBL_MANT_DIG >= SCM_I_FIXNUM_BIT-1
6650 || (scm_t_signed_bits) xx == yy));
6651 }
6652 else if (SCM_BIGP (y))
6653 {
6654 int cmp;
6655 if (isnan (xx))
6656 return SCM_BOOL_F;
6657 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (y), xx);
6658 scm_remember_upto_here_1 (y);
6659 return scm_from_bool (0 == cmp);
6660 }
6661 else if (SCM_REALP (y))
6662 return scm_from_bool (xx == SCM_REAL_VALUE (y));
6663 else if (SCM_COMPLEXP (y))
6664 return scm_from_bool ((xx == SCM_COMPLEX_REAL (y))
6665 && (0.0 == SCM_COMPLEX_IMAG (y)));
6666 else if (SCM_FRACTIONP (y))
6667 {
6668 if (isnan (xx) || isinf (xx))
6669 return SCM_BOOL_F;
6670 x = scm_inexact_to_exact (x); /* with x as frac or int */
6671 goto again;
6672 }
6673 else
6674 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARGn, s_scm_i_num_eq_p);
6675 }
6676 else if (SCM_COMPLEXP (x))
6677 {
6678 if (SCM_I_INUMP (y))
6679 {
6680 /* see comments with inum/real above */
6681 double rx = SCM_COMPLEX_REAL (x);
6682 scm_t_signed_bits yy = SCM_I_INUM (y);
6683 return scm_from_bool (rx == (double) yy
6684 && 0.0 == SCM_COMPLEX_IMAG (x)
6685 && (DBL_MANT_DIG >= SCM_I_FIXNUM_BIT-1
6686 || (scm_t_signed_bits) rx == yy));
6687 }
6688 else if (SCM_BIGP (y))
6689 {
6690 int cmp;
6691 if (0.0 != SCM_COMPLEX_IMAG (x))
6692 return SCM_BOOL_F;
6693 if (isnan (SCM_COMPLEX_REAL (x)))
6694 return SCM_BOOL_F;
6695 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (y), SCM_COMPLEX_REAL (x));
6696 scm_remember_upto_here_1 (y);
6697 return scm_from_bool (0 == cmp);
6698 }
6699 else if (SCM_REALP (y))
6700 return scm_from_bool ((SCM_COMPLEX_REAL (x) == SCM_REAL_VALUE (y))
6701 && (SCM_COMPLEX_IMAG (x) == 0.0));
6702 else if (SCM_COMPLEXP (y))
6703 return scm_from_bool ((SCM_COMPLEX_REAL (x) == SCM_COMPLEX_REAL (y))
6704 && (SCM_COMPLEX_IMAG (x) == SCM_COMPLEX_IMAG (y)));
6705 else if (SCM_FRACTIONP (y))
6706 {
6707 double xx;
6708 if (SCM_COMPLEX_IMAG (x) != 0.0)
6709 return SCM_BOOL_F;
6710 xx = SCM_COMPLEX_REAL (x);
6711 if (isnan (xx) || isinf (xx))
6712 return SCM_BOOL_F;
6713 x = scm_inexact_to_exact (x); /* with x as frac or int */
6714 goto again;
6715 }
6716 else
6717 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARGn, s_scm_i_num_eq_p);
6718 }
6719 else if (SCM_FRACTIONP (x))
6720 {
6721 if (SCM_I_INUMP (y))
6722 return SCM_BOOL_F;
6723 else if (SCM_BIGP (y))
6724 return SCM_BOOL_F;
6725 else if (SCM_REALP (y))
6726 {
6727 double yy = SCM_REAL_VALUE (y);
6728 if (isnan (yy) || isinf (yy))
6729 return SCM_BOOL_F;
6730 y = scm_inexact_to_exact (y); /* with y as frac or int */
6731 goto again;
6732 }
6733 else if (SCM_COMPLEXP (y))
6734 {
6735 double yy;
6736 if (SCM_COMPLEX_IMAG (y) != 0.0)
6737 return SCM_BOOL_F;
6738 yy = SCM_COMPLEX_REAL (y);
6739 if (isnan (yy) || isinf(yy))
6740 return SCM_BOOL_F;
6741 y = scm_inexact_to_exact (y); /* with y as frac or int */
6742 goto again;
6743 }
6744 else if (SCM_FRACTIONP (y))
6745 return scm_i_fraction_equalp (x, y);
6746 else
6747 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARGn, s_scm_i_num_eq_p);
6748 }
6749 else
6750 SCM_WTA_DISPATCH_2 (g_scm_i_num_eq_p, x, y, SCM_ARG1, s_scm_i_num_eq_p);
6751 }
6752
6753
6754 /* OPTIMIZE-ME: For int/frac and frac/frac compares, the multiplications
6755 done are good for inums, but for bignums an answer can almost always be
6756 had by just examining a few high bits of the operands, as done by GMP in
6757 mpq_cmp. flonum/frac compares likewise, but with the slight complication
6758 of the float exponent to take into account. */
6759
6760 SCM_INTERNAL SCM scm_i_num_less_p (SCM, SCM, SCM);
6761 SCM_PRIMITIVE_GENERIC (scm_i_num_less_p, "<", 0, 2, 1,
6762 (SCM x, SCM y, SCM rest),
6763 "Return @code{#t} if the list of parameters is monotonically\n"
6764 "increasing.")
6765 #define FUNC_NAME s_scm_i_num_less_p
6766 {
6767 if (SCM_UNBNDP (x) || SCM_UNBNDP (y))
6768 return SCM_BOOL_T;
6769 while (!scm_is_null (rest))
6770 {
6771 if (scm_is_false (scm_less_p (x, y)))
6772 return SCM_BOOL_F;
6773 x = y;
6774 y = scm_car (rest);
6775 rest = scm_cdr (rest);
6776 }
6777 return scm_less_p (x, y);
6778 }
6779 #undef FUNC_NAME
6780 SCM
6781 scm_less_p (SCM x, SCM y)
6782 {
6783 again:
6784 if (SCM_I_INUMP (x))
6785 {
6786 scm_t_inum xx = SCM_I_INUM (x);
6787 if (SCM_I_INUMP (y))
6788 {
6789 scm_t_inum yy = SCM_I_INUM (y);
6790 return scm_from_bool (xx < yy);
6791 }
6792 else if (SCM_BIGP (y))
6793 {
6794 int sgn = mpz_sgn (SCM_I_BIG_MPZ (y));
6795 scm_remember_upto_here_1 (y);
6796 return scm_from_bool (sgn > 0);
6797 }
6798 else if (SCM_REALP (y))
6799 {
6800 /* We can safely take the ceiling of y without changing the
6801 result of x<y, given that x is an integer. */
6802 double yy = ceil (SCM_REAL_VALUE (y));
6803
6804 /* In the following comparisons, it's important that the right
6805 hand side always be a power of 2, so that it can be
6806 losslessly converted to a double even on 64-bit
6807 machines. */
6808 if (yy >= (double) (SCM_MOST_POSITIVE_FIXNUM+1))
6809 return SCM_BOOL_T;
6810 else if (!(yy > (double) SCM_MOST_NEGATIVE_FIXNUM))
6811 /* The condition above is carefully written to include the
6812 case where yy==NaN. */
6813 return SCM_BOOL_F;
6814 else
6815 /* yy is a finite integer that fits in an inum. */
6816 return scm_from_bool (xx < (scm_t_inum) yy);
6817 }
6818 else if (SCM_FRACTIONP (y))
6819 {
6820 /* "x < a/b" becomes "x*b < a" */
6821 int_frac:
6822 x = scm_product (x, SCM_FRACTION_DENOMINATOR (y));
6823 y = SCM_FRACTION_NUMERATOR (y);
6824 goto again;
6825 }
6826 else
6827 SCM_WTA_DISPATCH_2 (g_scm_i_num_less_p, x, y, SCM_ARGn, s_scm_i_num_less_p);
6828 }
6829 else if (SCM_BIGP (x))
6830 {
6831 if (SCM_I_INUMP (y))
6832 {
6833 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
6834 scm_remember_upto_here_1 (x);
6835 return scm_from_bool (sgn < 0);
6836 }
6837 else if (SCM_BIGP (y))
6838 {
6839 int cmp = mpz_cmp (SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
6840 scm_remember_upto_here_2 (x, y);
6841 return scm_from_bool (cmp < 0);
6842 }
6843 else if (SCM_REALP (y))
6844 {
6845 int cmp;
6846 if (isnan (SCM_REAL_VALUE (y)))
6847 return SCM_BOOL_F;
6848 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (x), SCM_REAL_VALUE (y));
6849 scm_remember_upto_here_1 (x);
6850 return scm_from_bool (cmp < 0);
6851 }
6852 else if (SCM_FRACTIONP (y))
6853 goto int_frac;
6854 else
6855 SCM_WTA_DISPATCH_2 (g_scm_i_num_less_p, x, y, SCM_ARGn, s_scm_i_num_less_p);
6856 }
6857 else if (SCM_REALP (x))
6858 {
6859 if (SCM_I_INUMP (y))
6860 {
6861 /* We can safely take the floor of x without changing the
6862 result of x<y, given that y is an integer. */
6863 double xx = floor (SCM_REAL_VALUE (x));
6864
6865 /* In the following comparisons, it's important that the right
6866 hand side always be a power of 2, so that it can be
6867 losslessly converted to a double even on 64-bit
6868 machines. */
6869 if (xx < (double) SCM_MOST_NEGATIVE_FIXNUM)
6870 return SCM_BOOL_T;
6871 else if (!(xx < (double) (SCM_MOST_POSITIVE_FIXNUM+1)))
6872 /* The condition above is carefully written to include the
6873 case where xx==NaN. */
6874 return SCM_BOOL_F;
6875 else
6876 /* xx is a finite integer that fits in an inum. */
6877 return scm_from_bool ((scm_t_inum) xx < SCM_I_INUM (y));
6878 }
6879 else if (SCM_BIGP (y))
6880 {
6881 int cmp;
6882 if (isnan (SCM_REAL_VALUE (x)))
6883 return SCM_BOOL_F;
6884 cmp = xmpz_cmp_d (SCM_I_BIG_MPZ (y), SCM_REAL_VALUE (x));
6885 scm_remember_upto_here_1 (y);
6886 return scm_from_bool (cmp > 0);
6887 }
6888 else if (SCM_REALP (y))
6889 return scm_from_bool (SCM_REAL_VALUE (x) < SCM_REAL_VALUE (y));
6890 else if (SCM_FRACTIONP (y))
6891 {
6892 double xx = SCM_REAL_VALUE (x);
6893 if (isnan (xx))
6894 return SCM_BOOL_F;
6895 if (isinf (xx))
6896 return scm_from_bool (xx < 0.0);
6897 x = scm_inexact_to_exact (x); /* with x as frac or int */
6898 goto again;
6899 }
6900 else
6901 SCM_WTA_DISPATCH_2 (g_scm_i_num_less_p, x, y, SCM_ARGn, s_scm_i_num_less_p);
6902 }
6903 else if (SCM_FRACTIONP (x))
6904 {
6905 if (SCM_I_INUMP (y) || SCM_BIGP (y))
6906 {
6907 /* "a/b < y" becomes "a < y*b" */
6908 y = scm_product (y, SCM_FRACTION_DENOMINATOR (x));
6909 x = SCM_FRACTION_NUMERATOR (x);
6910 goto again;
6911 }
6912 else if (SCM_REALP (y))
6913 {
6914 double yy = SCM_REAL_VALUE (y);
6915 if (isnan (yy))
6916 return SCM_BOOL_F;
6917 if (isinf (yy))
6918 return scm_from_bool (0.0 < yy);
6919 y = scm_inexact_to_exact (y); /* with y as frac or int */
6920 goto again;
6921 }
6922 else if (SCM_FRACTIONP (y))
6923 {
6924 /* "a/b < c/d" becomes "a*d < c*b" */
6925 SCM new_x = scm_product (SCM_FRACTION_NUMERATOR (x),
6926 SCM_FRACTION_DENOMINATOR (y));
6927 SCM new_y = scm_product (SCM_FRACTION_NUMERATOR (y),
6928 SCM_FRACTION_DENOMINATOR (x));
6929 x = new_x;
6930 y = new_y;
6931 goto again;
6932 }
6933 else
6934 SCM_WTA_DISPATCH_2 (g_scm_i_num_less_p, x, y, SCM_ARGn, s_scm_i_num_less_p);
6935 }
6936 else
6937 SCM_WTA_DISPATCH_2 (g_scm_i_num_less_p, x, y, SCM_ARG1, s_scm_i_num_less_p);
6938 }
6939
6940
6941 SCM scm_i_num_gr_p (SCM, SCM, SCM);
6942 SCM_PRIMITIVE_GENERIC (scm_i_num_gr_p, ">", 0, 2, 1,
6943 (SCM x, SCM y, SCM rest),
6944 "Return @code{#t} if the list of parameters is monotonically\n"
6945 "decreasing.")
6946 #define FUNC_NAME s_scm_i_num_gr_p
6947 {
6948 if (SCM_UNBNDP (x) || SCM_UNBNDP (y))
6949 return SCM_BOOL_T;
6950 while (!scm_is_null (rest))
6951 {
6952 if (scm_is_false (scm_gr_p (x, y)))
6953 return SCM_BOOL_F;
6954 x = y;
6955 y = scm_car (rest);
6956 rest = scm_cdr (rest);
6957 }
6958 return scm_gr_p (x, y);
6959 }
6960 #undef FUNC_NAME
6961 #define FUNC_NAME s_scm_i_num_gr_p
6962 SCM
6963 scm_gr_p (SCM x, SCM y)
6964 {
6965 if (!SCM_NUMBERP (x))
6966 SCM_WTA_DISPATCH_2 (g_scm_i_num_gr_p, x, y, SCM_ARG1, FUNC_NAME);
6967 else if (!SCM_NUMBERP (y))
6968 SCM_WTA_DISPATCH_2 (g_scm_i_num_gr_p, x, y, SCM_ARG2, FUNC_NAME);
6969 else
6970 return scm_less_p (y, x);
6971 }
6972 #undef FUNC_NAME
6973
6974
6975 SCM scm_i_num_leq_p (SCM, SCM, SCM);
6976 SCM_PRIMITIVE_GENERIC (scm_i_num_leq_p, "<=", 0, 2, 1,
6977 (SCM x, SCM y, SCM rest),
6978 "Return @code{#t} if the list of parameters is monotonically\n"
6979 "non-decreasing.")
6980 #define FUNC_NAME s_scm_i_num_leq_p
6981 {
6982 if (SCM_UNBNDP (x) || SCM_UNBNDP (y))
6983 return SCM_BOOL_T;
6984 while (!scm_is_null (rest))
6985 {
6986 if (scm_is_false (scm_leq_p (x, y)))
6987 return SCM_BOOL_F;
6988 x = y;
6989 y = scm_car (rest);
6990 rest = scm_cdr (rest);
6991 }
6992 return scm_leq_p (x, y);
6993 }
6994 #undef FUNC_NAME
6995 #define FUNC_NAME s_scm_i_num_leq_p
6996 SCM
6997 scm_leq_p (SCM x, SCM y)
6998 {
6999 if (!SCM_NUMBERP (x))
7000 SCM_WTA_DISPATCH_2 (g_scm_i_num_leq_p, x, y, SCM_ARG1, FUNC_NAME);
7001 else if (!SCM_NUMBERP (y))
7002 SCM_WTA_DISPATCH_2 (g_scm_i_num_leq_p, x, y, SCM_ARG2, FUNC_NAME);
7003 else if (scm_is_true (scm_nan_p (x)) || scm_is_true (scm_nan_p (y)))
7004 return SCM_BOOL_F;
7005 else
7006 return scm_not (scm_less_p (y, x));
7007 }
7008 #undef FUNC_NAME
7009
7010
7011 SCM scm_i_num_geq_p (SCM, SCM, SCM);
7012 SCM_PRIMITIVE_GENERIC (scm_i_num_geq_p, ">=", 0, 2, 1,
7013 (SCM x, SCM y, SCM rest),
7014 "Return @code{#t} if the list of parameters is monotonically\n"
7015 "non-increasing.")
7016 #define FUNC_NAME s_scm_i_num_geq_p
7017 {
7018 if (SCM_UNBNDP (x) || SCM_UNBNDP (y))
7019 return SCM_BOOL_T;
7020 while (!scm_is_null (rest))
7021 {
7022 if (scm_is_false (scm_geq_p (x, y)))
7023 return SCM_BOOL_F;
7024 x = y;
7025 y = scm_car (rest);
7026 rest = scm_cdr (rest);
7027 }
7028 return scm_geq_p (x, y);
7029 }
7030 #undef FUNC_NAME
7031 #define FUNC_NAME s_scm_i_num_geq_p
7032 SCM
7033 scm_geq_p (SCM x, SCM y)
7034 {
7035 if (!SCM_NUMBERP (x))
7036 SCM_WTA_DISPATCH_2 (g_scm_i_num_geq_p, x, y, SCM_ARG1, FUNC_NAME);
7037 else if (!SCM_NUMBERP (y))
7038 SCM_WTA_DISPATCH_2 (g_scm_i_num_geq_p, x, y, SCM_ARG2, FUNC_NAME);
7039 else if (scm_is_true (scm_nan_p (x)) || scm_is_true (scm_nan_p (y)))
7040 return SCM_BOOL_F;
7041 else
7042 return scm_not (scm_less_p (x, y));
7043 }
7044 #undef FUNC_NAME
7045
7046
7047 SCM_PRIMITIVE_GENERIC (scm_zero_p, "zero?", 1, 0, 0,
7048 (SCM z),
7049 "Return @code{#t} if @var{z} is an exact or inexact number equal to\n"
7050 "zero.")
7051 #define FUNC_NAME s_scm_zero_p
7052 {
7053 if (SCM_I_INUMP (z))
7054 return scm_from_bool (scm_is_eq (z, SCM_INUM0));
7055 else if (SCM_BIGP (z))
7056 return SCM_BOOL_F;
7057 else if (SCM_REALP (z))
7058 return scm_from_bool (SCM_REAL_VALUE (z) == 0.0);
7059 else if (SCM_COMPLEXP (z))
7060 return scm_from_bool (SCM_COMPLEX_REAL (z) == 0.0
7061 && SCM_COMPLEX_IMAG (z) == 0.0);
7062 else if (SCM_FRACTIONP (z))
7063 return SCM_BOOL_F;
7064 else
7065 SCM_WTA_DISPATCH_1 (g_scm_zero_p, z, SCM_ARG1, s_scm_zero_p);
7066 }
7067 #undef FUNC_NAME
7068
7069
7070 SCM_PRIMITIVE_GENERIC (scm_positive_p, "positive?", 1, 0, 0,
7071 (SCM x),
7072 "Return @code{#t} if @var{x} is an exact or inexact number greater than\n"
7073 "zero.")
7074 #define FUNC_NAME s_scm_positive_p
7075 {
7076 if (SCM_I_INUMP (x))
7077 return scm_from_bool (SCM_I_INUM (x) > 0);
7078 else if (SCM_BIGP (x))
7079 {
7080 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
7081 scm_remember_upto_here_1 (x);
7082 return scm_from_bool (sgn > 0);
7083 }
7084 else if (SCM_REALP (x))
7085 return scm_from_bool(SCM_REAL_VALUE (x) > 0.0);
7086 else if (SCM_FRACTIONP (x))
7087 return scm_positive_p (SCM_FRACTION_NUMERATOR (x));
7088 else
7089 SCM_WTA_DISPATCH_1 (g_scm_positive_p, x, SCM_ARG1, s_scm_positive_p);
7090 }
7091 #undef FUNC_NAME
7092
7093
7094 SCM_PRIMITIVE_GENERIC (scm_negative_p, "negative?", 1, 0, 0,
7095 (SCM x),
7096 "Return @code{#t} if @var{x} is an exact or inexact number less than\n"
7097 "zero.")
7098 #define FUNC_NAME s_scm_negative_p
7099 {
7100 if (SCM_I_INUMP (x))
7101 return scm_from_bool (SCM_I_INUM (x) < 0);
7102 else if (SCM_BIGP (x))
7103 {
7104 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
7105 scm_remember_upto_here_1 (x);
7106 return scm_from_bool (sgn < 0);
7107 }
7108 else if (SCM_REALP (x))
7109 return scm_from_bool(SCM_REAL_VALUE (x) < 0.0);
7110 else if (SCM_FRACTIONP (x))
7111 return scm_negative_p (SCM_FRACTION_NUMERATOR (x));
7112 else
7113 SCM_WTA_DISPATCH_1 (g_scm_negative_p, x, SCM_ARG1, s_scm_negative_p);
7114 }
7115 #undef FUNC_NAME
7116
7117
7118 /* scm_min and scm_max return an inexact when either argument is inexact, as
7119 required by r5rs. On that basis, for exact/inexact combinations the
7120 exact is converted to inexact to compare and possibly return. This is
7121 unlike scm_less_p above which takes some trouble to preserve all bits in
7122 its test, such trouble is not required for min and max. */
7123
7124 SCM_PRIMITIVE_GENERIC (scm_i_max, "max", 0, 2, 1,
7125 (SCM x, SCM y, SCM rest),
7126 "Return the maximum of all parameter values.")
7127 #define FUNC_NAME s_scm_i_max
7128 {
7129 while (!scm_is_null (rest))
7130 { x = scm_max (x, y);
7131 y = scm_car (rest);
7132 rest = scm_cdr (rest);
7133 }
7134 return scm_max (x, y);
7135 }
7136 #undef FUNC_NAME
7137
7138 #define s_max s_scm_i_max
7139 #define g_max g_scm_i_max
7140
7141 SCM
7142 scm_max (SCM x, SCM y)
7143 {
7144 if (SCM_UNBNDP (y))
7145 {
7146 if (SCM_UNBNDP (x))
7147 SCM_WTA_DISPATCH_0 (g_max, s_max);
7148 else if (SCM_I_INUMP(x) || SCM_BIGP(x) || SCM_REALP(x) || SCM_FRACTIONP(x))
7149 return x;
7150 else
7151 SCM_WTA_DISPATCH_1 (g_max, x, SCM_ARG1, s_max);
7152 }
7153
7154 if (SCM_I_INUMP (x))
7155 {
7156 scm_t_inum xx = SCM_I_INUM (x);
7157 if (SCM_I_INUMP (y))
7158 {
7159 scm_t_inum yy = SCM_I_INUM (y);
7160 return (xx < yy) ? y : x;
7161 }
7162 else if (SCM_BIGP (y))
7163 {
7164 int sgn = mpz_sgn (SCM_I_BIG_MPZ (y));
7165 scm_remember_upto_here_1 (y);
7166 return (sgn < 0) ? x : y;
7167 }
7168 else if (SCM_REALP (y))
7169 {
7170 double xxd = xx;
7171 double yyd = SCM_REAL_VALUE (y);
7172
7173 if (xxd > yyd)
7174 return scm_from_double (xxd);
7175 /* If y is a NaN, then "==" is false and we return the NaN */
7176 else if (SCM_LIKELY (!(xxd == yyd)))
7177 return y;
7178 /* Handle signed zeroes properly */
7179 else if (xx == 0)
7180 return flo0;
7181 else
7182 return y;
7183 }
7184 else if (SCM_FRACTIONP (y))
7185 {
7186 use_less:
7187 return (scm_is_false (scm_less_p (x, y)) ? x : y);
7188 }
7189 else
7190 SCM_WTA_DISPATCH_2 (g_max, x, y, SCM_ARGn, s_max);
7191 }
7192 else if (SCM_BIGP (x))
7193 {
7194 if (SCM_I_INUMP (y))
7195 {
7196 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
7197 scm_remember_upto_here_1 (x);
7198 return (sgn < 0) ? y : x;
7199 }
7200 else if (SCM_BIGP (y))
7201 {
7202 int cmp = mpz_cmp (SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
7203 scm_remember_upto_here_2 (x, y);
7204 return (cmp > 0) ? x : y;
7205 }
7206 else if (SCM_REALP (y))
7207 {
7208 /* if y==NaN then xx>yy is false, so we return the NaN y */
7209 double xx, yy;
7210 big_real:
7211 xx = scm_i_big2dbl (x);
7212 yy = SCM_REAL_VALUE (y);
7213 return (xx > yy ? scm_from_double (xx) : y);
7214 }
7215 else if (SCM_FRACTIONP (y))
7216 {
7217 goto use_less;
7218 }
7219 else
7220 SCM_WTA_DISPATCH_2 (g_max, x, y, SCM_ARGn, s_max);
7221 }
7222 else if (SCM_REALP (x))
7223 {
7224 if (SCM_I_INUMP (y))
7225 {
7226 scm_t_inum yy = SCM_I_INUM (y);
7227 double xxd = SCM_REAL_VALUE (x);
7228 double yyd = yy;
7229
7230 if (yyd > xxd)
7231 return scm_from_double (yyd);
7232 /* If x is a NaN, then "==" is false and we return the NaN */
7233 else if (SCM_LIKELY (!(xxd == yyd)))
7234 return x;
7235 /* Handle signed zeroes properly */
7236 else if (yy == 0)
7237 return flo0;
7238 else
7239 return x;
7240 }
7241 else if (SCM_BIGP (y))
7242 {
7243 SCM_SWAP (x, y);
7244 goto big_real;
7245 }
7246 else if (SCM_REALP (y))
7247 {
7248 double xx = SCM_REAL_VALUE (x);
7249 double yy = SCM_REAL_VALUE (y);
7250
7251 /* For purposes of max: nan > +inf.0 > everything else,
7252 per the R6RS errata */
7253 if (xx > yy)
7254 return x;
7255 else if (SCM_LIKELY (xx < yy))
7256 return y;
7257 /* If neither (xx > yy) nor (xx < yy), then
7258 either they're equal or one is a NaN */
7259 else if (SCM_UNLIKELY (xx != yy))
7260 return (xx != xx) ? x : y; /* Return the NaN */
7261 /* xx == yy, but handle signed zeroes properly */
7262 else if (double_is_non_negative_zero (yy))
7263 return y;
7264 else
7265 return x;
7266 }
7267 else if (SCM_FRACTIONP (y))
7268 {
7269 double yy = scm_i_fraction2double (y);
7270 double xx = SCM_REAL_VALUE (x);
7271 return (xx < yy) ? scm_from_double (yy) : x;
7272 }
7273 else
7274 SCM_WTA_DISPATCH_2 (g_max, x, y, SCM_ARGn, s_max);
7275 }
7276 else if (SCM_FRACTIONP (x))
7277 {
7278 if (SCM_I_INUMP (y))
7279 {
7280 goto use_less;
7281 }
7282 else if (SCM_BIGP (y))
7283 {
7284 goto use_less;
7285 }
7286 else if (SCM_REALP (y))
7287 {
7288 double xx = scm_i_fraction2double (x);
7289 /* if y==NaN then ">" is false, so we return the NaN y */
7290 return (xx > SCM_REAL_VALUE (y)) ? scm_from_double (xx) : y;
7291 }
7292 else if (SCM_FRACTIONP (y))
7293 {
7294 goto use_less;
7295 }
7296 else
7297 SCM_WTA_DISPATCH_2 (g_max, x, y, SCM_ARGn, s_max);
7298 }
7299 else
7300 SCM_WTA_DISPATCH_2 (g_max, x, y, SCM_ARG1, s_max);
7301 }
7302
7303
7304 SCM_PRIMITIVE_GENERIC (scm_i_min, "min", 0, 2, 1,
7305 (SCM x, SCM y, SCM rest),
7306 "Return the minimum of all parameter values.")
7307 #define FUNC_NAME s_scm_i_min
7308 {
7309 while (!scm_is_null (rest))
7310 { x = scm_min (x, y);
7311 y = scm_car (rest);
7312 rest = scm_cdr (rest);
7313 }
7314 return scm_min (x, y);
7315 }
7316 #undef FUNC_NAME
7317
7318 #define s_min s_scm_i_min
7319 #define g_min g_scm_i_min
7320
7321 SCM
7322 scm_min (SCM x, SCM y)
7323 {
7324 if (SCM_UNBNDP (y))
7325 {
7326 if (SCM_UNBNDP (x))
7327 SCM_WTA_DISPATCH_0 (g_min, s_min);
7328 else if (SCM_I_INUMP(x) || SCM_BIGP(x) || SCM_REALP(x) || SCM_FRACTIONP(x))
7329 return x;
7330 else
7331 SCM_WTA_DISPATCH_1 (g_min, x, SCM_ARG1, s_min);
7332 }
7333
7334 if (SCM_I_INUMP (x))
7335 {
7336 scm_t_inum xx = SCM_I_INUM (x);
7337 if (SCM_I_INUMP (y))
7338 {
7339 scm_t_inum yy = SCM_I_INUM (y);
7340 return (xx < yy) ? x : y;
7341 }
7342 else if (SCM_BIGP (y))
7343 {
7344 int sgn = mpz_sgn (SCM_I_BIG_MPZ (y));
7345 scm_remember_upto_here_1 (y);
7346 return (sgn < 0) ? y : x;
7347 }
7348 else if (SCM_REALP (y))
7349 {
7350 double z = xx;
7351 /* if y==NaN then "<" is false and we return NaN */
7352 return (z < SCM_REAL_VALUE (y)) ? scm_from_double (z) : y;
7353 }
7354 else if (SCM_FRACTIONP (y))
7355 {
7356 use_less:
7357 return (scm_is_false (scm_less_p (x, y)) ? y : x);
7358 }
7359 else
7360 SCM_WTA_DISPATCH_2 (g_min, x, y, SCM_ARGn, s_min);
7361 }
7362 else if (SCM_BIGP (x))
7363 {
7364 if (SCM_I_INUMP (y))
7365 {
7366 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
7367 scm_remember_upto_here_1 (x);
7368 return (sgn < 0) ? x : y;
7369 }
7370 else if (SCM_BIGP (y))
7371 {
7372 int cmp = mpz_cmp (SCM_I_BIG_MPZ (x), SCM_I_BIG_MPZ (y));
7373 scm_remember_upto_here_2 (x, y);
7374 return (cmp > 0) ? y : x;
7375 }
7376 else if (SCM_REALP (y))
7377 {
7378 /* if y==NaN then xx<yy is false, so we return the NaN y */
7379 double xx, yy;
7380 big_real:
7381 xx = scm_i_big2dbl (x);
7382 yy = SCM_REAL_VALUE (y);
7383 return (xx < yy ? scm_from_double (xx) : y);
7384 }
7385 else if (SCM_FRACTIONP (y))
7386 {
7387 goto use_less;
7388 }
7389 else
7390 SCM_WTA_DISPATCH_2 (g_min, x, y, SCM_ARGn, s_min);
7391 }
7392 else if (SCM_REALP (x))
7393 {
7394 if (SCM_I_INUMP (y))
7395 {
7396 double z = SCM_I_INUM (y);
7397 /* if x==NaN then "<" is false and we return NaN */
7398 return (z < SCM_REAL_VALUE (x)) ? scm_from_double (z) : x;
7399 }
7400 else if (SCM_BIGP (y))
7401 {
7402 SCM_SWAP (x, y);
7403 goto big_real;
7404 }
7405 else if (SCM_REALP (y))
7406 {
7407 double xx = SCM_REAL_VALUE (x);
7408 double yy = SCM_REAL_VALUE (y);
7409
7410 /* For purposes of min: nan < -inf.0 < everything else,
7411 per the R6RS errata */
7412 if (xx < yy)
7413 return x;
7414 else if (SCM_LIKELY (xx > yy))
7415 return y;
7416 /* If neither (xx < yy) nor (xx > yy), then
7417 either they're equal or one is a NaN */
7418 else if (SCM_UNLIKELY (xx != yy))
7419 return (xx != xx) ? x : y; /* Return the NaN */
7420 /* xx == yy, but handle signed zeroes properly */
7421 else if (double_is_non_negative_zero (xx))
7422 return y;
7423 else
7424 return x;
7425 }
7426 else if (SCM_FRACTIONP (y))
7427 {
7428 double yy = scm_i_fraction2double (y);
7429 double xx = SCM_REAL_VALUE (x);
7430 return (yy < xx) ? scm_from_double (yy) : x;
7431 }
7432 else
7433 SCM_WTA_DISPATCH_2 (g_min, x, y, SCM_ARGn, s_min);
7434 }
7435 else if (SCM_FRACTIONP (x))
7436 {
7437 if (SCM_I_INUMP (y))
7438 {
7439 goto use_less;
7440 }
7441 else if (SCM_BIGP (y))
7442 {
7443 goto use_less;
7444 }
7445 else if (SCM_REALP (y))
7446 {
7447 double xx = scm_i_fraction2double (x);
7448 /* if y==NaN then "<" is false, so we return the NaN y */
7449 return (xx < SCM_REAL_VALUE (y)) ? scm_from_double (xx) : y;
7450 }
7451 else if (SCM_FRACTIONP (y))
7452 {
7453 goto use_less;
7454 }
7455 else
7456 SCM_WTA_DISPATCH_2 (g_min, x, y, SCM_ARGn, s_min);
7457 }
7458 else
7459 SCM_WTA_DISPATCH_2 (g_min, x, y, SCM_ARG1, s_min);
7460 }
7461
7462
7463 SCM_PRIMITIVE_GENERIC (scm_i_sum, "+", 0, 2, 1,
7464 (SCM x, SCM y, SCM rest),
7465 "Return the sum of all parameter values. Return 0 if called without\n"
7466 "any parameters." )
7467 #define FUNC_NAME s_scm_i_sum
7468 {
7469 while (!scm_is_null (rest))
7470 { x = scm_sum (x, y);
7471 y = scm_car (rest);
7472 rest = scm_cdr (rest);
7473 }
7474 return scm_sum (x, y);
7475 }
7476 #undef FUNC_NAME
7477
7478 #define s_sum s_scm_i_sum
7479 #define g_sum g_scm_i_sum
7480
7481 SCM
7482 scm_sum (SCM x, SCM y)
7483 {
7484 if (SCM_UNLIKELY (SCM_UNBNDP (y)))
7485 {
7486 if (SCM_NUMBERP (x)) return x;
7487 if (SCM_UNBNDP (x)) return SCM_INUM0;
7488 SCM_WTA_DISPATCH_1 (g_sum, x, SCM_ARG1, s_sum);
7489 }
7490
7491 if (SCM_LIKELY (SCM_I_INUMP (x)))
7492 {
7493 if (SCM_LIKELY (SCM_I_INUMP (y)))
7494 {
7495 scm_t_inum xx = SCM_I_INUM (x);
7496 scm_t_inum yy = SCM_I_INUM (y);
7497 scm_t_inum z = xx + yy;
7498 return SCM_FIXABLE (z) ? SCM_I_MAKINUM (z) : scm_i_inum2big (z);
7499 }
7500 else if (SCM_BIGP (y))
7501 {
7502 SCM_SWAP (x, y);
7503 goto add_big_inum;
7504 }
7505 else if (SCM_REALP (y))
7506 {
7507 scm_t_inum xx = SCM_I_INUM (x);
7508 return scm_from_double (xx + SCM_REAL_VALUE (y));
7509 }
7510 else if (SCM_COMPLEXP (y))
7511 {
7512 scm_t_inum xx = SCM_I_INUM (x);
7513 return scm_c_make_rectangular (xx + SCM_COMPLEX_REAL (y),
7514 SCM_COMPLEX_IMAG (y));
7515 }
7516 else if (SCM_FRACTIONP (y))
7517 return scm_i_make_ratio (scm_sum (SCM_FRACTION_NUMERATOR (y),
7518 scm_product (x, SCM_FRACTION_DENOMINATOR (y))),
7519 SCM_FRACTION_DENOMINATOR (y));
7520 else
7521 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARGn, s_sum);
7522 } else if (SCM_BIGP (x))
7523 {
7524 if (SCM_I_INUMP (y))
7525 {
7526 scm_t_inum inum;
7527 int bigsgn;
7528 add_big_inum:
7529 inum = SCM_I_INUM (y);
7530 if (inum == 0)
7531 return x;
7532 bigsgn = mpz_sgn (SCM_I_BIG_MPZ (x));
7533 if (inum < 0)
7534 {
7535 SCM result = scm_i_mkbig ();
7536 mpz_sub_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (x), - inum);
7537 scm_remember_upto_here_1 (x);
7538 /* we know the result will have to be a bignum */
7539 if (bigsgn == -1)
7540 return result;
7541 return scm_i_normbig (result);
7542 }
7543 else
7544 {
7545 SCM result = scm_i_mkbig ();
7546 mpz_add_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (x), inum);
7547 scm_remember_upto_here_1 (x);
7548 /* we know the result will have to be a bignum */
7549 if (bigsgn == 1)
7550 return result;
7551 return scm_i_normbig (result);
7552 }
7553 }
7554 else if (SCM_BIGP (y))
7555 {
7556 SCM result = scm_i_mkbig ();
7557 int sgn_x = mpz_sgn (SCM_I_BIG_MPZ (x));
7558 int sgn_y = mpz_sgn (SCM_I_BIG_MPZ (y));
7559 mpz_add (SCM_I_BIG_MPZ (result),
7560 SCM_I_BIG_MPZ (x),
7561 SCM_I_BIG_MPZ (y));
7562 scm_remember_upto_here_2 (x, y);
7563 /* we know the result will have to be a bignum */
7564 if (sgn_x == sgn_y)
7565 return result;
7566 return scm_i_normbig (result);
7567 }
7568 else if (SCM_REALP (y))
7569 {
7570 double result = mpz_get_d (SCM_I_BIG_MPZ (x)) + SCM_REAL_VALUE (y);
7571 scm_remember_upto_here_1 (x);
7572 return scm_from_double (result);
7573 }
7574 else if (SCM_COMPLEXP (y))
7575 {
7576 double real_part = (mpz_get_d (SCM_I_BIG_MPZ (x))
7577 + SCM_COMPLEX_REAL (y));
7578 scm_remember_upto_here_1 (x);
7579 return scm_c_make_rectangular (real_part, SCM_COMPLEX_IMAG (y));
7580 }
7581 else if (SCM_FRACTIONP (y))
7582 return scm_i_make_ratio (scm_sum (SCM_FRACTION_NUMERATOR (y),
7583 scm_product (x, SCM_FRACTION_DENOMINATOR (y))),
7584 SCM_FRACTION_DENOMINATOR (y));
7585 else
7586 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARGn, s_sum);
7587 }
7588 else if (SCM_REALP (x))
7589 {
7590 if (SCM_I_INUMP (y))
7591 return scm_from_double (SCM_REAL_VALUE (x) + SCM_I_INUM (y));
7592 else if (SCM_BIGP (y))
7593 {
7594 double result = mpz_get_d (SCM_I_BIG_MPZ (y)) + SCM_REAL_VALUE (x);
7595 scm_remember_upto_here_1 (y);
7596 return scm_from_double (result);
7597 }
7598 else if (SCM_REALP (y))
7599 return scm_from_double (SCM_REAL_VALUE (x) + SCM_REAL_VALUE (y));
7600 else if (SCM_COMPLEXP (y))
7601 return scm_c_make_rectangular (SCM_REAL_VALUE (x) + SCM_COMPLEX_REAL (y),
7602 SCM_COMPLEX_IMAG (y));
7603 else if (SCM_FRACTIONP (y))
7604 return scm_from_double (SCM_REAL_VALUE (x) + scm_i_fraction2double (y));
7605 else
7606 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARGn, s_sum);
7607 }
7608 else if (SCM_COMPLEXP (x))
7609 {
7610 if (SCM_I_INUMP (y))
7611 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) + SCM_I_INUM (y),
7612 SCM_COMPLEX_IMAG (x));
7613 else if (SCM_BIGP (y))
7614 {
7615 double real_part = (mpz_get_d (SCM_I_BIG_MPZ (y))
7616 + SCM_COMPLEX_REAL (x));
7617 scm_remember_upto_here_1 (y);
7618 return scm_c_make_rectangular (real_part, SCM_COMPLEX_IMAG (x));
7619 }
7620 else if (SCM_REALP (y))
7621 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) + SCM_REAL_VALUE (y),
7622 SCM_COMPLEX_IMAG (x));
7623 else if (SCM_COMPLEXP (y))
7624 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) + SCM_COMPLEX_REAL (y),
7625 SCM_COMPLEX_IMAG (x) + SCM_COMPLEX_IMAG (y));
7626 else if (SCM_FRACTIONP (y))
7627 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) + scm_i_fraction2double (y),
7628 SCM_COMPLEX_IMAG (x));
7629 else
7630 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARGn, s_sum);
7631 }
7632 else if (SCM_FRACTIONP (x))
7633 {
7634 if (SCM_I_INUMP (y))
7635 return scm_i_make_ratio (scm_sum (SCM_FRACTION_NUMERATOR (x),
7636 scm_product (y, SCM_FRACTION_DENOMINATOR (x))),
7637 SCM_FRACTION_DENOMINATOR (x));
7638 else if (SCM_BIGP (y))
7639 return scm_i_make_ratio (scm_sum (SCM_FRACTION_NUMERATOR (x),
7640 scm_product (y, SCM_FRACTION_DENOMINATOR (x))),
7641 SCM_FRACTION_DENOMINATOR (x));
7642 else if (SCM_REALP (y))
7643 return scm_from_double (SCM_REAL_VALUE (y) + scm_i_fraction2double (x));
7644 else if (SCM_COMPLEXP (y))
7645 return scm_c_make_rectangular (SCM_COMPLEX_REAL (y) + scm_i_fraction2double (x),
7646 SCM_COMPLEX_IMAG (y));
7647 else if (SCM_FRACTIONP (y))
7648 /* a/b + c/d = (ad + bc) / bd */
7649 return scm_i_make_ratio (scm_sum (scm_product (SCM_FRACTION_NUMERATOR (x), SCM_FRACTION_DENOMINATOR (y)),
7650 scm_product (SCM_FRACTION_NUMERATOR (y), SCM_FRACTION_DENOMINATOR (x))),
7651 scm_product (SCM_FRACTION_DENOMINATOR (x), SCM_FRACTION_DENOMINATOR (y)));
7652 else
7653 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARGn, s_sum);
7654 }
7655 else
7656 SCM_WTA_DISPATCH_2 (g_sum, x, y, SCM_ARG1, s_sum);
7657 }
7658
7659
7660 SCM_DEFINE (scm_oneplus, "1+", 1, 0, 0,
7661 (SCM x),
7662 "Return @math{@var{x}+1}.")
7663 #define FUNC_NAME s_scm_oneplus
7664 {
7665 return scm_sum (x, SCM_INUM1);
7666 }
7667 #undef FUNC_NAME
7668
7669
7670 SCM_PRIMITIVE_GENERIC (scm_i_difference, "-", 0, 2, 1,
7671 (SCM x, SCM y, SCM rest),
7672 "If called with one argument @var{z1}, -@var{z1} returned. Otherwise\n"
7673 "the sum of all but the first argument are subtracted from the first\n"
7674 "argument.")
7675 #define FUNC_NAME s_scm_i_difference
7676 {
7677 while (!scm_is_null (rest))
7678 { x = scm_difference (x, y);
7679 y = scm_car (rest);
7680 rest = scm_cdr (rest);
7681 }
7682 return scm_difference (x, y);
7683 }
7684 #undef FUNC_NAME
7685
7686 #define s_difference s_scm_i_difference
7687 #define g_difference g_scm_i_difference
7688
7689 SCM
7690 scm_difference (SCM x, SCM y)
7691 #define FUNC_NAME s_difference
7692 {
7693 if (SCM_UNLIKELY (SCM_UNBNDP (y)))
7694 {
7695 if (SCM_UNBNDP (x))
7696 SCM_WTA_DISPATCH_0 (g_difference, s_difference);
7697 else
7698 if (SCM_I_INUMP (x))
7699 {
7700 scm_t_inum xx = -SCM_I_INUM (x);
7701 if (SCM_FIXABLE (xx))
7702 return SCM_I_MAKINUM (xx);
7703 else
7704 return scm_i_inum2big (xx);
7705 }
7706 else if (SCM_BIGP (x))
7707 /* Must scm_i_normbig here because -SCM_MOST_NEGATIVE_FIXNUM is a
7708 bignum, but negating that gives a fixnum. */
7709 return scm_i_normbig (scm_i_clonebig (x, 0));
7710 else if (SCM_REALP (x))
7711 return scm_from_double (-SCM_REAL_VALUE (x));
7712 else if (SCM_COMPLEXP (x))
7713 return scm_c_make_rectangular (-SCM_COMPLEX_REAL (x),
7714 -SCM_COMPLEX_IMAG (x));
7715 else if (SCM_FRACTIONP (x))
7716 return scm_i_make_ratio_already_reduced
7717 (scm_difference (SCM_FRACTION_NUMERATOR (x), SCM_UNDEFINED),
7718 SCM_FRACTION_DENOMINATOR (x));
7719 else
7720 SCM_WTA_DISPATCH_1 (g_difference, x, SCM_ARG1, s_difference);
7721 }
7722
7723 if (SCM_LIKELY (SCM_I_INUMP (x)))
7724 {
7725 if (SCM_LIKELY (SCM_I_INUMP (y)))
7726 {
7727 scm_t_inum xx = SCM_I_INUM (x);
7728 scm_t_inum yy = SCM_I_INUM (y);
7729 scm_t_inum z = xx - yy;
7730 if (SCM_FIXABLE (z))
7731 return SCM_I_MAKINUM (z);
7732 else
7733 return scm_i_inum2big (z);
7734 }
7735 else if (SCM_BIGP (y))
7736 {
7737 /* inum-x - big-y */
7738 scm_t_inum xx = SCM_I_INUM (x);
7739
7740 if (xx == 0)
7741 {
7742 /* Must scm_i_normbig here because -SCM_MOST_NEGATIVE_FIXNUM is a
7743 bignum, but negating that gives a fixnum. */
7744 return scm_i_normbig (scm_i_clonebig (y, 0));
7745 }
7746 else
7747 {
7748 int sgn_y = mpz_sgn (SCM_I_BIG_MPZ (y));
7749 SCM result = scm_i_mkbig ();
7750
7751 if (xx >= 0)
7752 mpz_ui_sub (SCM_I_BIG_MPZ (result), xx, SCM_I_BIG_MPZ (y));
7753 else
7754 {
7755 /* x - y == -(y + -x) */
7756 mpz_add_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (y), -xx);
7757 mpz_neg (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result));
7758 }
7759 scm_remember_upto_here_1 (y);
7760
7761 if ((xx < 0 && (sgn_y > 0)) || ((xx > 0) && sgn_y < 0))
7762 /* we know the result will have to be a bignum */
7763 return result;
7764 else
7765 return scm_i_normbig (result);
7766 }
7767 }
7768 else if (SCM_REALP (y))
7769 {
7770 scm_t_inum xx = SCM_I_INUM (x);
7771
7772 /*
7773 * We need to handle x == exact 0
7774 * specially because R6RS states that:
7775 * (- 0.0) ==> -0.0 and
7776 * (- 0.0 0.0) ==> 0.0
7777 * and the scheme compiler changes
7778 * (- 0.0) into (- 0 0.0)
7779 * So we need to treat (- 0 0.0) like (- 0.0).
7780 * At the C level, (-x) is different than (0.0 - x).
7781 * (0.0 - 0.0) ==> 0.0, but (- 0.0) ==> -0.0.
7782 */
7783 if (xx == 0)
7784 return scm_from_double (- SCM_REAL_VALUE (y));
7785 else
7786 return scm_from_double (xx - SCM_REAL_VALUE (y));
7787 }
7788 else if (SCM_COMPLEXP (y))
7789 {
7790 scm_t_inum xx = SCM_I_INUM (x);
7791
7792 /* We need to handle x == exact 0 specially.
7793 See the comment above (for SCM_REALP (y)) */
7794 if (xx == 0)
7795 return scm_c_make_rectangular (- SCM_COMPLEX_REAL (y),
7796 - SCM_COMPLEX_IMAG (y));
7797 else
7798 return scm_c_make_rectangular (xx - SCM_COMPLEX_REAL (y),
7799 - SCM_COMPLEX_IMAG (y));
7800 }
7801 else if (SCM_FRACTIONP (y))
7802 /* a - b/c = (ac - b) / c */
7803 return scm_i_make_ratio (scm_difference (scm_product (x, SCM_FRACTION_DENOMINATOR (y)),
7804 SCM_FRACTION_NUMERATOR (y)),
7805 SCM_FRACTION_DENOMINATOR (y));
7806 else
7807 SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARGn, s_difference);
7808 }
7809 else if (SCM_BIGP (x))
7810 {
7811 if (SCM_I_INUMP (y))
7812 {
7813 /* big-x - inum-y */
7814 scm_t_inum yy = SCM_I_INUM (y);
7815 int sgn_x = mpz_sgn (SCM_I_BIG_MPZ (x));
7816
7817 scm_remember_upto_here_1 (x);
7818 if (sgn_x == 0)
7819 return (SCM_FIXABLE (-yy) ?
7820 SCM_I_MAKINUM (-yy) : scm_from_inum (-yy));
7821 else
7822 {
7823 SCM result = scm_i_mkbig ();
7824
7825 if (yy >= 0)
7826 mpz_sub_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (x), yy);
7827 else
7828 mpz_add_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (x), -yy);
7829 scm_remember_upto_here_1 (x);
7830
7831 if ((sgn_x < 0 && (yy > 0)) || ((sgn_x > 0) && yy < 0))
7832 /* we know the result will have to be a bignum */
7833 return result;
7834 else
7835 return scm_i_normbig (result);
7836 }
7837 }
7838 else if (SCM_BIGP (y))
7839 {
7840 int sgn_x = mpz_sgn (SCM_I_BIG_MPZ (x));
7841 int sgn_y = mpz_sgn (SCM_I_BIG_MPZ (y));
7842 SCM result = scm_i_mkbig ();
7843 mpz_sub (SCM_I_BIG_MPZ (result),
7844 SCM_I_BIG_MPZ (x),
7845 SCM_I_BIG_MPZ (y));
7846 scm_remember_upto_here_2 (x, y);
7847 /* we know the result will have to be a bignum */
7848 if ((sgn_x == 1) && (sgn_y == -1))
7849 return result;
7850 if ((sgn_x == -1) && (sgn_y == 1))
7851 return result;
7852 return scm_i_normbig (result);
7853 }
7854 else if (SCM_REALP (y))
7855 {
7856 double result = mpz_get_d (SCM_I_BIG_MPZ (x)) - SCM_REAL_VALUE (y);
7857 scm_remember_upto_here_1 (x);
7858 return scm_from_double (result);
7859 }
7860 else if (SCM_COMPLEXP (y))
7861 {
7862 double real_part = (mpz_get_d (SCM_I_BIG_MPZ (x))
7863 - SCM_COMPLEX_REAL (y));
7864 scm_remember_upto_here_1 (x);
7865 return scm_c_make_rectangular (real_part, - SCM_COMPLEX_IMAG (y));
7866 }
7867 else if (SCM_FRACTIONP (y))
7868 return scm_i_make_ratio (scm_difference (scm_product (x, SCM_FRACTION_DENOMINATOR (y)),
7869 SCM_FRACTION_NUMERATOR (y)),
7870 SCM_FRACTION_DENOMINATOR (y));
7871 else SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARGn, s_difference);
7872 }
7873 else if (SCM_REALP (x))
7874 {
7875 if (SCM_I_INUMP (y))
7876 return scm_from_double (SCM_REAL_VALUE (x) - SCM_I_INUM (y));
7877 else if (SCM_BIGP (y))
7878 {
7879 double result = SCM_REAL_VALUE (x) - mpz_get_d (SCM_I_BIG_MPZ (y));
7880 scm_remember_upto_here_1 (x);
7881 return scm_from_double (result);
7882 }
7883 else if (SCM_REALP (y))
7884 return scm_from_double (SCM_REAL_VALUE (x) - SCM_REAL_VALUE (y));
7885 else if (SCM_COMPLEXP (y))
7886 return scm_c_make_rectangular (SCM_REAL_VALUE (x) - SCM_COMPLEX_REAL (y),
7887 -SCM_COMPLEX_IMAG (y));
7888 else if (SCM_FRACTIONP (y))
7889 return scm_from_double (SCM_REAL_VALUE (x) - scm_i_fraction2double (y));
7890 else
7891 SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARGn, s_difference);
7892 }
7893 else if (SCM_COMPLEXP (x))
7894 {
7895 if (SCM_I_INUMP (y))
7896 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) - SCM_I_INUM (y),
7897 SCM_COMPLEX_IMAG (x));
7898 else if (SCM_BIGP (y))
7899 {
7900 double real_part = (SCM_COMPLEX_REAL (x)
7901 - mpz_get_d (SCM_I_BIG_MPZ (y)));
7902 scm_remember_upto_here_1 (x);
7903 return scm_c_make_rectangular (real_part, SCM_COMPLEX_IMAG (y));
7904 }
7905 else if (SCM_REALP (y))
7906 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) - SCM_REAL_VALUE (y),
7907 SCM_COMPLEX_IMAG (x));
7908 else if (SCM_COMPLEXP (y))
7909 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) - SCM_COMPLEX_REAL (y),
7910 SCM_COMPLEX_IMAG (x) - SCM_COMPLEX_IMAG (y));
7911 else if (SCM_FRACTIONP (y))
7912 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) - scm_i_fraction2double (y),
7913 SCM_COMPLEX_IMAG (x));
7914 else
7915 SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARGn, s_difference);
7916 }
7917 else if (SCM_FRACTIONP (x))
7918 {
7919 if (SCM_I_INUMP (y))
7920 /* a/b - c = (a - cb) / b */
7921 return scm_i_make_ratio (scm_difference (SCM_FRACTION_NUMERATOR (x),
7922 scm_product(y, SCM_FRACTION_DENOMINATOR (x))),
7923 SCM_FRACTION_DENOMINATOR (x));
7924 else if (SCM_BIGP (y))
7925 return scm_i_make_ratio (scm_difference (SCM_FRACTION_NUMERATOR (x),
7926 scm_product(y, SCM_FRACTION_DENOMINATOR (x))),
7927 SCM_FRACTION_DENOMINATOR (x));
7928 else if (SCM_REALP (y))
7929 return scm_from_double (scm_i_fraction2double (x) - SCM_REAL_VALUE (y));
7930 else if (SCM_COMPLEXP (y))
7931 return scm_c_make_rectangular (scm_i_fraction2double (x) - SCM_COMPLEX_REAL (y),
7932 -SCM_COMPLEX_IMAG (y));
7933 else if (SCM_FRACTIONP (y))
7934 /* a/b - c/d = (ad - bc) / bd */
7935 return scm_i_make_ratio (scm_difference (scm_product (SCM_FRACTION_NUMERATOR (x), SCM_FRACTION_DENOMINATOR (y)),
7936 scm_product (SCM_FRACTION_NUMERATOR (y), SCM_FRACTION_DENOMINATOR (x))),
7937 scm_product (SCM_FRACTION_DENOMINATOR (x), SCM_FRACTION_DENOMINATOR (y)));
7938 else
7939 SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARGn, s_difference);
7940 }
7941 else
7942 SCM_WTA_DISPATCH_2 (g_difference, x, y, SCM_ARG1, s_difference);
7943 }
7944 #undef FUNC_NAME
7945
7946
7947 SCM_DEFINE (scm_oneminus, "1-", 1, 0, 0,
7948 (SCM x),
7949 "Return @math{@var{x}-1}.")
7950 #define FUNC_NAME s_scm_oneminus
7951 {
7952 return scm_difference (x, SCM_INUM1);
7953 }
7954 #undef FUNC_NAME
7955
7956
7957 SCM_PRIMITIVE_GENERIC (scm_i_product, "*", 0, 2, 1,
7958 (SCM x, SCM y, SCM rest),
7959 "Return the product of all arguments. If called without arguments,\n"
7960 "1 is returned.")
7961 #define FUNC_NAME s_scm_i_product
7962 {
7963 while (!scm_is_null (rest))
7964 { x = scm_product (x, y);
7965 y = scm_car (rest);
7966 rest = scm_cdr (rest);
7967 }
7968 return scm_product (x, y);
7969 }
7970 #undef FUNC_NAME
7971
7972 #define s_product s_scm_i_product
7973 #define g_product g_scm_i_product
7974
7975 SCM
7976 scm_product (SCM x, SCM y)
7977 {
7978 if (SCM_UNLIKELY (SCM_UNBNDP (y)))
7979 {
7980 if (SCM_UNBNDP (x))
7981 return SCM_I_MAKINUM (1L);
7982 else if (SCM_NUMBERP (x))
7983 return x;
7984 else
7985 SCM_WTA_DISPATCH_1 (g_product, x, SCM_ARG1, s_product);
7986 }
7987
7988 if (SCM_LIKELY (SCM_I_INUMP (x)))
7989 {
7990 scm_t_inum xx;
7991
7992 xinum:
7993 xx = SCM_I_INUM (x);
7994
7995 switch (xx)
7996 {
7997 case 1:
7998 /* exact1 is the universal multiplicative identity */
7999 return y;
8000 break;
8001 case 0:
8002 /* exact0 times a fixnum is exact0: optimize this case */
8003 if (SCM_LIKELY (SCM_I_INUMP (y)))
8004 return SCM_INUM0;
8005 /* if the other argument is inexact, the result is inexact,
8006 and we must do the multiplication in order to handle
8007 infinities and NaNs properly. */
8008 else if (SCM_REALP (y))
8009 return scm_from_double (0.0 * SCM_REAL_VALUE (y));
8010 else if (SCM_COMPLEXP (y))
8011 return scm_c_make_rectangular (0.0 * SCM_COMPLEX_REAL (y),
8012 0.0 * SCM_COMPLEX_IMAG (y));
8013 /* we've already handled inexact numbers,
8014 so y must be exact, and we return exact0 */
8015 else if (SCM_NUMP (y))
8016 return SCM_INUM0;
8017 else
8018 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8019 break;
8020 case -1:
8021 /*
8022 * This case is important for more than just optimization.
8023 * It handles the case of negating
8024 * (+ 1 most-positive-fixnum) aka (- most-negative-fixnum),
8025 * which is a bignum that must be changed back into a fixnum.
8026 * Failure to do so will cause the following to return #f:
8027 * (= most-negative-fixnum (* -1 (- most-negative-fixnum)))
8028 */
8029 return scm_difference(y, SCM_UNDEFINED);
8030 break;
8031 }
8032
8033 if (SCM_LIKELY (SCM_I_INUMP (y)))
8034 {
8035 scm_t_inum yy = SCM_I_INUM (y);
8036 #if SCM_I_FIXNUM_BIT < 32 && SCM_HAVE_T_INT64
8037 scm_t_int64 kk = xx * (scm_t_int64) yy;
8038 if (SCM_FIXABLE (kk))
8039 return SCM_I_MAKINUM (kk);
8040 #else
8041 scm_t_inum axx = (xx > 0) ? xx : -xx;
8042 scm_t_inum ayy = (yy > 0) ? yy : -yy;
8043 if (SCM_MOST_POSITIVE_FIXNUM / axx >= ayy)
8044 return SCM_I_MAKINUM (xx * yy);
8045 #endif
8046 else
8047 {
8048 SCM result = scm_i_inum2big (xx);
8049 mpz_mul_si (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result), yy);
8050 return scm_i_normbig (result);
8051 }
8052 }
8053 else if (SCM_BIGP (y))
8054 {
8055 SCM result = scm_i_mkbig ();
8056 mpz_mul_si (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (y), xx);
8057 scm_remember_upto_here_1 (y);
8058 return result;
8059 }
8060 else if (SCM_REALP (y))
8061 return scm_from_double (xx * SCM_REAL_VALUE (y));
8062 else if (SCM_COMPLEXP (y))
8063 return scm_c_make_rectangular (xx * SCM_COMPLEX_REAL (y),
8064 xx * SCM_COMPLEX_IMAG (y));
8065 else if (SCM_FRACTIONP (y))
8066 return scm_i_make_ratio (scm_product (x, SCM_FRACTION_NUMERATOR (y)),
8067 SCM_FRACTION_DENOMINATOR (y));
8068 else
8069 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8070 }
8071 else if (SCM_BIGP (x))
8072 {
8073 if (SCM_I_INUMP (y))
8074 {
8075 SCM_SWAP (x, y);
8076 goto xinum;
8077 }
8078 else if (SCM_BIGP (y))
8079 {
8080 SCM result = scm_i_mkbig ();
8081 mpz_mul (SCM_I_BIG_MPZ (result),
8082 SCM_I_BIG_MPZ (x),
8083 SCM_I_BIG_MPZ (y));
8084 scm_remember_upto_here_2 (x, y);
8085 return result;
8086 }
8087 else if (SCM_REALP (y))
8088 {
8089 double result = mpz_get_d (SCM_I_BIG_MPZ (x)) * SCM_REAL_VALUE (y);
8090 scm_remember_upto_here_1 (x);
8091 return scm_from_double (result);
8092 }
8093 else if (SCM_COMPLEXP (y))
8094 {
8095 double z = mpz_get_d (SCM_I_BIG_MPZ (x));
8096 scm_remember_upto_here_1 (x);
8097 return scm_c_make_rectangular (z * SCM_COMPLEX_REAL (y),
8098 z * SCM_COMPLEX_IMAG (y));
8099 }
8100 else if (SCM_FRACTIONP (y))
8101 return scm_i_make_ratio (scm_product (x, SCM_FRACTION_NUMERATOR (y)),
8102 SCM_FRACTION_DENOMINATOR (y));
8103 else
8104 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8105 }
8106 else if (SCM_REALP (x))
8107 {
8108 if (SCM_I_INUMP (y))
8109 {
8110 SCM_SWAP (x, y);
8111 goto xinum;
8112 }
8113 else if (SCM_BIGP (y))
8114 {
8115 double result = mpz_get_d (SCM_I_BIG_MPZ (y)) * SCM_REAL_VALUE (x);
8116 scm_remember_upto_here_1 (y);
8117 return scm_from_double (result);
8118 }
8119 else if (SCM_REALP (y))
8120 return scm_from_double (SCM_REAL_VALUE (x) * SCM_REAL_VALUE (y));
8121 else if (SCM_COMPLEXP (y))
8122 return scm_c_make_rectangular (SCM_REAL_VALUE (x) * SCM_COMPLEX_REAL (y),
8123 SCM_REAL_VALUE (x) * SCM_COMPLEX_IMAG (y));
8124 else if (SCM_FRACTIONP (y))
8125 return scm_from_double (SCM_REAL_VALUE (x) * scm_i_fraction2double (y));
8126 else
8127 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8128 }
8129 else if (SCM_COMPLEXP (x))
8130 {
8131 if (SCM_I_INUMP (y))
8132 {
8133 SCM_SWAP (x, y);
8134 goto xinum;
8135 }
8136 else if (SCM_BIGP (y))
8137 {
8138 double z = mpz_get_d (SCM_I_BIG_MPZ (y));
8139 scm_remember_upto_here_1 (y);
8140 return scm_c_make_rectangular (z * SCM_COMPLEX_REAL (x),
8141 z * SCM_COMPLEX_IMAG (x));
8142 }
8143 else if (SCM_REALP (y))
8144 return scm_c_make_rectangular (SCM_REAL_VALUE (y) * SCM_COMPLEX_REAL (x),
8145 SCM_REAL_VALUE (y) * SCM_COMPLEX_IMAG (x));
8146 else if (SCM_COMPLEXP (y))
8147 {
8148 return scm_c_make_rectangular (SCM_COMPLEX_REAL (x) * SCM_COMPLEX_REAL (y)
8149 - SCM_COMPLEX_IMAG (x) * SCM_COMPLEX_IMAG (y),
8150 SCM_COMPLEX_REAL (x) * SCM_COMPLEX_IMAG (y)
8151 + SCM_COMPLEX_IMAG (x) * SCM_COMPLEX_REAL (y));
8152 }
8153 else if (SCM_FRACTIONP (y))
8154 {
8155 double yy = scm_i_fraction2double (y);
8156 return scm_c_make_rectangular (yy * SCM_COMPLEX_REAL (x),
8157 yy * SCM_COMPLEX_IMAG (x));
8158 }
8159 else
8160 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8161 }
8162 else if (SCM_FRACTIONP (x))
8163 {
8164 if (SCM_I_INUMP (y))
8165 return scm_i_make_ratio (scm_product (y, SCM_FRACTION_NUMERATOR (x)),
8166 SCM_FRACTION_DENOMINATOR (x));
8167 else if (SCM_BIGP (y))
8168 return scm_i_make_ratio (scm_product (y, SCM_FRACTION_NUMERATOR (x)),
8169 SCM_FRACTION_DENOMINATOR (x));
8170 else if (SCM_REALP (y))
8171 return scm_from_double (scm_i_fraction2double (x) * SCM_REAL_VALUE (y));
8172 else if (SCM_COMPLEXP (y))
8173 {
8174 double xx = scm_i_fraction2double (x);
8175 return scm_c_make_rectangular (xx * SCM_COMPLEX_REAL (y),
8176 xx * SCM_COMPLEX_IMAG (y));
8177 }
8178 else if (SCM_FRACTIONP (y))
8179 /* a/b * c/d = ac / bd */
8180 return scm_i_make_ratio (scm_product (SCM_FRACTION_NUMERATOR (x),
8181 SCM_FRACTION_NUMERATOR (y)),
8182 scm_product (SCM_FRACTION_DENOMINATOR (x),
8183 SCM_FRACTION_DENOMINATOR (y)));
8184 else
8185 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARGn, s_product);
8186 }
8187 else
8188 SCM_WTA_DISPATCH_2 (g_product, x, y, SCM_ARG1, s_product);
8189 }
8190
8191 #if ((defined (HAVE_ISINF) && defined (HAVE_ISNAN)) \
8192 || (defined (HAVE_FINITE) && defined (HAVE_ISNAN)))
8193 #define ALLOW_DIVIDE_BY_ZERO
8194 /* #define ALLOW_DIVIDE_BY_EXACT_ZERO */
8195 #endif
8196
8197 /* The code below for complex division is adapted from the GNU
8198 libstdc++, which adapted it from f2c's libF77, and is subject to
8199 this copyright: */
8200
8201 /****************************************************************
8202 Copyright 1990, 1991, 1992, 1993 by AT&T Bell Laboratories and Bellcore.
8203
8204 Permission to use, copy, modify, and distribute this software
8205 and its documentation for any purpose and without fee is hereby
8206 granted, provided that the above copyright notice appear in all
8207 copies and that both that the copyright notice and this
8208 permission notice and warranty disclaimer appear in supporting
8209 documentation, and that the names of AT&T Bell Laboratories or
8210 Bellcore or any of their entities not be used in advertising or
8211 publicity pertaining to distribution of the software without
8212 specific, written prior permission.
8213
8214 AT&T and Bellcore disclaim all warranties with regard to this
8215 software, including all implied warranties of merchantability
8216 and fitness. In no event shall AT&T or Bellcore be liable for
8217 any special, indirect or consequential damages or any damages
8218 whatsoever resulting from loss of use, data or profits, whether
8219 in an action of contract, negligence or other tortious action,
8220 arising out of or in connection with the use or performance of
8221 this software.
8222 ****************************************************************/
8223
8224 SCM_PRIMITIVE_GENERIC (scm_i_divide, "/", 0, 2, 1,
8225 (SCM x, SCM y, SCM rest),
8226 "Divide the first argument by the product of the remaining\n"
8227 "arguments. If called with one argument @var{z1}, 1/@var{z1} is\n"
8228 "returned.")
8229 #define FUNC_NAME s_scm_i_divide
8230 {
8231 while (!scm_is_null (rest))
8232 { x = scm_divide (x, y);
8233 y = scm_car (rest);
8234 rest = scm_cdr (rest);
8235 }
8236 return scm_divide (x, y);
8237 }
8238 #undef FUNC_NAME
8239
8240 #define s_divide s_scm_i_divide
8241 #define g_divide g_scm_i_divide
8242
8243 SCM
8244 scm_divide (SCM x, SCM y)
8245 #define FUNC_NAME s_divide
8246 {
8247 double a;
8248
8249 if (SCM_UNLIKELY (SCM_UNBNDP (y)))
8250 {
8251 if (SCM_UNBNDP (x))
8252 SCM_WTA_DISPATCH_0 (g_divide, s_divide);
8253 else if (SCM_I_INUMP (x))
8254 {
8255 scm_t_inum xx = SCM_I_INUM (x);
8256 if (xx == 1 || xx == -1)
8257 return x;
8258 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8259 else if (xx == 0)
8260 scm_num_overflow (s_divide);
8261 #endif
8262 else
8263 return scm_i_make_ratio_already_reduced (SCM_INUM1, x);
8264 }
8265 else if (SCM_BIGP (x))
8266 return scm_i_make_ratio_already_reduced (SCM_INUM1, x);
8267 else if (SCM_REALP (x))
8268 {
8269 double xx = SCM_REAL_VALUE (x);
8270 #ifndef ALLOW_DIVIDE_BY_ZERO
8271 if (xx == 0.0)
8272 scm_num_overflow (s_divide);
8273 else
8274 #endif
8275 return scm_from_double (1.0 / xx);
8276 }
8277 else if (SCM_COMPLEXP (x))
8278 {
8279 double r = SCM_COMPLEX_REAL (x);
8280 double i = SCM_COMPLEX_IMAG (x);
8281 if (fabs(r) <= fabs(i))
8282 {
8283 double t = r / i;
8284 double d = i * (1.0 + t * t);
8285 return scm_c_make_rectangular (t / d, -1.0 / d);
8286 }
8287 else
8288 {
8289 double t = i / r;
8290 double d = r * (1.0 + t * t);
8291 return scm_c_make_rectangular (1.0 / d, -t / d);
8292 }
8293 }
8294 else if (SCM_FRACTIONP (x))
8295 return scm_i_make_ratio_already_reduced (SCM_FRACTION_DENOMINATOR (x),
8296 SCM_FRACTION_NUMERATOR (x));
8297 else
8298 SCM_WTA_DISPATCH_1 (g_divide, x, SCM_ARG1, s_divide);
8299 }
8300
8301 if (SCM_LIKELY (SCM_I_INUMP (x)))
8302 {
8303 scm_t_inum xx = SCM_I_INUM (x);
8304 if (SCM_LIKELY (SCM_I_INUMP (y)))
8305 {
8306 scm_t_inum yy = SCM_I_INUM (y);
8307 if (yy == 0)
8308 {
8309 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8310 scm_num_overflow (s_divide);
8311 #else
8312 return scm_from_double ((double) xx / (double) yy);
8313 #endif
8314 }
8315 else if (xx % yy != 0)
8316 return scm_i_make_ratio (x, y);
8317 else
8318 {
8319 scm_t_inum z = xx / yy;
8320 if (SCM_FIXABLE (z))
8321 return SCM_I_MAKINUM (z);
8322 else
8323 return scm_i_inum2big (z);
8324 }
8325 }
8326 else if (SCM_BIGP (y))
8327 return scm_i_make_ratio (x, y);
8328 else if (SCM_REALP (y))
8329 {
8330 double yy = SCM_REAL_VALUE (y);
8331 #ifndef ALLOW_DIVIDE_BY_ZERO
8332 if (yy == 0.0)
8333 scm_num_overflow (s_divide);
8334 else
8335 #endif
8336 /* FIXME: Precision may be lost here due to:
8337 (1) The cast from 'scm_t_inum' to 'double'
8338 (2) Double rounding */
8339 return scm_from_double ((double) xx / yy);
8340 }
8341 else if (SCM_COMPLEXP (y))
8342 {
8343 a = xx;
8344 complex_div: /* y _must_ be a complex number */
8345 {
8346 double r = SCM_COMPLEX_REAL (y);
8347 double i = SCM_COMPLEX_IMAG (y);
8348 if (fabs(r) <= fabs(i))
8349 {
8350 double t = r / i;
8351 double d = i * (1.0 + t * t);
8352 return scm_c_make_rectangular ((a * t) / d, -a / d);
8353 }
8354 else
8355 {
8356 double t = i / r;
8357 double d = r * (1.0 + t * t);
8358 return scm_c_make_rectangular (a / d, -(a * t) / d);
8359 }
8360 }
8361 }
8362 else if (SCM_FRACTIONP (y))
8363 /* a / b/c = ac / b */
8364 return scm_i_make_ratio (scm_product (x, SCM_FRACTION_DENOMINATOR (y)),
8365 SCM_FRACTION_NUMERATOR (y));
8366 else
8367 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARGn, s_divide);
8368 }
8369 else if (SCM_BIGP (x))
8370 {
8371 if (SCM_I_INUMP (y))
8372 {
8373 scm_t_inum yy = SCM_I_INUM (y);
8374 if (yy == 0)
8375 {
8376 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8377 scm_num_overflow (s_divide);
8378 #else
8379 int sgn = mpz_sgn (SCM_I_BIG_MPZ (x));
8380 scm_remember_upto_here_1 (x);
8381 return (sgn == 0) ? scm_nan () : scm_inf ();
8382 #endif
8383 }
8384 else if (yy == 1)
8385 return x;
8386 else
8387 {
8388 /* FIXME: HMM, what are the relative performance issues here?
8389 We need to test. Is it faster on average to test
8390 divisible_p, then perform whichever operation, or is it
8391 faster to perform the integer div opportunistically and
8392 switch to real if there's a remainder? For now we take the
8393 middle ground: test, then if divisible, use the faster div
8394 func. */
8395
8396 scm_t_inum abs_yy = yy < 0 ? -yy : yy;
8397 int divisible_p = mpz_divisible_ui_p (SCM_I_BIG_MPZ (x), abs_yy);
8398
8399 if (divisible_p)
8400 {
8401 SCM result = scm_i_mkbig ();
8402 mpz_divexact_ui (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (x), abs_yy);
8403 scm_remember_upto_here_1 (x);
8404 if (yy < 0)
8405 mpz_neg (SCM_I_BIG_MPZ (result), SCM_I_BIG_MPZ (result));
8406 return scm_i_normbig (result);
8407 }
8408 else
8409 return scm_i_make_ratio (x, y);
8410 }
8411 }
8412 else if (SCM_BIGP (y))
8413 {
8414 int divisible_p = mpz_divisible_p (SCM_I_BIG_MPZ (x),
8415 SCM_I_BIG_MPZ (y));
8416 if (divisible_p)
8417 {
8418 SCM result = scm_i_mkbig ();
8419 mpz_divexact (SCM_I_BIG_MPZ (result),
8420 SCM_I_BIG_MPZ (x),
8421 SCM_I_BIG_MPZ (y));
8422 scm_remember_upto_here_2 (x, y);
8423 return scm_i_normbig (result);
8424 }
8425 else
8426 return scm_i_make_ratio (x, y);
8427 }
8428 else if (SCM_REALP (y))
8429 {
8430 double yy = SCM_REAL_VALUE (y);
8431 #ifndef ALLOW_DIVIDE_BY_ZERO
8432 if (yy == 0.0)
8433 scm_num_overflow (s_divide);
8434 else
8435 #endif
8436 /* FIXME: Precision may be lost here due to:
8437 (1) scm_i_big2dbl (2) Double rounding */
8438 return scm_from_double (scm_i_big2dbl (x) / yy);
8439 }
8440 else if (SCM_COMPLEXP (y))
8441 {
8442 a = scm_i_big2dbl (x);
8443 goto complex_div;
8444 }
8445 else if (SCM_FRACTIONP (y))
8446 return scm_i_make_ratio (scm_product (x, SCM_FRACTION_DENOMINATOR (y)),
8447 SCM_FRACTION_NUMERATOR (y));
8448 else
8449 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARGn, s_divide);
8450 }
8451 else if (SCM_REALP (x))
8452 {
8453 double rx = SCM_REAL_VALUE (x);
8454 if (SCM_I_INUMP (y))
8455 {
8456 scm_t_inum yy = SCM_I_INUM (y);
8457 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8458 if (yy == 0)
8459 scm_num_overflow (s_divide);
8460 else
8461 #endif
8462 /* FIXME: Precision may be lost here due to:
8463 (1) The cast from 'scm_t_inum' to 'double'
8464 (2) Double rounding */
8465 return scm_from_double (rx / (double) yy);
8466 }
8467 else if (SCM_BIGP (y))
8468 {
8469 /* FIXME: Precision may be lost here due to:
8470 (1) The conversion from bignum to double
8471 (2) Double rounding */
8472 double dby = mpz_get_d (SCM_I_BIG_MPZ (y));
8473 scm_remember_upto_here_1 (y);
8474 return scm_from_double (rx / dby);
8475 }
8476 else if (SCM_REALP (y))
8477 {
8478 double yy = SCM_REAL_VALUE (y);
8479 #ifndef ALLOW_DIVIDE_BY_ZERO
8480 if (yy == 0.0)
8481 scm_num_overflow (s_divide);
8482 else
8483 #endif
8484 return scm_from_double (rx / yy);
8485 }
8486 else if (SCM_COMPLEXP (y))
8487 {
8488 a = rx;
8489 goto complex_div;
8490 }
8491 else if (SCM_FRACTIONP (y))
8492 return scm_from_double (rx / scm_i_fraction2double (y));
8493 else
8494 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARGn, s_divide);
8495 }
8496 else if (SCM_COMPLEXP (x))
8497 {
8498 double rx = SCM_COMPLEX_REAL (x);
8499 double ix = SCM_COMPLEX_IMAG (x);
8500 if (SCM_I_INUMP (y))
8501 {
8502 scm_t_inum yy = SCM_I_INUM (y);
8503 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8504 if (yy == 0)
8505 scm_num_overflow (s_divide);
8506 else
8507 #endif
8508 {
8509 /* FIXME: Precision may be lost here due to:
8510 (1) The conversion from 'scm_t_inum' to double
8511 (2) Double rounding */
8512 double d = yy;
8513 return scm_c_make_rectangular (rx / d, ix / d);
8514 }
8515 }
8516 else if (SCM_BIGP (y))
8517 {
8518 /* FIXME: Precision may be lost here due to:
8519 (1) The conversion from bignum to double
8520 (2) Double rounding */
8521 double dby = mpz_get_d (SCM_I_BIG_MPZ (y));
8522 scm_remember_upto_here_1 (y);
8523 return scm_c_make_rectangular (rx / dby, ix / dby);
8524 }
8525 else if (SCM_REALP (y))
8526 {
8527 double yy = SCM_REAL_VALUE (y);
8528 #ifndef ALLOW_DIVIDE_BY_ZERO
8529 if (yy == 0.0)
8530 scm_num_overflow (s_divide);
8531 else
8532 #endif
8533 return scm_c_make_rectangular (rx / yy, ix / yy);
8534 }
8535 else if (SCM_COMPLEXP (y))
8536 {
8537 double ry = SCM_COMPLEX_REAL (y);
8538 double iy = SCM_COMPLEX_IMAG (y);
8539 if (fabs(ry) <= fabs(iy))
8540 {
8541 double t = ry / iy;
8542 double d = iy * (1.0 + t * t);
8543 return scm_c_make_rectangular ((rx * t + ix) / d, (ix * t - rx) / d);
8544 }
8545 else
8546 {
8547 double t = iy / ry;
8548 double d = ry * (1.0 + t * t);
8549 return scm_c_make_rectangular ((rx + ix * t) / d, (ix - rx * t) / d);
8550 }
8551 }
8552 else if (SCM_FRACTIONP (y))
8553 {
8554 /* FIXME: Precision may be lost here due to:
8555 (1) The conversion from fraction to double
8556 (2) Double rounding */
8557 double yy = scm_i_fraction2double (y);
8558 return scm_c_make_rectangular (rx / yy, ix / yy);
8559 }
8560 else
8561 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARGn, s_divide);
8562 }
8563 else if (SCM_FRACTIONP (x))
8564 {
8565 if (SCM_I_INUMP (y))
8566 {
8567 scm_t_inum yy = SCM_I_INUM (y);
8568 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
8569 if (yy == 0)
8570 scm_num_overflow (s_divide);
8571 else
8572 #endif
8573 return scm_i_make_ratio (SCM_FRACTION_NUMERATOR (x),
8574 scm_product (SCM_FRACTION_DENOMINATOR (x), y));
8575 }
8576 else if (SCM_BIGP (y))
8577 {
8578 return scm_i_make_ratio (SCM_FRACTION_NUMERATOR (x),
8579 scm_product (SCM_FRACTION_DENOMINATOR (x), y));
8580 }
8581 else if (SCM_REALP (y))
8582 {
8583 double yy = SCM_REAL_VALUE (y);
8584 #ifndef ALLOW_DIVIDE_BY_ZERO
8585 if (yy == 0.0)
8586 scm_num_overflow (s_divide);
8587 else
8588 #endif
8589 /* FIXME: Precision may be lost here due to:
8590 (1) The conversion from fraction to double
8591 (2) Double rounding */
8592 return scm_from_double (scm_i_fraction2double (x) / yy);
8593 }
8594 else if (SCM_COMPLEXP (y))
8595 {
8596 /* FIXME: Precision may be lost here due to:
8597 (1) The conversion from fraction to double
8598 (2) Double rounding */
8599 a = scm_i_fraction2double (x);
8600 goto complex_div;
8601 }
8602 else if (SCM_FRACTIONP (y))
8603 return scm_i_make_ratio (scm_product (SCM_FRACTION_NUMERATOR (x), SCM_FRACTION_DENOMINATOR (y)),
8604 scm_product (SCM_FRACTION_NUMERATOR (y), SCM_FRACTION_DENOMINATOR (x)));
8605 else
8606 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARGn, s_divide);
8607 }
8608 else
8609 SCM_WTA_DISPATCH_2 (g_divide, x, y, SCM_ARG1, s_divide);
8610 }
8611 #undef FUNC_NAME
8612
8613
8614 double
8615 scm_c_truncate (double x)
8616 {
8617 return trunc (x);
8618 }
8619
8620 /* scm_c_round is done using floor(x+0.5) to round to nearest and with
8621 half-way case (ie. when x is an integer plus 0.5) going upwards.
8622 Then half-way cases are identified and adjusted down if the
8623 round-upwards didn't give the desired even integer.
8624
8625 "plus_half == result" identifies a half-way case. If plus_half, which is
8626 x + 0.5, is an integer then x must be an integer plus 0.5.
8627
8628 An odd "result" value is identified with result/2 != floor(result/2).
8629 This is done with plus_half, since that value is ready for use sooner in
8630 a pipelined cpu, and we're already requiring plus_half == result.
8631
8632 Note however that we need to be careful when x is big and already an
8633 integer. In that case "x+0.5" may round to an adjacent integer, causing
8634 us to return such a value, incorrectly. For instance if the hardware is
8635 in the usual default nearest-even rounding, then for x = 0x1FFFFFFFFFFFFF
8636 (ie. 53 one bits) we will have x+0.5 = 0x20000000000000 and that value
8637 returned. Or if the hardware is in round-upwards mode, then other bigger
8638 values like say x == 2^128 will see x+0.5 rounding up to the next higher
8639 representable value, 2^128+2^76 (or whatever), again incorrect.
8640
8641 These bad roundings of x+0.5 are avoided by testing at the start whether
8642 x is already an integer. If it is then clearly that's the desired result
8643 already. And if it's not then the exponent must be small enough to allow
8644 an 0.5 to be represented, and hence added without a bad rounding. */
8645
8646 double
8647 scm_c_round (double x)
8648 {
8649 double plus_half, result;
8650
8651 if (x == floor (x))
8652 return x;
8653
8654 plus_half = x + 0.5;
8655 result = floor (plus_half);
8656 /* Adjust so that the rounding is towards even. */
8657 return ((plus_half == result && plus_half / 2 != floor (plus_half / 2))
8658 ? result - 1
8659 : result);
8660 }
8661
8662 SCM_PRIMITIVE_GENERIC (scm_truncate_number, "truncate", 1, 0, 0,
8663 (SCM x),
8664 "Round the number @var{x} towards zero.")
8665 #define FUNC_NAME s_scm_truncate_number
8666 {
8667 if (SCM_I_INUMP (x) || SCM_BIGP (x))
8668 return x;
8669 else if (SCM_REALP (x))
8670 return scm_from_double (trunc (SCM_REAL_VALUE (x)));
8671 else if (SCM_FRACTIONP (x))
8672 return scm_truncate_quotient (SCM_FRACTION_NUMERATOR (x),
8673 SCM_FRACTION_DENOMINATOR (x));
8674 else
8675 SCM_WTA_DISPATCH_1 (g_scm_truncate_number, x, SCM_ARG1,
8676 s_scm_truncate_number);
8677 }
8678 #undef FUNC_NAME
8679
8680 SCM_PRIMITIVE_GENERIC (scm_round_number, "round", 1, 0, 0,
8681 (SCM x),
8682 "Round the number @var{x} towards the nearest integer. "
8683 "When it is exactly halfway between two integers, "
8684 "round towards the even one.")
8685 #define FUNC_NAME s_scm_round_number
8686 {
8687 if (SCM_I_INUMP (x) || SCM_BIGP (x))
8688 return x;
8689 else if (SCM_REALP (x))
8690 return scm_from_double (scm_c_round (SCM_REAL_VALUE (x)));
8691 else if (SCM_FRACTIONP (x))
8692 return scm_round_quotient (SCM_FRACTION_NUMERATOR (x),
8693 SCM_FRACTION_DENOMINATOR (x));
8694 else
8695 SCM_WTA_DISPATCH_1 (g_scm_round_number, x, SCM_ARG1,
8696 s_scm_round_number);
8697 }
8698 #undef FUNC_NAME
8699
8700 SCM_PRIMITIVE_GENERIC (scm_floor, "floor", 1, 0, 0,
8701 (SCM x),
8702 "Round the number @var{x} towards minus infinity.")
8703 #define FUNC_NAME s_scm_floor
8704 {
8705 if (SCM_I_INUMP (x) || SCM_BIGP (x))
8706 return x;
8707 else if (SCM_REALP (x))
8708 return scm_from_double (floor (SCM_REAL_VALUE (x)));
8709 else if (SCM_FRACTIONP (x))
8710 return scm_floor_quotient (SCM_FRACTION_NUMERATOR (x),
8711 SCM_FRACTION_DENOMINATOR (x));
8712 else
8713 SCM_WTA_DISPATCH_1 (g_scm_floor, x, 1, s_scm_floor);
8714 }
8715 #undef FUNC_NAME
8716
8717 SCM_PRIMITIVE_GENERIC (scm_ceiling, "ceiling", 1, 0, 0,
8718 (SCM x),
8719 "Round the number @var{x} towards infinity.")
8720 #define FUNC_NAME s_scm_ceiling
8721 {
8722 if (SCM_I_INUMP (x) || SCM_BIGP (x))
8723 return x;
8724 else if (SCM_REALP (x))
8725 return scm_from_double (ceil (SCM_REAL_VALUE (x)));
8726 else if (SCM_FRACTIONP (x))
8727 return scm_ceiling_quotient (SCM_FRACTION_NUMERATOR (x),
8728 SCM_FRACTION_DENOMINATOR (x));
8729 else
8730 SCM_WTA_DISPATCH_1 (g_scm_ceiling, x, 1, s_scm_ceiling);
8731 }
8732 #undef FUNC_NAME
8733
8734 SCM_PRIMITIVE_GENERIC (scm_expt, "expt", 2, 0, 0,
8735 (SCM x, SCM y),
8736 "Return @var{x} raised to the power of @var{y}.")
8737 #define FUNC_NAME s_scm_expt
8738 {
8739 if (scm_is_integer (y))
8740 {
8741 if (scm_is_true (scm_exact_p (y)))
8742 return scm_integer_expt (x, y);
8743 else
8744 {
8745 /* Here we handle the case where the exponent is an inexact
8746 integer. We make the exponent exact in order to use
8747 scm_integer_expt, and thus avoid the spurious imaginary
8748 parts that may result from round-off errors in the general
8749 e^(y log x) method below (for example when squaring a large
8750 negative number). In this case, we must return an inexact
8751 result for correctness. We also make the base inexact so
8752 that scm_integer_expt will use fast inexact arithmetic
8753 internally. Note that making the base inexact is not
8754 sufficient to guarantee an inexact result, because
8755 scm_integer_expt will return an exact 1 when the exponent
8756 is 0, even if the base is inexact. */
8757 return scm_exact_to_inexact
8758 (scm_integer_expt (scm_exact_to_inexact (x),
8759 scm_inexact_to_exact (y)));
8760 }
8761 }
8762 else if (scm_is_real (x) && scm_is_real (y) && scm_to_double (x) >= 0.0)
8763 {
8764 return scm_from_double (pow (scm_to_double (x), scm_to_double (y)));
8765 }
8766 else if (scm_is_complex (x) && scm_is_complex (y))
8767 return scm_exp (scm_product (scm_log (x), y));
8768 else if (scm_is_complex (x))
8769 SCM_WTA_DISPATCH_2 (g_scm_expt, x, y, SCM_ARG2, s_scm_expt);
8770 else
8771 SCM_WTA_DISPATCH_2 (g_scm_expt, x, y, SCM_ARG1, s_scm_expt);
8772 }
8773 #undef FUNC_NAME
8774
8775 /* sin/cos/tan/asin/acos/atan
8776 sinh/cosh/tanh/asinh/acosh/atanh
8777 Derived from "Transcen.scm", Complex trancendental functions for SCM.
8778 Written by Jerry D. Hedden, (C) FSF.
8779 See the file `COPYING' for terms applying to this program. */
8780
8781 SCM_PRIMITIVE_GENERIC (scm_sin, "sin", 1, 0, 0,
8782 (SCM z),
8783 "Compute the sine of @var{z}.")
8784 #define FUNC_NAME s_scm_sin
8785 {
8786 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8787 return z; /* sin(exact0) = exact0 */
8788 else if (scm_is_real (z))
8789 return scm_from_double (sin (scm_to_double (z)));
8790 else if (SCM_COMPLEXP (z))
8791 { double x, y;
8792 x = SCM_COMPLEX_REAL (z);
8793 y = SCM_COMPLEX_IMAG (z);
8794 return scm_c_make_rectangular (sin (x) * cosh (y),
8795 cos (x) * sinh (y));
8796 }
8797 else
8798 SCM_WTA_DISPATCH_1 (g_scm_sin, z, 1, s_scm_sin);
8799 }
8800 #undef FUNC_NAME
8801
8802 SCM_PRIMITIVE_GENERIC (scm_cos, "cos", 1, 0, 0,
8803 (SCM z),
8804 "Compute the cosine of @var{z}.")
8805 #define FUNC_NAME s_scm_cos
8806 {
8807 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8808 return SCM_INUM1; /* cos(exact0) = exact1 */
8809 else if (scm_is_real (z))
8810 return scm_from_double (cos (scm_to_double (z)));
8811 else if (SCM_COMPLEXP (z))
8812 { double x, y;
8813 x = SCM_COMPLEX_REAL (z);
8814 y = SCM_COMPLEX_IMAG (z);
8815 return scm_c_make_rectangular (cos (x) * cosh (y),
8816 -sin (x) * sinh (y));
8817 }
8818 else
8819 SCM_WTA_DISPATCH_1 (g_scm_cos, z, 1, s_scm_cos);
8820 }
8821 #undef FUNC_NAME
8822
8823 SCM_PRIMITIVE_GENERIC (scm_tan, "tan", 1, 0, 0,
8824 (SCM z),
8825 "Compute the tangent of @var{z}.")
8826 #define FUNC_NAME s_scm_tan
8827 {
8828 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8829 return z; /* tan(exact0) = exact0 */
8830 else if (scm_is_real (z))
8831 return scm_from_double (tan (scm_to_double (z)));
8832 else if (SCM_COMPLEXP (z))
8833 { double x, y, w;
8834 x = 2.0 * SCM_COMPLEX_REAL (z);
8835 y = 2.0 * SCM_COMPLEX_IMAG (z);
8836 w = cos (x) + cosh (y);
8837 #ifndef ALLOW_DIVIDE_BY_ZERO
8838 if (w == 0.0)
8839 scm_num_overflow (s_scm_tan);
8840 #endif
8841 return scm_c_make_rectangular (sin (x) / w, sinh (y) / w);
8842 }
8843 else
8844 SCM_WTA_DISPATCH_1 (g_scm_tan, z, 1, s_scm_tan);
8845 }
8846 #undef FUNC_NAME
8847
8848 SCM_PRIMITIVE_GENERIC (scm_sinh, "sinh", 1, 0, 0,
8849 (SCM z),
8850 "Compute the hyperbolic sine of @var{z}.")
8851 #define FUNC_NAME s_scm_sinh
8852 {
8853 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8854 return z; /* sinh(exact0) = exact0 */
8855 else if (scm_is_real (z))
8856 return scm_from_double (sinh (scm_to_double (z)));
8857 else if (SCM_COMPLEXP (z))
8858 { double x, y;
8859 x = SCM_COMPLEX_REAL (z);
8860 y = SCM_COMPLEX_IMAG (z);
8861 return scm_c_make_rectangular (sinh (x) * cos (y),
8862 cosh (x) * sin (y));
8863 }
8864 else
8865 SCM_WTA_DISPATCH_1 (g_scm_sinh, z, 1, s_scm_sinh);
8866 }
8867 #undef FUNC_NAME
8868
8869 SCM_PRIMITIVE_GENERIC (scm_cosh, "cosh", 1, 0, 0,
8870 (SCM z),
8871 "Compute the hyperbolic cosine of @var{z}.")
8872 #define FUNC_NAME s_scm_cosh
8873 {
8874 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8875 return SCM_INUM1; /* cosh(exact0) = exact1 */
8876 else if (scm_is_real (z))
8877 return scm_from_double (cosh (scm_to_double (z)));
8878 else if (SCM_COMPLEXP (z))
8879 { double x, y;
8880 x = SCM_COMPLEX_REAL (z);
8881 y = SCM_COMPLEX_IMAG (z);
8882 return scm_c_make_rectangular (cosh (x) * cos (y),
8883 sinh (x) * sin (y));
8884 }
8885 else
8886 SCM_WTA_DISPATCH_1 (g_scm_cosh, z, 1, s_scm_cosh);
8887 }
8888 #undef FUNC_NAME
8889
8890 SCM_PRIMITIVE_GENERIC (scm_tanh, "tanh", 1, 0, 0,
8891 (SCM z),
8892 "Compute the hyperbolic tangent of @var{z}.")
8893 #define FUNC_NAME s_scm_tanh
8894 {
8895 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8896 return z; /* tanh(exact0) = exact0 */
8897 else if (scm_is_real (z))
8898 return scm_from_double (tanh (scm_to_double (z)));
8899 else if (SCM_COMPLEXP (z))
8900 { double x, y, w;
8901 x = 2.0 * SCM_COMPLEX_REAL (z);
8902 y = 2.0 * SCM_COMPLEX_IMAG (z);
8903 w = cosh (x) + cos (y);
8904 #ifndef ALLOW_DIVIDE_BY_ZERO
8905 if (w == 0.0)
8906 scm_num_overflow (s_scm_tanh);
8907 #endif
8908 return scm_c_make_rectangular (sinh (x) / w, sin (y) / w);
8909 }
8910 else
8911 SCM_WTA_DISPATCH_1 (g_scm_tanh, z, 1, s_scm_tanh);
8912 }
8913 #undef FUNC_NAME
8914
8915 SCM_PRIMITIVE_GENERIC (scm_asin, "asin", 1, 0, 0,
8916 (SCM z),
8917 "Compute the arc sine of @var{z}.")
8918 #define FUNC_NAME s_scm_asin
8919 {
8920 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8921 return z; /* asin(exact0) = exact0 */
8922 else if (scm_is_real (z))
8923 {
8924 double w = scm_to_double (z);
8925 if (w >= -1.0 && w <= 1.0)
8926 return scm_from_double (asin (w));
8927 else
8928 return scm_product (scm_c_make_rectangular (0, -1),
8929 scm_sys_asinh (scm_c_make_rectangular (0, w)));
8930 }
8931 else if (SCM_COMPLEXP (z))
8932 { double x, y;
8933 x = SCM_COMPLEX_REAL (z);
8934 y = SCM_COMPLEX_IMAG (z);
8935 return scm_product (scm_c_make_rectangular (0, -1),
8936 scm_sys_asinh (scm_c_make_rectangular (-y, x)));
8937 }
8938 else
8939 SCM_WTA_DISPATCH_1 (g_scm_asin, z, 1, s_scm_asin);
8940 }
8941 #undef FUNC_NAME
8942
8943 SCM_PRIMITIVE_GENERIC (scm_acos, "acos", 1, 0, 0,
8944 (SCM z),
8945 "Compute the arc cosine of @var{z}.")
8946 #define FUNC_NAME s_scm_acos
8947 {
8948 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM1)))
8949 return SCM_INUM0; /* acos(exact1) = exact0 */
8950 else if (scm_is_real (z))
8951 {
8952 double w = scm_to_double (z);
8953 if (w >= -1.0 && w <= 1.0)
8954 return scm_from_double (acos (w));
8955 else
8956 return scm_sum (scm_from_double (acos (0.0)),
8957 scm_product (scm_c_make_rectangular (0, 1),
8958 scm_sys_asinh (scm_c_make_rectangular (0, w))));
8959 }
8960 else if (SCM_COMPLEXP (z))
8961 { double x, y;
8962 x = SCM_COMPLEX_REAL (z);
8963 y = SCM_COMPLEX_IMAG (z);
8964 return scm_sum (scm_from_double (acos (0.0)),
8965 scm_product (scm_c_make_rectangular (0, 1),
8966 scm_sys_asinh (scm_c_make_rectangular (-y, x))));
8967 }
8968 else
8969 SCM_WTA_DISPATCH_1 (g_scm_acos, z, 1, s_scm_acos);
8970 }
8971 #undef FUNC_NAME
8972
8973 SCM_PRIMITIVE_GENERIC (scm_atan, "atan", 1, 1, 0,
8974 (SCM z, SCM y),
8975 "With one argument, compute the arc tangent of @var{z}.\n"
8976 "If @var{y} is present, compute the arc tangent of @var{z}/@var{y},\n"
8977 "using the sign of @var{z} and @var{y} to determine the quadrant.")
8978 #define FUNC_NAME s_scm_atan
8979 {
8980 if (SCM_UNBNDP (y))
8981 {
8982 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
8983 return z; /* atan(exact0) = exact0 */
8984 else if (scm_is_real (z))
8985 return scm_from_double (atan (scm_to_double (z)));
8986 else if (SCM_COMPLEXP (z))
8987 {
8988 double v, w;
8989 v = SCM_COMPLEX_REAL (z);
8990 w = SCM_COMPLEX_IMAG (z);
8991 return scm_divide (scm_log (scm_divide (scm_c_make_rectangular (v, w - 1.0),
8992 scm_c_make_rectangular (v, w + 1.0))),
8993 scm_c_make_rectangular (0, 2));
8994 }
8995 else
8996 SCM_WTA_DISPATCH_1 (g_scm_atan, z, SCM_ARG1, s_scm_atan);
8997 }
8998 else if (scm_is_real (z))
8999 {
9000 if (scm_is_real (y))
9001 return scm_from_double (atan2 (scm_to_double (z), scm_to_double (y)));
9002 else
9003 SCM_WTA_DISPATCH_2 (g_scm_atan, z, y, SCM_ARG2, s_scm_atan);
9004 }
9005 else
9006 SCM_WTA_DISPATCH_2 (g_scm_atan, z, y, SCM_ARG1, s_scm_atan);
9007 }
9008 #undef FUNC_NAME
9009
9010 SCM_PRIMITIVE_GENERIC (scm_sys_asinh, "asinh", 1, 0, 0,
9011 (SCM z),
9012 "Compute the inverse hyperbolic sine of @var{z}.")
9013 #define FUNC_NAME s_scm_sys_asinh
9014 {
9015 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
9016 return z; /* asinh(exact0) = exact0 */
9017 else if (scm_is_real (z))
9018 return scm_from_double (asinh (scm_to_double (z)));
9019 else if (scm_is_number (z))
9020 return scm_log (scm_sum (z,
9021 scm_sqrt (scm_sum (scm_product (z, z),
9022 SCM_INUM1))));
9023 else
9024 SCM_WTA_DISPATCH_1 (g_scm_sys_asinh, z, 1, s_scm_sys_asinh);
9025 }
9026 #undef FUNC_NAME
9027
9028 SCM_PRIMITIVE_GENERIC (scm_sys_acosh, "acosh", 1, 0, 0,
9029 (SCM z),
9030 "Compute the inverse hyperbolic cosine of @var{z}.")
9031 #define FUNC_NAME s_scm_sys_acosh
9032 {
9033 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM1)))
9034 return SCM_INUM0; /* acosh(exact1) = exact0 */
9035 else if (scm_is_real (z) && scm_to_double (z) >= 1.0)
9036 return scm_from_double (acosh (scm_to_double (z)));
9037 else if (scm_is_number (z))
9038 return scm_log (scm_sum (z,
9039 scm_sqrt (scm_difference (scm_product (z, z),
9040 SCM_INUM1))));
9041 else
9042 SCM_WTA_DISPATCH_1 (g_scm_sys_acosh, z, 1, s_scm_sys_acosh);
9043 }
9044 #undef FUNC_NAME
9045
9046 SCM_PRIMITIVE_GENERIC (scm_sys_atanh, "atanh", 1, 0, 0,
9047 (SCM z),
9048 "Compute the inverse hyperbolic tangent of @var{z}.")
9049 #define FUNC_NAME s_scm_sys_atanh
9050 {
9051 if (SCM_UNLIKELY (scm_is_eq (z, SCM_INUM0)))
9052 return z; /* atanh(exact0) = exact0 */
9053 else if (scm_is_real (z) && scm_to_double (z) >= -1.0 && scm_to_double (z) <= 1.0)
9054 return scm_from_double (atanh (scm_to_double (z)));
9055 else if (scm_is_number (z))
9056 return scm_divide (scm_log (scm_divide (scm_sum (SCM_INUM1, z),
9057 scm_difference (SCM_INUM1, z))),
9058 SCM_I_MAKINUM (2));
9059 else
9060 SCM_WTA_DISPATCH_1 (g_scm_sys_atanh, z, 1, s_scm_sys_atanh);
9061 }
9062 #undef FUNC_NAME
9063
9064 SCM
9065 scm_c_make_rectangular (double re, double im)
9066 {
9067 SCM z;
9068
9069 z = PTR2SCM (scm_gc_malloc_pointerless (sizeof (scm_t_complex),
9070 "complex"));
9071 SCM_SET_CELL_TYPE (z, scm_tc16_complex);
9072 SCM_COMPLEX_REAL (z) = re;
9073 SCM_COMPLEX_IMAG (z) = im;
9074 return z;
9075 }
9076
9077 SCM_DEFINE (scm_make_rectangular, "make-rectangular", 2, 0, 0,
9078 (SCM real_part, SCM imaginary_part),
9079 "Return a complex number constructed of the given @var{real_part} "
9080 "and @var{imaginary_part} parts.")
9081 #define FUNC_NAME s_scm_make_rectangular
9082 {
9083 SCM_ASSERT_TYPE (scm_is_real (real_part), real_part,
9084 SCM_ARG1, FUNC_NAME, "real");
9085 SCM_ASSERT_TYPE (scm_is_real (imaginary_part), imaginary_part,
9086 SCM_ARG2, FUNC_NAME, "real");
9087
9088 /* Return a real if and only if the imaginary_part is an _exact_ 0 */
9089 if (scm_is_eq (imaginary_part, SCM_INUM0))
9090 return real_part;
9091 else
9092 return scm_c_make_rectangular (scm_to_double (real_part),
9093 scm_to_double (imaginary_part));
9094 }
9095 #undef FUNC_NAME
9096
9097 SCM
9098 scm_c_make_polar (double mag, double ang)
9099 {
9100 double s, c;
9101
9102 /* The sincos(3) function is undocumented an broken on Tru64. Thus we only
9103 use it on Glibc-based systems that have it (it's a GNU extension). See
9104 http://lists.gnu.org/archive/html/guile-user/2009-04/msg00033.html for
9105 details. */
9106 #if (defined HAVE_SINCOS) && (defined __GLIBC__) && (defined _GNU_SOURCE)
9107 sincos (ang, &s, &c);
9108 #else
9109 s = sin (ang);
9110 c = cos (ang);
9111 #endif
9112
9113 /* If s and c are NaNs, this indicates that the angle is a NaN,
9114 infinite, or perhaps simply too large to determine its value
9115 mod 2*pi. However, we know something that the floating-point
9116 implementation doesn't know: We know that s and c are finite.
9117 Therefore, if the magnitude is zero, return a complex zero.
9118
9119 The reason we check for the NaNs instead of using this case
9120 whenever mag == 0.0 is because when the angle is known, we'd
9121 like to return the correct kind of non-real complex zero:
9122 +0.0+0.0i, -0.0+0.0i, -0.0-0.0i, or +0.0-0.0i, depending
9123 on which quadrant the angle is in.
9124 */
9125 if (SCM_UNLIKELY (isnan(s)) && isnan(c) && (mag == 0.0))
9126 return scm_c_make_rectangular (0.0, 0.0);
9127 else
9128 return scm_c_make_rectangular (mag * c, mag * s);
9129 }
9130
9131 SCM_DEFINE (scm_make_polar, "make-polar", 2, 0, 0,
9132 (SCM mag, SCM ang),
9133 "Return the complex number @var{mag} * e^(i * @var{ang}).")
9134 #define FUNC_NAME s_scm_make_polar
9135 {
9136 SCM_ASSERT_TYPE (scm_is_real (mag), mag, SCM_ARG1, FUNC_NAME, "real");
9137 SCM_ASSERT_TYPE (scm_is_real (ang), ang, SCM_ARG2, FUNC_NAME, "real");
9138
9139 /* If mag is exact0, return exact0 */
9140 if (scm_is_eq (mag, SCM_INUM0))
9141 return SCM_INUM0;
9142 /* Return a real if ang is exact0 */
9143 else if (scm_is_eq (ang, SCM_INUM0))
9144 return mag;
9145 else
9146 return scm_c_make_polar (scm_to_double (mag), scm_to_double (ang));
9147 }
9148 #undef FUNC_NAME
9149
9150
9151 SCM_PRIMITIVE_GENERIC (scm_real_part, "real-part", 1, 0, 0,
9152 (SCM z),
9153 "Return the real part of the number @var{z}.")
9154 #define FUNC_NAME s_scm_real_part
9155 {
9156 if (SCM_COMPLEXP (z))
9157 return scm_from_double (SCM_COMPLEX_REAL (z));
9158 else if (SCM_I_INUMP (z) || SCM_BIGP (z) || SCM_REALP (z) || SCM_FRACTIONP (z))
9159 return z;
9160 else
9161 SCM_WTA_DISPATCH_1 (g_scm_real_part, z, SCM_ARG1, s_scm_real_part);
9162 }
9163 #undef FUNC_NAME
9164
9165
9166 SCM_PRIMITIVE_GENERIC (scm_imag_part, "imag-part", 1, 0, 0,
9167 (SCM z),
9168 "Return the imaginary part of the number @var{z}.")
9169 #define FUNC_NAME s_scm_imag_part
9170 {
9171 if (SCM_COMPLEXP (z))
9172 return scm_from_double (SCM_COMPLEX_IMAG (z));
9173 else if (SCM_I_INUMP (z) || SCM_REALP (z) || SCM_BIGP (z) || SCM_FRACTIONP (z))
9174 return SCM_INUM0;
9175 else
9176 SCM_WTA_DISPATCH_1 (g_scm_imag_part, z, SCM_ARG1, s_scm_imag_part);
9177 }
9178 #undef FUNC_NAME
9179
9180 SCM_PRIMITIVE_GENERIC (scm_numerator, "numerator", 1, 0, 0,
9181 (SCM z),
9182 "Return the numerator of the number @var{z}.")
9183 #define FUNC_NAME s_scm_numerator
9184 {
9185 if (SCM_I_INUMP (z) || SCM_BIGP (z))
9186 return z;
9187 else if (SCM_FRACTIONP (z))
9188 return SCM_FRACTION_NUMERATOR (z);
9189 else if (SCM_REALP (z))
9190 return scm_exact_to_inexact (scm_numerator (scm_inexact_to_exact (z)));
9191 else
9192 SCM_WTA_DISPATCH_1 (g_scm_numerator, z, SCM_ARG1, s_scm_numerator);
9193 }
9194 #undef FUNC_NAME
9195
9196
9197 SCM_PRIMITIVE_GENERIC (scm_denominator, "denominator", 1, 0, 0,
9198 (SCM z),
9199 "Return the denominator of the number @var{z}.")
9200 #define FUNC_NAME s_scm_denominator
9201 {
9202 if (SCM_I_INUMP (z) || SCM_BIGP (z))
9203 return SCM_INUM1;
9204 else if (SCM_FRACTIONP (z))
9205 return SCM_FRACTION_DENOMINATOR (z);
9206 else if (SCM_REALP (z))
9207 return scm_exact_to_inexact (scm_denominator (scm_inexact_to_exact (z)));
9208 else
9209 SCM_WTA_DISPATCH_1 (g_scm_denominator, z, SCM_ARG1, s_scm_denominator);
9210 }
9211 #undef FUNC_NAME
9212
9213
9214 SCM_PRIMITIVE_GENERIC (scm_magnitude, "magnitude", 1, 0, 0,
9215 (SCM z),
9216 "Return the magnitude of the number @var{z}. This is the same as\n"
9217 "@code{abs} for real arguments, but also allows complex numbers.")
9218 #define FUNC_NAME s_scm_magnitude
9219 {
9220 if (SCM_I_INUMP (z))
9221 {
9222 scm_t_inum zz = SCM_I_INUM (z);
9223 if (zz >= 0)
9224 return z;
9225 else if (SCM_POSFIXABLE (-zz))
9226 return SCM_I_MAKINUM (-zz);
9227 else
9228 return scm_i_inum2big (-zz);
9229 }
9230 else if (SCM_BIGP (z))
9231 {
9232 int sgn = mpz_sgn (SCM_I_BIG_MPZ (z));
9233 scm_remember_upto_here_1 (z);
9234 if (sgn < 0)
9235 return scm_i_clonebig (z, 0);
9236 else
9237 return z;
9238 }
9239 else if (SCM_REALP (z))
9240 return scm_from_double (fabs (SCM_REAL_VALUE (z)));
9241 else if (SCM_COMPLEXP (z))
9242 return scm_from_double (hypot (SCM_COMPLEX_REAL (z), SCM_COMPLEX_IMAG (z)));
9243 else if (SCM_FRACTIONP (z))
9244 {
9245 if (scm_is_false (scm_negative_p (SCM_FRACTION_NUMERATOR (z))))
9246 return z;
9247 return scm_i_make_ratio_already_reduced
9248 (scm_difference (SCM_FRACTION_NUMERATOR (z), SCM_UNDEFINED),
9249 SCM_FRACTION_DENOMINATOR (z));
9250 }
9251 else
9252 SCM_WTA_DISPATCH_1 (g_scm_magnitude, z, SCM_ARG1, s_scm_magnitude);
9253 }
9254 #undef FUNC_NAME
9255
9256
9257 SCM_PRIMITIVE_GENERIC (scm_angle, "angle", 1, 0, 0,
9258 (SCM z),
9259 "Return the angle of the complex number @var{z}.")
9260 #define FUNC_NAME s_scm_angle
9261 {
9262 /* atan(0,-1) is pi and it'd be possible to have that as a constant like
9263 flo0 to save allocating a new flonum with scm_from_double each time.
9264 But if atan2 follows the floating point rounding mode, then the value
9265 is not a constant. Maybe it'd be close enough though. */
9266 if (SCM_I_INUMP (z))
9267 {
9268 if (SCM_I_INUM (z) >= 0)
9269 return flo0;
9270 else
9271 return scm_from_double (atan2 (0.0, -1.0));
9272 }
9273 else if (SCM_BIGP (z))
9274 {
9275 int sgn = mpz_sgn (SCM_I_BIG_MPZ (z));
9276 scm_remember_upto_here_1 (z);
9277 if (sgn < 0)
9278 return scm_from_double (atan2 (0.0, -1.0));
9279 else
9280 return flo0;
9281 }
9282 else if (SCM_REALP (z))
9283 {
9284 double x = SCM_REAL_VALUE (z);
9285 if (x > 0.0 || double_is_non_negative_zero (x))
9286 return flo0;
9287 else
9288 return scm_from_double (atan2 (0.0, -1.0));
9289 }
9290 else if (SCM_COMPLEXP (z))
9291 return scm_from_double (atan2 (SCM_COMPLEX_IMAG (z), SCM_COMPLEX_REAL (z)));
9292 else if (SCM_FRACTIONP (z))
9293 {
9294 if (scm_is_false (scm_negative_p (SCM_FRACTION_NUMERATOR (z))))
9295 return flo0;
9296 else return scm_from_double (atan2 (0.0, -1.0));
9297 }
9298 else
9299 SCM_WTA_DISPATCH_1 (g_scm_angle, z, SCM_ARG1, s_scm_angle);
9300 }
9301 #undef FUNC_NAME
9302
9303
9304 SCM_PRIMITIVE_GENERIC (scm_exact_to_inexact, "exact->inexact", 1, 0, 0,
9305 (SCM z),
9306 "Convert the number @var{z} to its inexact representation.\n")
9307 #define FUNC_NAME s_scm_exact_to_inexact
9308 {
9309 if (SCM_I_INUMP (z))
9310 return scm_from_double ((double) SCM_I_INUM (z));
9311 else if (SCM_BIGP (z))
9312 return scm_from_double (scm_i_big2dbl (z));
9313 else if (SCM_FRACTIONP (z))
9314 return scm_from_double (scm_i_fraction2double (z));
9315 else if (SCM_INEXACTP (z))
9316 return z;
9317 else
9318 SCM_WTA_DISPATCH_1 (g_scm_exact_to_inexact, z, 1, s_scm_exact_to_inexact);
9319 }
9320 #undef FUNC_NAME
9321
9322
9323 SCM_PRIMITIVE_GENERIC (scm_inexact_to_exact, "inexact->exact", 1, 0, 0,
9324 (SCM z),
9325 "Return an exact number that is numerically closest to @var{z}.")
9326 #define FUNC_NAME s_scm_inexact_to_exact
9327 {
9328 if (SCM_I_INUMP (z) || SCM_BIGP (z) || SCM_FRACTIONP (z))
9329 return z;
9330 else
9331 {
9332 double val;
9333
9334 if (SCM_REALP (z))
9335 val = SCM_REAL_VALUE (z);
9336 else if (SCM_COMPLEXP (z) && SCM_COMPLEX_IMAG (z) == 0.0)
9337 val = SCM_COMPLEX_REAL (z);
9338 else
9339 SCM_WTA_DISPATCH_1 (g_scm_inexact_to_exact, z, 1, s_scm_inexact_to_exact);
9340
9341 if (!SCM_LIKELY (DOUBLE_IS_FINITE (val)))
9342 SCM_OUT_OF_RANGE (1, z);
9343 else if (val == 0.0)
9344 return SCM_INUM0;
9345 else
9346 {
9347 int expon;
9348 SCM numerator;
9349
9350 numerator = scm_i_dbl2big (ldexp (frexp (val, &expon),
9351 DBL_MANT_DIG));
9352 expon -= DBL_MANT_DIG;
9353 if (expon < 0)
9354 {
9355 int shift = mpz_scan1 (SCM_I_BIG_MPZ (numerator), 0);
9356
9357 if (shift > -expon)
9358 shift = -expon;
9359 mpz_fdiv_q_2exp (SCM_I_BIG_MPZ (numerator),
9360 SCM_I_BIG_MPZ (numerator),
9361 shift);
9362 expon += shift;
9363 }
9364 numerator = scm_i_normbig (numerator);
9365 if (expon < 0)
9366 return scm_i_make_ratio_already_reduced
9367 (numerator, left_shift_exact_integer (SCM_INUM1, -expon));
9368 else if (expon > 0)
9369 return left_shift_exact_integer (numerator, expon);
9370 else
9371 return numerator;
9372 }
9373 }
9374 }
9375 #undef FUNC_NAME
9376
9377 SCM_DEFINE (scm_rationalize, "rationalize", 2, 0, 0,
9378 (SCM x, SCM eps),
9379 "Returns the @emph{simplest} rational number differing\n"
9380 "from @var{x} by no more than @var{eps}.\n"
9381 "\n"
9382 "As required by @acronym{R5RS}, @code{rationalize} only returns an\n"
9383 "exact result when both its arguments are exact. Thus, you might need\n"
9384 "to use @code{inexact->exact} on the arguments.\n"
9385 "\n"
9386 "@lisp\n"
9387 "(rationalize (inexact->exact 1.2) 1/100)\n"
9388 "@result{} 6/5\n"
9389 "@end lisp")
9390 #define FUNC_NAME s_scm_rationalize
9391 {
9392 SCM_ASSERT_TYPE (scm_is_real (x), x, SCM_ARG1, FUNC_NAME, "real");
9393 SCM_ASSERT_TYPE (scm_is_real (eps), eps, SCM_ARG2, FUNC_NAME, "real");
9394 eps = scm_abs (eps);
9395 if (scm_is_false (scm_positive_p (eps)))
9396 {
9397 /* eps is either zero or a NaN */
9398 if (scm_is_true (scm_nan_p (eps)))
9399 return scm_nan ();
9400 else if (SCM_INEXACTP (eps))
9401 return scm_exact_to_inexact (x);
9402 else
9403 return x;
9404 }
9405 else if (scm_is_false (scm_finite_p (eps)))
9406 {
9407 if (scm_is_true (scm_finite_p (x)))
9408 return flo0;
9409 else
9410 return scm_nan ();
9411 }
9412 else if (scm_is_false (scm_finite_p (x))) /* checks for both inf and nan */
9413 return x;
9414 else if (scm_is_false (scm_less_p (scm_floor (scm_sum (x, eps)),
9415 scm_ceiling (scm_difference (x, eps)))))
9416 {
9417 /* There's an integer within range; we want the one closest to zero */
9418 if (scm_is_false (scm_less_p (eps, scm_abs (x))))
9419 {
9420 /* zero is within range */
9421 if (SCM_INEXACTP (x) || SCM_INEXACTP (eps))
9422 return flo0;
9423 else
9424 return SCM_INUM0;
9425 }
9426 else if (scm_is_true (scm_positive_p (x)))
9427 return scm_ceiling (scm_difference (x, eps));
9428 else
9429 return scm_floor (scm_sum (x, eps));
9430 }
9431 else
9432 {
9433 /* Use continued fractions to find closest ratio. All
9434 arithmetic is done with exact numbers.
9435 */
9436
9437 SCM ex = scm_inexact_to_exact (x);
9438 SCM int_part = scm_floor (ex);
9439 SCM tt = SCM_INUM1;
9440 SCM a1 = SCM_INUM0, a2 = SCM_INUM1, a = SCM_INUM0;
9441 SCM b1 = SCM_INUM1, b2 = SCM_INUM0, b = SCM_INUM0;
9442 SCM rx;
9443 int i = 0;
9444
9445 ex = scm_difference (ex, int_part); /* x = x-int_part */
9446 rx = scm_divide (ex, SCM_UNDEFINED); /* rx = 1/x */
9447
9448 /* We stop after a million iterations just to be absolutely sure
9449 that we don't go into an infinite loop. The process normally
9450 converges after less than a dozen iterations.
9451 */
9452
9453 while (++i < 1000000)
9454 {
9455 a = scm_sum (scm_product (a1, tt), a2); /* a = a1*tt + a2 */
9456 b = scm_sum (scm_product (b1, tt), b2); /* b = b1*tt + b2 */
9457 if (scm_is_false (scm_zero_p (b)) && /* b != 0 */
9458 scm_is_false
9459 (scm_gr_p (scm_abs (scm_difference (ex, scm_divide (a, b))),
9460 eps))) /* abs(x-a/b) <= eps */
9461 {
9462 SCM res = scm_sum (int_part, scm_divide (a, b));
9463 if (SCM_INEXACTP (x) || SCM_INEXACTP (eps))
9464 return scm_exact_to_inexact (res);
9465 else
9466 return res;
9467 }
9468 rx = scm_divide (scm_difference (rx, tt), /* rx = 1/(rx - tt) */
9469 SCM_UNDEFINED);
9470 tt = scm_floor (rx); /* tt = floor (rx) */
9471 a2 = a1;
9472 b2 = b1;
9473 a1 = a;
9474 b1 = b;
9475 }
9476 scm_num_overflow (s_scm_rationalize);
9477 }
9478 }
9479 #undef FUNC_NAME
9480
9481 /* conversion functions */
9482
9483 int
9484 scm_is_integer (SCM val)
9485 {
9486 return scm_is_true (scm_integer_p (val));
9487 }
9488
9489 int
9490 scm_is_signed_integer (SCM val, scm_t_intmax min, scm_t_intmax max)
9491 {
9492 if (SCM_I_INUMP (val))
9493 {
9494 scm_t_signed_bits n = SCM_I_INUM (val);
9495 return n >= min && n <= max;
9496 }
9497 else if (SCM_BIGP (val))
9498 {
9499 if (min >= SCM_MOST_NEGATIVE_FIXNUM && max <= SCM_MOST_POSITIVE_FIXNUM)
9500 return 0;
9501 else if (min >= LONG_MIN && max <= LONG_MAX)
9502 {
9503 if (mpz_fits_slong_p (SCM_I_BIG_MPZ (val)))
9504 {
9505 long n = mpz_get_si (SCM_I_BIG_MPZ (val));
9506 return n >= min && n <= max;
9507 }
9508 else
9509 return 0;
9510 }
9511 else
9512 {
9513 scm_t_intmax n;
9514 size_t count;
9515
9516 if (mpz_sizeinbase (SCM_I_BIG_MPZ (val), 2)
9517 > CHAR_BIT*sizeof (scm_t_uintmax))
9518 return 0;
9519
9520 mpz_export (&n, &count, 1, sizeof (scm_t_uintmax), 0, 0,
9521 SCM_I_BIG_MPZ (val));
9522
9523 if (mpz_sgn (SCM_I_BIG_MPZ (val)) >= 0)
9524 {
9525 if (n < 0)
9526 return 0;
9527 }
9528 else
9529 {
9530 n = -n;
9531 if (n >= 0)
9532 return 0;
9533 }
9534
9535 return n >= min && n <= max;
9536 }
9537 }
9538 else
9539 return 0;
9540 }
9541
9542 int
9543 scm_is_unsigned_integer (SCM val, scm_t_uintmax min, scm_t_uintmax max)
9544 {
9545 if (SCM_I_INUMP (val))
9546 {
9547 scm_t_signed_bits n = SCM_I_INUM (val);
9548 return n >= 0 && ((scm_t_uintmax)n) >= min && ((scm_t_uintmax)n) <= max;
9549 }
9550 else if (SCM_BIGP (val))
9551 {
9552 if (max <= SCM_MOST_POSITIVE_FIXNUM)
9553 return 0;
9554 else if (max <= ULONG_MAX)
9555 {
9556 if (mpz_fits_ulong_p (SCM_I_BIG_MPZ (val)))
9557 {
9558 unsigned long n = mpz_get_ui (SCM_I_BIG_MPZ (val));
9559 return n >= min && n <= max;
9560 }
9561 else
9562 return 0;
9563 }
9564 else
9565 {
9566 scm_t_uintmax n;
9567 size_t count;
9568
9569 if (mpz_sgn (SCM_I_BIG_MPZ (val)) < 0)
9570 return 0;
9571
9572 if (mpz_sizeinbase (SCM_I_BIG_MPZ (val), 2)
9573 > CHAR_BIT*sizeof (scm_t_uintmax))
9574 return 0;
9575
9576 mpz_export (&n, &count, 1, sizeof (scm_t_uintmax), 0, 0,
9577 SCM_I_BIG_MPZ (val));
9578
9579 return n >= min && n <= max;
9580 }
9581 }
9582 else
9583 return 0;
9584 }
9585
9586 static void
9587 scm_i_range_error (SCM bad_val, SCM min, SCM max)
9588 {
9589 scm_error (scm_out_of_range_key,
9590 NULL,
9591 "Value out of range ~S to ~S: ~S",
9592 scm_list_3 (min, max, bad_val),
9593 scm_list_1 (bad_val));
9594 }
9595
9596 #define TYPE scm_t_intmax
9597 #define TYPE_MIN min
9598 #define TYPE_MAX max
9599 #define SIZEOF_TYPE 0
9600 #define SCM_TO_TYPE_PROTO(arg) scm_to_signed_integer (arg, scm_t_intmax min, scm_t_intmax max)
9601 #define SCM_FROM_TYPE_PROTO(arg) scm_from_signed_integer (arg)
9602 #include "libguile/conv-integer.i.c"
9603
9604 #define TYPE scm_t_uintmax
9605 #define TYPE_MIN min
9606 #define TYPE_MAX max
9607 #define SIZEOF_TYPE 0
9608 #define SCM_TO_TYPE_PROTO(arg) scm_to_unsigned_integer (arg, scm_t_uintmax min, scm_t_uintmax max)
9609 #define SCM_FROM_TYPE_PROTO(arg) scm_from_unsigned_integer (arg)
9610 #include "libguile/conv-uinteger.i.c"
9611
9612 #define TYPE scm_t_int8
9613 #define TYPE_MIN SCM_T_INT8_MIN
9614 #define TYPE_MAX SCM_T_INT8_MAX
9615 #define SIZEOF_TYPE 1
9616 #define SCM_TO_TYPE_PROTO(arg) scm_to_int8 (arg)
9617 #define SCM_FROM_TYPE_PROTO(arg) scm_from_int8 (arg)
9618 #include "libguile/conv-integer.i.c"
9619
9620 #define TYPE scm_t_uint8
9621 #define TYPE_MIN 0
9622 #define TYPE_MAX SCM_T_UINT8_MAX
9623 #define SIZEOF_TYPE 1
9624 #define SCM_TO_TYPE_PROTO(arg) scm_to_uint8 (arg)
9625 #define SCM_FROM_TYPE_PROTO(arg) scm_from_uint8 (arg)
9626 #include "libguile/conv-uinteger.i.c"
9627
9628 #define TYPE scm_t_int16
9629 #define TYPE_MIN SCM_T_INT16_MIN
9630 #define TYPE_MAX SCM_T_INT16_MAX
9631 #define SIZEOF_TYPE 2
9632 #define SCM_TO_TYPE_PROTO(arg) scm_to_int16 (arg)
9633 #define SCM_FROM_TYPE_PROTO(arg) scm_from_int16 (arg)
9634 #include "libguile/conv-integer.i.c"
9635
9636 #define TYPE scm_t_uint16
9637 #define TYPE_MIN 0
9638 #define TYPE_MAX SCM_T_UINT16_MAX
9639 #define SIZEOF_TYPE 2
9640 #define SCM_TO_TYPE_PROTO(arg) scm_to_uint16 (arg)
9641 #define SCM_FROM_TYPE_PROTO(arg) scm_from_uint16 (arg)
9642 #include "libguile/conv-uinteger.i.c"
9643
9644 #define TYPE scm_t_int32
9645 #define TYPE_MIN SCM_T_INT32_MIN
9646 #define TYPE_MAX SCM_T_INT32_MAX
9647 #define SIZEOF_TYPE 4
9648 #define SCM_TO_TYPE_PROTO(arg) scm_to_int32 (arg)
9649 #define SCM_FROM_TYPE_PROTO(arg) scm_from_int32 (arg)
9650 #include "libguile/conv-integer.i.c"
9651
9652 #define TYPE scm_t_uint32
9653 #define TYPE_MIN 0
9654 #define TYPE_MAX SCM_T_UINT32_MAX
9655 #define SIZEOF_TYPE 4
9656 #define SCM_TO_TYPE_PROTO(arg) scm_to_uint32 (arg)
9657 #define SCM_FROM_TYPE_PROTO(arg) scm_from_uint32 (arg)
9658 #include "libguile/conv-uinteger.i.c"
9659
9660 #define TYPE scm_t_wchar
9661 #define TYPE_MIN (scm_t_int32)-1
9662 #define TYPE_MAX (scm_t_int32)0x10ffff
9663 #define SIZEOF_TYPE 4
9664 #define SCM_TO_TYPE_PROTO(arg) scm_to_wchar (arg)
9665 #define SCM_FROM_TYPE_PROTO(arg) scm_from_wchar (arg)
9666 #include "libguile/conv-integer.i.c"
9667
9668 #define TYPE scm_t_int64
9669 #define TYPE_MIN SCM_T_INT64_MIN
9670 #define TYPE_MAX SCM_T_INT64_MAX
9671 #define SIZEOF_TYPE 8
9672 #define SCM_TO_TYPE_PROTO(arg) scm_to_int64 (arg)
9673 #define SCM_FROM_TYPE_PROTO(arg) scm_from_int64 (arg)
9674 #include "libguile/conv-integer.i.c"
9675
9676 #define TYPE scm_t_uint64
9677 #define TYPE_MIN 0
9678 #define TYPE_MAX SCM_T_UINT64_MAX
9679 #define SIZEOF_TYPE 8
9680 #define SCM_TO_TYPE_PROTO(arg) scm_to_uint64 (arg)
9681 #define SCM_FROM_TYPE_PROTO(arg) scm_from_uint64 (arg)
9682 #include "libguile/conv-uinteger.i.c"
9683
9684 void
9685 scm_to_mpz (SCM val, mpz_t rop)
9686 {
9687 if (SCM_I_INUMP (val))
9688 mpz_set_si (rop, SCM_I_INUM (val));
9689 else if (SCM_BIGP (val))
9690 mpz_set (rop, SCM_I_BIG_MPZ (val));
9691 else
9692 scm_wrong_type_arg_msg (NULL, 0, val, "exact integer");
9693 }
9694
9695 SCM
9696 scm_from_mpz (mpz_t val)
9697 {
9698 return scm_i_mpz2num (val);
9699 }
9700
9701 int
9702 scm_is_real (SCM val)
9703 {
9704 return scm_is_true (scm_real_p (val));
9705 }
9706
9707 int
9708 scm_is_rational (SCM val)
9709 {
9710 return scm_is_true (scm_rational_p (val));
9711 }
9712
9713 double
9714 scm_to_double (SCM val)
9715 {
9716 if (SCM_I_INUMP (val))
9717 return SCM_I_INUM (val);
9718 else if (SCM_BIGP (val))
9719 return scm_i_big2dbl (val);
9720 else if (SCM_FRACTIONP (val))
9721 return scm_i_fraction2double (val);
9722 else if (SCM_REALP (val))
9723 return SCM_REAL_VALUE (val);
9724 else
9725 scm_wrong_type_arg_msg (NULL, 0, val, "real number");
9726 }
9727
9728 SCM
9729 scm_from_double (double val)
9730 {
9731 SCM z;
9732
9733 z = PTR2SCM (scm_gc_malloc_pointerless (sizeof (scm_t_double), "real"));
9734
9735 SCM_SET_CELL_TYPE (z, scm_tc16_real);
9736 SCM_REAL_VALUE (z) = val;
9737
9738 return z;
9739 }
9740
9741 #if SCM_ENABLE_DEPRECATED == 1
9742
9743 float
9744 scm_num2float (SCM num, unsigned long pos, const char *s_caller)
9745 {
9746 scm_c_issue_deprecation_warning
9747 ("`scm_num2float' is deprecated. Use scm_to_double instead.");
9748
9749 if (SCM_BIGP (num))
9750 {
9751 float res = mpz_get_d (SCM_I_BIG_MPZ (num));
9752 if (!isinf (res))
9753 return res;
9754 else
9755 scm_out_of_range (NULL, num);
9756 }
9757 else
9758 return scm_to_double (num);
9759 }
9760
9761 double
9762 scm_num2double (SCM num, unsigned long pos, const char *s_caller)
9763 {
9764 scm_c_issue_deprecation_warning
9765 ("`scm_num2double' is deprecated. Use scm_to_double instead.");
9766
9767 if (SCM_BIGP (num))
9768 {
9769 double res = mpz_get_d (SCM_I_BIG_MPZ (num));
9770 if (!isinf (res))
9771 return res;
9772 else
9773 scm_out_of_range (NULL, num);
9774 }
9775 else
9776 return scm_to_double (num);
9777 }
9778
9779 #endif
9780
9781 int
9782 scm_is_complex (SCM val)
9783 {
9784 return scm_is_true (scm_complex_p (val));
9785 }
9786
9787 double
9788 scm_c_real_part (SCM z)
9789 {
9790 if (SCM_COMPLEXP (z))
9791 return SCM_COMPLEX_REAL (z);
9792 else
9793 {
9794 /* Use the scm_real_part to get proper error checking and
9795 dispatching.
9796 */
9797 return scm_to_double (scm_real_part (z));
9798 }
9799 }
9800
9801 double
9802 scm_c_imag_part (SCM z)
9803 {
9804 if (SCM_COMPLEXP (z))
9805 return SCM_COMPLEX_IMAG (z);
9806 else
9807 {
9808 /* Use the scm_imag_part to get proper error checking and
9809 dispatching. The result will almost always be 0.0, but not
9810 always.
9811 */
9812 return scm_to_double (scm_imag_part (z));
9813 }
9814 }
9815
9816 double
9817 scm_c_magnitude (SCM z)
9818 {
9819 return scm_to_double (scm_magnitude (z));
9820 }
9821
9822 double
9823 scm_c_angle (SCM z)
9824 {
9825 return scm_to_double (scm_angle (z));
9826 }
9827
9828 int
9829 scm_is_number (SCM z)
9830 {
9831 return scm_is_true (scm_number_p (z));
9832 }
9833
9834
9835 /* Returns log(x * 2^shift) */
9836 static SCM
9837 log_of_shifted_double (double x, long shift)
9838 {
9839 double ans = log (fabs (x)) + shift * M_LN2;
9840
9841 if (x > 0.0 || double_is_non_negative_zero (x))
9842 return scm_from_double (ans);
9843 else
9844 return scm_c_make_rectangular (ans, M_PI);
9845 }
9846
9847 /* Returns log(n), for exact integer n */
9848 static SCM
9849 log_of_exact_integer (SCM n)
9850 {
9851 if (SCM_I_INUMP (n))
9852 return log_of_shifted_double (SCM_I_INUM (n), 0);
9853 else if (SCM_BIGP (n))
9854 {
9855 long expon;
9856 double signif = scm_i_big2dbl_2exp (n, &expon);
9857 return log_of_shifted_double (signif, expon);
9858 }
9859 else
9860 scm_wrong_type_arg ("log_of_exact_integer", SCM_ARG1, n);
9861 }
9862
9863 /* Returns log(n/d), for exact non-zero integers n and d */
9864 static SCM
9865 log_of_fraction (SCM n, SCM d)
9866 {
9867 long n_size = scm_to_long (scm_integer_length (n));
9868 long d_size = scm_to_long (scm_integer_length (d));
9869
9870 if (abs (n_size - d_size) > 1)
9871 return (scm_difference (log_of_exact_integer (n),
9872 log_of_exact_integer (d)));
9873 else if (scm_is_false (scm_negative_p (n)))
9874 return scm_from_double
9875 (log1p (scm_i_divide2double (scm_difference (n, d), d)));
9876 else
9877 return scm_c_make_rectangular
9878 (log1p (scm_i_divide2double (scm_difference (scm_abs (n), d),
9879 d)),
9880 M_PI);
9881 }
9882
9883
9884 /* In the following functions we dispatch to the real-arg funcs like log()
9885 when we know the arg is real, instead of just handing everything to
9886 clog() for instance. This is in case clog() doesn't optimize for a
9887 real-only case, and because we have to test SCM_COMPLEXP anyway so may as
9888 well use it to go straight to the applicable C func. */
9889
9890 SCM_PRIMITIVE_GENERIC (scm_log, "log", 1, 0, 0,
9891 (SCM z),
9892 "Return the natural logarithm of @var{z}.")
9893 #define FUNC_NAME s_scm_log
9894 {
9895 if (SCM_COMPLEXP (z))
9896 {
9897 #if defined HAVE_COMPLEX_DOUBLE && defined HAVE_CLOG \
9898 && defined (SCM_COMPLEX_VALUE)
9899 return scm_from_complex_double (clog (SCM_COMPLEX_VALUE (z)));
9900 #else
9901 double re = SCM_COMPLEX_REAL (z);
9902 double im = SCM_COMPLEX_IMAG (z);
9903 return scm_c_make_rectangular (log (hypot (re, im)),
9904 atan2 (im, re));
9905 #endif
9906 }
9907 else if (SCM_REALP (z))
9908 return log_of_shifted_double (SCM_REAL_VALUE (z), 0);
9909 else if (SCM_I_INUMP (z))
9910 {
9911 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
9912 if (scm_is_eq (z, SCM_INUM0))
9913 scm_num_overflow (s_scm_log);
9914 #endif
9915 return log_of_shifted_double (SCM_I_INUM (z), 0);
9916 }
9917 else if (SCM_BIGP (z))
9918 return log_of_exact_integer (z);
9919 else if (SCM_FRACTIONP (z))
9920 return log_of_fraction (SCM_FRACTION_NUMERATOR (z),
9921 SCM_FRACTION_DENOMINATOR (z));
9922 else
9923 SCM_WTA_DISPATCH_1 (g_scm_log, z, 1, s_scm_log);
9924 }
9925 #undef FUNC_NAME
9926
9927
9928 SCM_PRIMITIVE_GENERIC (scm_log10, "log10", 1, 0, 0,
9929 (SCM z),
9930 "Return the base 10 logarithm of @var{z}.")
9931 #define FUNC_NAME s_scm_log10
9932 {
9933 if (SCM_COMPLEXP (z))
9934 {
9935 /* Mingw has clog() but not clog10(). (Maybe it'd be worth using
9936 clog() and a multiply by M_LOG10E, rather than the fallback
9937 log10+hypot+atan2.) */
9938 #if defined HAVE_COMPLEX_DOUBLE && defined HAVE_CLOG10 \
9939 && defined SCM_COMPLEX_VALUE
9940 return scm_from_complex_double (clog10 (SCM_COMPLEX_VALUE (z)));
9941 #else
9942 double re = SCM_COMPLEX_REAL (z);
9943 double im = SCM_COMPLEX_IMAG (z);
9944 return scm_c_make_rectangular (log10 (hypot (re, im)),
9945 M_LOG10E * atan2 (im, re));
9946 #endif
9947 }
9948 else if (SCM_REALP (z) || SCM_I_INUMP (z))
9949 {
9950 #ifndef ALLOW_DIVIDE_BY_EXACT_ZERO
9951 if (scm_is_eq (z, SCM_INUM0))
9952 scm_num_overflow (s_scm_log10);
9953 #endif
9954 {
9955 double re = scm_to_double (z);
9956 double l = log10 (fabs (re));
9957 if (re > 0.0 || double_is_non_negative_zero (re))
9958 return scm_from_double (l);
9959 else
9960 return scm_c_make_rectangular (l, M_LOG10E * M_PI);
9961 }
9962 }
9963 else if (SCM_BIGP (z))
9964 return scm_product (flo_log10e, log_of_exact_integer (z));
9965 else if (SCM_FRACTIONP (z))
9966 return scm_product (flo_log10e,
9967 log_of_fraction (SCM_FRACTION_NUMERATOR (z),
9968 SCM_FRACTION_DENOMINATOR (z)));
9969 else
9970 SCM_WTA_DISPATCH_1 (g_scm_log10, z, 1, s_scm_log10);
9971 }
9972 #undef FUNC_NAME
9973
9974
9975 SCM_PRIMITIVE_GENERIC (scm_exp, "exp", 1, 0, 0,
9976 (SCM z),
9977 "Return @math{e} to the power of @var{z}, where @math{e} is the\n"
9978 "base of natural logarithms (2.71828@dots{}).")
9979 #define FUNC_NAME s_scm_exp
9980 {
9981 if (SCM_COMPLEXP (z))
9982 {
9983 #if defined HAVE_COMPLEX_DOUBLE && defined HAVE_CEXP \
9984 && defined (SCM_COMPLEX_VALUE)
9985 return scm_from_complex_double (cexp (SCM_COMPLEX_VALUE (z)));
9986 #else
9987 return scm_c_make_polar (exp (SCM_COMPLEX_REAL (z)),
9988 SCM_COMPLEX_IMAG (z));
9989 #endif
9990 }
9991 else if (SCM_NUMBERP (z))
9992 {
9993 /* When z is a negative bignum the conversion to double overflows,
9994 giving -infinity, but that's ok, the exp is still 0.0. */
9995 return scm_from_double (exp (scm_to_double (z)));
9996 }
9997 else
9998 SCM_WTA_DISPATCH_1 (g_scm_exp, z, 1, s_scm_exp);
9999 }
10000 #undef FUNC_NAME
10001
10002
10003 SCM_DEFINE (scm_i_exact_integer_sqrt, "exact-integer-sqrt", 1, 0, 0,
10004 (SCM k),
10005 "Return two exact non-negative integers @var{s} and @var{r}\n"
10006 "such that @math{@var{k} = @var{s}^2 + @var{r}} and\n"
10007 "@math{@var{s}^2 <= @var{k} < (@var{s} + 1)^2}.\n"
10008 "An error is raised if @var{k} is not an exact non-negative integer.\n"
10009 "\n"
10010 "@lisp\n"
10011 "(exact-integer-sqrt 10) @result{} 3 and 1\n"
10012 "@end lisp")
10013 #define FUNC_NAME s_scm_i_exact_integer_sqrt
10014 {
10015 SCM s, r;
10016
10017 scm_exact_integer_sqrt (k, &s, &r);
10018 return scm_values (scm_list_2 (s, r));
10019 }
10020 #undef FUNC_NAME
10021
10022 void
10023 scm_exact_integer_sqrt (SCM k, SCM *sp, SCM *rp)
10024 {
10025 if (SCM_LIKELY (SCM_I_INUMP (k)))
10026 {
10027 mpz_t kk, ss, rr;
10028
10029 if (SCM_I_INUM (k) < 0)
10030 scm_wrong_type_arg_msg ("exact-integer-sqrt", SCM_ARG1, k,
10031 "exact non-negative integer");
10032 mpz_init_set_ui (kk, SCM_I_INUM (k));
10033 mpz_inits (ss, rr, NULL);
10034 mpz_sqrtrem (ss, rr, kk);
10035 *sp = SCM_I_MAKINUM (mpz_get_ui (ss));
10036 *rp = SCM_I_MAKINUM (mpz_get_ui (rr));
10037 mpz_clears (kk, ss, rr, NULL);
10038 }
10039 else if (SCM_LIKELY (SCM_BIGP (k)))
10040 {
10041 SCM s, r;
10042
10043 if (mpz_sgn (SCM_I_BIG_MPZ (k)) < 0)
10044 scm_wrong_type_arg_msg ("exact-integer-sqrt", SCM_ARG1, k,
10045 "exact non-negative integer");
10046 s = scm_i_mkbig ();
10047 r = scm_i_mkbig ();
10048 mpz_sqrtrem (SCM_I_BIG_MPZ (s), SCM_I_BIG_MPZ (r), SCM_I_BIG_MPZ (k));
10049 scm_remember_upto_here_1 (k);
10050 *sp = scm_i_normbig (s);
10051 *rp = scm_i_normbig (r);
10052 }
10053 else
10054 scm_wrong_type_arg_msg ("exact-integer-sqrt", SCM_ARG1, k,
10055 "exact non-negative integer");
10056 }
10057
10058 /* Return true iff K is a perfect square.
10059 K must be an exact integer. */
10060 static int
10061 exact_integer_is_perfect_square (SCM k)
10062 {
10063 int result;
10064
10065 if (SCM_LIKELY (SCM_I_INUMP (k)))
10066 {
10067 mpz_t kk;
10068
10069 mpz_init_set_si (kk, SCM_I_INUM (k));
10070 result = mpz_perfect_square_p (kk);
10071 mpz_clear (kk);
10072 }
10073 else
10074 {
10075 result = mpz_perfect_square_p (SCM_I_BIG_MPZ (k));
10076 scm_remember_upto_here_1 (k);
10077 }
10078 return result;
10079 }
10080
10081 /* Return the floor of the square root of K.
10082 K must be an exact integer. */
10083 static SCM
10084 exact_integer_floor_square_root (SCM k)
10085 {
10086 if (SCM_LIKELY (SCM_I_INUMP (k)))
10087 {
10088 mpz_t kk;
10089 scm_t_inum ss;
10090
10091 mpz_init_set_ui (kk, SCM_I_INUM (k));
10092 mpz_sqrt (kk, kk);
10093 ss = mpz_get_ui (kk);
10094 mpz_clear (kk);
10095 return SCM_I_MAKINUM (ss);
10096 }
10097 else
10098 {
10099 SCM s;
10100
10101 s = scm_i_mkbig ();
10102 mpz_sqrt (SCM_I_BIG_MPZ (s), SCM_I_BIG_MPZ (k));
10103 scm_remember_upto_here_1 (k);
10104 return scm_i_normbig (s);
10105 }
10106 }
10107
10108
10109 SCM_PRIMITIVE_GENERIC (scm_sqrt, "sqrt", 1, 0, 0,
10110 (SCM z),
10111 "Return the square root of @var{z}. Of the two possible roots\n"
10112 "(positive and negative), the one with positive real part\n"
10113 "is returned, or if that's zero then a positive imaginary part.\n"
10114 "Thus,\n"
10115 "\n"
10116 "@example\n"
10117 "(sqrt 9.0) @result{} 3.0\n"
10118 "(sqrt -9.0) @result{} 0.0+3.0i\n"
10119 "(sqrt 1.0+1.0i) @result{} 1.09868411346781+0.455089860562227i\n"
10120 "(sqrt -1.0-1.0i) @result{} 0.455089860562227-1.09868411346781i\n"
10121 "@end example")
10122 #define FUNC_NAME s_scm_sqrt
10123 {
10124 if (SCM_COMPLEXP (z))
10125 {
10126 #if defined HAVE_COMPLEX_DOUBLE && defined HAVE_USABLE_CSQRT \
10127 && defined SCM_COMPLEX_VALUE
10128 return scm_from_complex_double (csqrt (SCM_COMPLEX_VALUE (z)));
10129 #else
10130 double re = SCM_COMPLEX_REAL (z);
10131 double im = SCM_COMPLEX_IMAG (z);
10132 return scm_c_make_polar (sqrt (hypot (re, im)),
10133 0.5 * atan2 (im, re));
10134 #endif
10135 }
10136 else if (SCM_NUMBERP (z))
10137 {
10138 if (SCM_I_INUMP (z))
10139 {
10140 scm_t_inum x = SCM_I_INUM (z);
10141
10142 if (SCM_LIKELY (x >= 0))
10143 {
10144 if (SCM_LIKELY (SCM_I_FIXNUM_BIT < DBL_MANT_DIG
10145 || x < (1L << (DBL_MANT_DIG - 1))))
10146 {
10147 double root = sqrt (x);
10148
10149 /* If 0 <= x < 2^(DBL_MANT_DIG-1) and sqrt(x) is an
10150 integer, then the result is exact. */
10151 if (root == floor (root))
10152 return SCM_I_MAKINUM ((scm_t_inum) root);
10153 else
10154 return scm_from_double (root);
10155 }
10156 else
10157 {
10158 mpz_t xx;
10159 scm_t_inum root;
10160
10161 mpz_init_set_ui (xx, x);
10162 if (mpz_perfect_square_p (xx))
10163 {
10164 mpz_sqrt (xx, xx);
10165 root = mpz_get_ui (xx);
10166 mpz_clear (xx);
10167 return SCM_I_MAKINUM (root);
10168 }
10169 else
10170 mpz_clear (xx);
10171 }
10172 }
10173 }
10174 else if (SCM_BIGP (z))
10175 {
10176 if (mpz_perfect_square_p (SCM_I_BIG_MPZ (z)))
10177 {
10178 SCM root = scm_i_mkbig ();
10179
10180 mpz_sqrt (SCM_I_BIG_MPZ (root), SCM_I_BIG_MPZ (z));
10181 scm_remember_upto_here_1 (z);
10182 return scm_i_normbig (root);
10183 }
10184 else
10185 {
10186 long expon;
10187 double signif = scm_i_big2dbl_2exp (z, &expon);
10188
10189 if (expon & 1)
10190 {
10191 signif *= 2;
10192 expon--;
10193 }
10194 if (signif < 0)
10195 return scm_c_make_rectangular
10196 (0.0, ldexp (sqrt (-signif), expon / 2));
10197 else
10198 return scm_from_double (ldexp (sqrt (signif), expon / 2));
10199 }
10200 }
10201 else if (SCM_FRACTIONP (z))
10202 {
10203 SCM n = SCM_FRACTION_NUMERATOR (z);
10204 SCM d = SCM_FRACTION_DENOMINATOR (z);
10205
10206 if (exact_integer_is_perfect_square (n)
10207 && exact_integer_is_perfect_square (d))
10208 return scm_i_make_ratio_already_reduced
10209 (exact_integer_floor_square_root (n),
10210 exact_integer_floor_square_root (d));
10211 else
10212 {
10213 double xx = scm_i_divide2double (n, d);
10214 double abs_xx = fabs (xx);
10215 long shift = 0;
10216
10217 if (SCM_UNLIKELY (abs_xx > DBL_MAX || abs_xx < DBL_MIN))
10218 {
10219 shift = (scm_to_long (scm_integer_length (n))
10220 - scm_to_long (scm_integer_length (d))) / 2;
10221 if (shift > 0)
10222 d = left_shift_exact_integer (d, 2 * shift);
10223 else
10224 n = left_shift_exact_integer (n, -2 * shift);
10225 xx = scm_i_divide2double (n, d);
10226 }
10227
10228 if (xx < 0)
10229 return scm_c_make_rectangular (0.0, ldexp (sqrt (-xx), shift));
10230 else
10231 return scm_from_double (ldexp (sqrt (xx), shift));
10232 }
10233 }
10234
10235 /* Fallback method, when the cases above do not apply. */
10236 {
10237 double xx = scm_to_double (z);
10238 if (xx < 0)
10239 return scm_c_make_rectangular (0.0, sqrt (-xx));
10240 else
10241 return scm_from_double (sqrt (xx));
10242 }
10243 }
10244 else
10245 SCM_WTA_DISPATCH_1 (g_scm_sqrt, z, 1, s_scm_sqrt);
10246 }
10247 #undef FUNC_NAME
10248
10249
10250
10251 void
10252 scm_init_numbers ()
10253 {
10254 if (scm_install_gmp_memory_functions)
10255 mp_set_memory_functions (custom_gmp_malloc,
10256 custom_gmp_realloc,
10257 custom_gmp_free);
10258
10259 mpz_init_set_si (z_negative_one, -1);
10260
10261 /* It may be possible to tune the performance of some algorithms by using
10262 * the following constants to avoid the creation of bignums. Please, before
10263 * using these values, remember the two rules of program optimization:
10264 * 1st Rule: Don't do it. 2nd Rule (experts only): Don't do it yet. */
10265 scm_c_define ("most-positive-fixnum",
10266 SCM_I_MAKINUM (SCM_MOST_POSITIVE_FIXNUM));
10267 scm_c_define ("most-negative-fixnum",
10268 SCM_I_MAKINUM (SCM_MOST_NEGATIVE_FIXNUM));
10269
10270 scm_add_feature ("complex");
10271 scm_add_feature ("inexact");
10272 flo0 = scm_from_double (0.0);
10273 flo_log10e = scm_from_double (M_LOG10E);
10274
10275 exactly_one_half = scm_divide (SCM_INUM1, SCM_I_MAKINUM (2));
10276
10277 {
10278 /* Set scm_i_divide2double_lo2b to (2 b^p - 1) */
10279 mpz_init_set_ui (scm_i_divide2double_lo2b, 1);
10280 mpz_mul_2exp (scm_i_divide2double_lo2b,
10281 scm_i_divide2double_lo2b,
10282 DBL_MANT_DIG + 1); /* 2 b^p */
10283 mpz_sub_ui (scm_i_divide2double_lo2b, scm_i_divide2double_lo2b, 1);
10284 }
10285
10286 {
10287 /* Set dbl_minimum_normal_mantissa to b^{p-1} */
10288 mpz_init_set_ui (dbl_minimum_normal_mantissa, 1);
10289 mpz_mul_2exp (dbl_minimum_normal_mantissa,
10290 dbl_minimum_normal_mantissa,
10291 DBL_MANT_DIG - 1);
10292 }
10293
10294 #include "libguile/numbers.x"
10295 }
10296
10297 /*
10298 Local Variables:
10299 c-file-style: "gnu"
10300 End:
10301 */