## Outdated egg!

This is an egg for CHICKEN 4, the unsupported old release. You're almost certainly looking for the CHICKEN 5 version of this egg, if it exists.

If it does not exist, there may be equivalent functionality provided by another egg; have a look at the egg index. Otherwise, please consider porting this egg to the current version of CHICKEN.

## TOC »

## Numbers

This egg provides support for the full numeric tower. It adds support for:

- Integers larger than
`most-positive-fixnum`and smaller than`most-negative-fixnum`through bignums, instead of the default behaviour of falling back to inexact flonums. - Rational numbers (fractions), instead of falling back to inexact flonums.
- Complex numbers.

All of these are supported by exporting different versions of the standard numerical procedures. Be sure to import the `numbers` module after the `scheme` module, or to hide the standard numerical procedures from `scheme`. These number types are also supported as read-time literals, but only after loading the extension and only in the interpreter (but see below for limited compile-time support).

This egg also adds a handful of extra procedures. See below.

## Interface

This extension provides support for large exact integers, exact rational and complex numbers.

The following standard procedures are redefined:

+ - * / = > < >= <= abs max min eqv? equal? exp expt log sin cos tan atan asin acos sqrt quotient modulo remainder exact? inexact? exact->inexact inexact->exact positive? negative? even? odd? zero? number? complex? real? rational? integer? gcd lcm truncate ceiling floor round number->string string->number numerator denominator rationalize magnitude angle real-part imag-part

The `log` procedure is extended to allow a second argument specifying the logarithm base, as per R7RS.

The following standard procedures are provided:

make-rectangular make-polar

The following non-standard extended procedures are redefined:

add1 sub1 signum bitwise-and bitwise-ior bitwise-xor bitwise-not arithmetic-shift randomize random finite? bit-set?

Additionally the following procedures are available:

`infinite?``Z`procedureIs the number

`Z``+inf.0`or`-inf.0`, or a complex number containing either infinity as its real or imaginary part?From R6RS and R7RS.

**Note**: This is**not**the inverse of`finite?`, since it produces`#f`on`nan.0`(or complex numbers containing`nan.0`), while`finite?`also returns`#f`in that case.

`nan?``Z`procedureIs the object

`Z`a real representing`nan.0`?From R6RS and R7RS.

`exact``Z`procedure`inexact``Z`procedureConvert

`Z`to an exact or an inexact number, respectively. These are just the R6RS and R7RS names for`inexact->exact`and`exact->inexact`.

`exact-integer-sqrt``K`procedureReturns two values

`s`and`r`, where`s^2 + r = K`and`K < (s+1)^2`. In other words,`s`is the closest square root we can find that's equal to or smaller than`K`, and`r`is the rest if`K`isn't a neat square of two numbers.This procedure is compatible with the R7RS specification.

`exact-integer-nth-root``K``N`procedureLike

`exact-integer-sqrt`, but with any base value. Calculates`\sqrt[N]{K`}, the`N`th root of`K`and returns two values`s`and`r`where`s^N + r = K`and`K < (s+1)^N`.

`exact-integer?``X`procedureIs

`X`an exact integer?

`quotient&remainder``A``B`procedureReturn the quotient

*and*the remainder of A divided by B.This is especially useful for bignums, since both numbers are derived simultaneously. This saves performing the division algorithm twice.

This name is deprecated in favor of its more "regular" alias from R7RS,

`truncate/`.

`quotient&modulo``A``B`procedureLike

`quotient&remainder`, except return the modulo instead of remainder.This procedure has been deprecated.

`floor/``A``B`procedure`floor-quotient``A``B`procedure`floor-remainder``A``B`procedure`truncate/``A``B`procedure`truncate-quotient``A``B`procedure`truncate-remainder``A``B`procedureThese procedures are from R7RS.

The

`floor/`and`truncate/`versions return two values: the quotient and remainder obtained after dividing`A`by`B`. The`-quotient`and`-remainder procedures`simply return only the corresponding value of the "full" computation.The difference is in how the values are derived for negative values.

If both values are desired, the two-value versions are recommended, as they perform the computation only once.

All the procedures compute a quotient

`q`and remainder`r`such that`A = nq + r`. The remainder is determined by the choice for`q`, through the relation`r = A - nq`. The`floor`procedures compute`q = floor(A/B)`and the`truncate`procedures compute`q = truncate(A/B)`.See Riastradh's proposal for Division operators in Scheme for a full explanation of the intricacies of these procedures.

`conj``Z`procedureReturns the conjugate of the complex number Z.

`bignum?``X`procedureIs X an extended-precision integer?

`ratnum?``X`procedureIs X a ratio?

`cplxnum?``X`procedureIs X a complex?

`rectnum?``X`procedureIs X an exact-complex? (Treats an integer-floatingpoint as "exact".)

`compnum?``X`procedureIs X an inexact-complex?

`cflonum?``X`procedureIs X a floatingpoint-complex or a floatingpoint?

`cintnum?``X`procedureIs X an integer-complex or an integer?

`integer-length``X`procedureFrom SRFI-60; get the number of bits required to represent the integer

`X`in 2s complement notation.

## Example

(define (fac n) (if (zero? n) 1 (* n (fac (- n 1))) ) ) (fac 100) ; => 9332621544394415268169923885626670049071596826438162146859296389 5217599993229915608941463976156518286253697920827223758251185210 916864000000000000000000000000

## Compiled code

Starting with version 2.8, extended number literals can be used in compiled code. To make this work, compile your code with:

csc -X numbers-syntax foo.scm

**IMPORTANT**: Extended number literals only work when the code will be run on exactly the same platform as the Scheme compiler ran on. Cross-compilation and compiling to C and compiling that on the target platform is *not supported*. (You will get an error message when you try to do it anyway)

## Bugs and limitations

- Extended number literals can not be used portably in compiled code (use
`string->number`for maximum portability). - For best results, use Chicken 4.7.4 or later. Extended numbers syntax isn't reliably supported by the reader of earlier Chicken versions (here as well, use
`string->number`for maximum portability).

## About this egg

### Author

The code for complex arithmetic was mostly taken from Thomas Chust's complex egg for CHICKEN 3.

### Maintainer

The CHICKEN Team

### Version history

- 4.6.3
- Fix a bug introduced in 4.6.2 related to printing negative floating-point numbers.
- 4.6.2
- Fix an edge case in printing floating-point numbers resulting in
`0.0`for numbers that will be normalized to`2^64`. - 4.6.1
- Fix a few warnings during compilation due to invalid
`exclude`directives in module definition (thanks to Evan Hanson). - 4.6
- Proper fix for Burnikel-Ziegler performance problem from release 4.3, thereby fixing another pathological case.
- 4.5
- Fix "overlap" handling in number->string for power of two radices which have a bit length that's not a multiple of the word size.
- 4.4
- Add support for "argvector" CHICKEN, while maintaining support for pre-argvector versions.
- 4.3
- Fix pathological performance problem in Burnikel-Ziegler division routines triggered by "pidigits" benchmark from the Great Languages Shootout Game (thanks to "Balkenbrij" on Reddit). Fix a double
`C_fix()`call in`bitwise-and`that would sometimes cause invalid result values due to 1 limb of uninitialized memory. Fix a similar bug in comparisons of ratnums with other numbers. Fix error reporting when passed non-numeric objects to elementary arithmetic operators. Make bignum to floating-point more stable across platforms by disabling extended precision FP registers (on Linux/i386). - 4.2
- Fix an error in Burnikel-Ziegler division that caused wrong results in some edge cases. Fix compilation error in pre-4.8.0 CHICKENs due to use of missing C macro.
- 4.1
- Fix a few errors in specialization rules and a strange use of "eval" in the unit tests.
- 4.0
- Convert internal digit representation to use full words. Improve performance by accessing halfdigits directly. Improve performance of number<->string conversions for radixes that are a power of two by directly operating on digits, avoiding in-place shifts. Improve performance of number->string by using a divide and conquer algorithm. Implement Burnikel&Ziegler recursive division which is O(r*s^{log(3)-1} + r*log(s)) instead of O(n^2) (this is mostly useful for very large numbers due to high constant overhead). Make comparisons inlineable and implement vararg comparison procedures in C to avoid consing up a rest list. Implement Karatsuba square root, which is more efficient than Newton's algorithm. Implement
`bit-set?`. Rewrite the last remaining s48 code (very little was left) to ensure clean license/copyright. - 3.1
- Improve performance of string<->number conversions by chunking bignum digits off instead of using a binary digit at a time. Use a faster and shorter division algorithm from Hacker's Delight. Implement Lehmer's hybrid Euclidian GCD algorithm which is O(n^2/log n) instead of O(n^2) like Euclid and Stein's algorithms. Implement Karatsuba multiplication which is O(n^log2(3)) instead of O(n^2), but is only effective for larger bignums. Make a few more things inlineable. Fix stupid mistake which caused exact operations involving rational numbers to be needlessly slow. Improve performance for string<->number conversion using radix powers of two, and for multiplication of bignums with small powers of two.
- 3.0.1
- Fix quotient&remainder and derived procedures for 2 bignum arguments (it returned only the remainder). Fix crash bug in flonum comparison.
- 3.0
- Improve performance of
`exact-integer-sqrt`and`exact-integer-nth-root`by using a better initial guess. Improve read/write performance. Major refactoring to make things a lot more consistent with the core system. Added some more specializations. Change`integer-length`,`bitwise-and`,`bitwise-ior`,`bitwise-ior`,`bitwise-not`,`arithmetic-shift`and`integer-length`to only allow exact integers. Handling of rationals should be better, as well as a few other division procedures. - 2.10.1
- Fix a few inexact number tests to use nonzero epsilons.
- 2.10
- Fix error reporting of
`>=`,`<=`,`nan?`,`finite?`and`infinite?`[thanks to Felix Winkelmann]. Fix types DB entry for`inexact->exact`(found by adding insanely paranoid checks to CHICKEN itself) - 2.9
- Fix a few compiler warnings. R7RS support: Add support for a 2nd "base" argument to the
`log`procedure, export`exact`and`inexact`aliases for`exact->inexact`and`inexact->exact`. Add`floor/`,`floor-quotient`,`floor-remainder`,`truncate/`,`truncate-quotient`and`truncate-remainder`. - 2.8.2
- Add CL-compatible support for complex numbers to
`signum`(#953), and support`numerator`and`denominator`on flonums (as per RnRS) (#1016) [Thanks to John Cowan] - 2.8.1
- Remove long-deprecated and undocumented
`numbers:`-prefixed variants of`+`,`-`, etc. Fix compilation on 4.8.1, which failed due to invalid +inf/-inf literals. Remove`(declare (disable-interrupts))`, which should make numbers play better with threaded code. - 2.8
- Correct handling of exactness prefix (requires recent Chicken to work, at least 4.7.4). Division by inexact zero is no longer considered an error, but returns NaN or +Inf/-Inf.
`inexact->exact`raises an error on NaN instead of returning 0 (reported by Felix Winkelmann). Fix`log`so it doesn't erroneously fail on complex numbers. Generalize`asin`and`acos`so they can return complex numbers. Fix`<=`and`>=`so they work when given a`nan`argument in rest position. Various fixes for code that expected inexact numbers so it calls`exact->inexact`before. Add types database for scrutinizer (Only in Chicken 4.7.4 and later). - 2.7
- Fix several bugs (
`expt`,`integer?`,`rational?`,`<=`,`>=`,`eqv?`,`-`) found by importing the number tests from Gauche and writing an extensive test for number syntax edge cases. Complete rewrite of number parser (it should fully conform to the R7RS superset of R5RS number syntax now). Dropped dependency on the regex egg. Improved precision of`exact->inexact`so it can handle more extreme numbers. Provide the`nan?`,`finite?`and`infinite?`predicates and`integer-length`procedure. - 2.6.1
- Fix
`string->number`so it raises an exception instead of crashing when passed a negative, zero or too large base (reported by Peter Hendrickson). Update test scripts so they exit with nonzero status in case of failed tests (reported by Mario Goulart) - 2.6
- Fix expt and log so they work for numbers which produce complex results.
- 2.5
- Fix expt so it doesn't use flonums and loses precision in case of bignums
- 2.4
- Added regex to dependency list
- 2.3
- Added regex requirement to make it work in Chicken 4.6.2+
- 2.2
- Fixed ratnum normalization in case of negative divisors
- 2.1
- Changed
`quotient`,`remainder`and`quotient&remainder`semantics so they accept fractional flonums to match Chicken's implementation of`quotient`and`remainder`. This also affects`modulo`and`quotient&modulo`. - 2.0
- Removed dependency on GMP, replacing it by the Scheme48 numbers code. Improved performance by integrating with GC. Added benchmarks and more tests. Converted testsuite to use the test egg instead of testeez. [by Peter Bex]
- 1.82
- removed dependency on easyffi (Thanks to Peter Bex)
- 1.81
- fixed dependencies
- 1.809
- Fix for
`(expt <number> <ratio>)`, would fail [Bug noted by John Cowan] - 1.808
- Fix for 1.0+1i not treated as a rectnum or compnum [Bug noted by John Cowan] Added 'cintnum?' & 'cplxnum?' [kon lovett]
- 1.806
- Fix for equal? when given keywords as args [Bug noted by papasi] [elf]
- 1.804
- Using more accurate exact->inexact conversion for rationals [Alex Shinn]
- 1.803
- fixed bug in fixnum bitwise operations [Thanks to Jeremy Sydik]
- 1.802
- not quite complete support for static linking
- 1.801
- Fixed a bug in
`angle`[zb, mario] - 1.8
- Single-argument
`+`and`*`didn't check argument type [Thanks to Stephen Gilardi] - 1.701
- Bugfix for compiler macros, undefined symbol [Kon Lovett]
- 1.7
- Added compiler macros for
`bitwise-...`operations - 1.6
- Compiler macros now work without -X numbers
- 1.5
- Added support for speculative inlining of fixnum ops
- 1.4
- Fixed bug in ratnum/bignum division [Thanks to Ivan Shmakov]
- 1.3
- Fixing round for rational numbers [Alex Shinn]
- 1.2
- Added
`bignum? ratnum? cflonum? rectnum? compnum?`[Kon Lovett] - 1.1
- Uses easyffi properly [reported by John Cowan]
- 1.0
- Fix for fixnum/rational comparison [by Zbigniew]
- 0.999
`rational?`always returned false for flonums- 0.998
- Added some missing definitions to numbers.scm [found by Kon Lovett]
- 0.997
- Fixed memory leak in some bitwise operations [found by Dan Muresan]
- 0.996
- Fixed a bug in
`expt`[Daishi Kato] - 0.995
`round`rounds to even (as specified by R5RS) [Thanks to Benedikt Rosenau]- 0.994
- Reimplemented
`=`in C - 0.993
- Fixed
`equal?`which didn't handle extended numbers nested in other data - 0.992
- Slight performance tuning for
`expt`[Again by Daishi] - 0.991
- Fixed bug in fixnum/bignum subtraction [Thanks to Daishi Kato and Alex Shinn]
- 0.99
- Speed improvements for
`expt`by Daishi Kato - 0.98
- Added
`random`and`randomize`[Suggested by Daishi Kato] - 0.97
- bignum/fixnum subtraction used wrong argument order [Thanks to Kon Lovett]
- 0.96
- Several bug fixes by Alex Shinn;
`signum`is exactness preserving - 0.95
- Alex Shinn contributed a working version of
`expt` - 0.94
- Yet another bug-fix by Michal
- 0.93
- Several bug-fixes by Michal Janeczek
- 0.92
- exactness handling of
`expt`is slightly better but still not perfect. - 0.91
- Fixed bug in
`integer?` - 0.9
- (beta)

### License

Copyright (c) 2008-2017 The CHICKEN Team Copyright (c) 2000-2007, Felix L. Winkelmann All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.