This library is free; this means that everyone is free to use it and free to redistribute it on a free basis. The library is not in the public domain; it is copyrighted and there are restrictions on its distribution, but these restrictions are designed to permit everything that a good cooperating citizen would want to do. What is not allowed is to try to prevent others from further sharing any version of this library that they might get from you.
Specifically, we want to make sure that you have the right to give away copies of the library, that you receive source code or else can get it if you want it, that you can change this library or use pieces of it in new free programs, and that you know you can do these things.
To make sure that everyone has such rights, we have to forbid you to deprive anyone else of these rights. For example, if you distribute copies of the GNU MP library, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights.
Also, for our own protection, we must make certain that everyone finds out that there is no warranty for the GNU MP library. If it is modified by someone else and passed on, we want their recipients to know that what they have is not what we distributed, so that any problems introduced by others will not reflect on our reputation.
The precise conditions of the license for the GNU MP library are found in the Lesser General Public License that accompany the source code.
GNU MP is a portable library written in C for arbitrary precision arithmetic on integers, rational numbers, and floating-point numbers. It aims to provide the fastest possible arithmetic for all applications that need higher precision than is directly supported by the basic C types.
Many applications use just a few hundred bits of precision; but some applications may need thousands or even millions of bits. GMP is designed to give good performance for both, by choosing algorithms based on the sizes of the operands, and by carefully keeping the overhead at a minimum.
The speed of GMP is achieved by using fullwords as the basic arithmetic type, by using sophisticated algorithms, by including carefully optimized assembly code for the most common inner loops for many different CPUs, and by a general emphasis on speed (as opposed to simplicity or elegance).
There is carefully optimized assembly code for these CPUs: ARM, DEC Alpha 21064, 21164, and 21264, AMD 29000, AMD K6 and Athlon, Hitachi SuperH and SH-2, HPPA 1.0, 1.1 and 2.0, Intel Pentium, Pentium Pro/Pentium II, generic x86, Intel i960, Motorola MC68000, MC68020, MC88100, and MC88110, Motorola/IBM PowerPC 32 and 64, National NS32000, IBM POWER, MIPS R3000, R4000, SPARCv7, SuperSPARC, generic SPARCv8, UltraSPARC, DEC VAX, and Zilog Z8000. Some optimizations also for Clipper, IBM ROMP (RT), and Pyramid AP/XP.
There is a mailing list for GMP users. To join it, send a mail to gmp-request@swox.com with the word `subscribe' in the message body (not in the subject line).
For up-to-date information on GMP, please see the GMP Home Pages at http://www.swox.com/gmp/.
Everyone should read section GMP Basics. If you need to install the library yourself, you need to read section Installing GMP, too.
The rest of the manual can be used for later reference, although it is probably a good idea to glance through it.
GMP has an autoconf/automake/libtool based configuration system. On a Unix-like system a basic build can be done with
./configure make
Some self-tests can be run with
make check
And you can install (under `/usr/local' by default) with
make install
If you experience problems, please report them to bug-gmp@gnu.org. (See section Reporting Bugs, for information on what to include in useful bug reports.)
All the usual autoconf configure options are available, run `./configure --help' for a summary.
cd to that directory, and
prefix the configure command with the path to the GMP source directory. For
example `../src/gmp/configure'. Not all `make' programs have the
necessary features (VPATH) to support this. In particular, SunOS and
Slowaris make have bugs that make them unable to build from a
separate object directory. Use GNU make instead.
alloca if that
function is available, or malloc if not. If you're working with large
numbers and alloca overflows the available stack space, you can build
with @option{--disable-alloca} to use malloc instead. malloc
will probably be slightly slower than alloca.
When not using alloca, it's actually the allocation function
selected with mp_set_memory_functions that's used, this being
malloc by default. See section Custom Allocation.
Depending on your system, the only indication of stack overflow might be a
segmentation violation. It might be possible to increase available stack
space with limit, ulimit or setrlimit, or under
DJGPP with stubedit or _stklen.
ABI (Application Binary Interface) refers to the calling conventions between functions, meaning what registers are used and what sizes the various C data types are. ISA (Instruction Set Architecture) refers to the instructions and registers a CPU has available.
Some 64-bit ISA CPUs have both a 64-bit ABI and a 32-bit ABI defined, the latter for compatibility with older CPUs in the family. GMP chooses the best ABI available for a given target system, and this generally gives significantly greater speed.
The burden is on application programs and cooperating libraries to ensure they match the ABI chosen by GMP. Fortunately this presents a difficulty only on a few systems, and if you have one of them then the performance gains are enough to make it worth the trouble.
Some of what's described in this section may change in future releases of GMP.
c89. No
gcc support is planned for 64-bit operations in this ABI.
Applications must be compiled with the same options as GMP, which means
c89 +DA2.0 +e -D_LONG_LONG_LIMBA 32-bit limb is used in other cases, and no special compiler options are needed. CPU target `hppa2.0w' uses the hppa2.0w 64-bit ABI, which is available on HP-UX 11 or up when using
c89. gcc support for this is in
progress. Applications must be compiled for the same ABI, which means
c89 +DD64
gcc -mabi=n32 cc -n32
gcc -maix64 xlc -q64On other systems the 32-bit ABI is used, but with 64-bit limbs provided by
long long in gcc. Applications must be compiled using
gcc -D_LONG_LONG_LIMB
gcc -mv8plus cc -xarch=v8plusFor the v9 ABI, applications must be compiled with either
gcc -m64 -mptr64 -Wa,-xarch=v9 -mcpu=v9 cc -xarch=v9Don't be confused by the names of these options, they're called `arch' but they effectively control the ABI.
GMP should present no great difficulties for packaging in a binary distribution.
Libtool is used to build the library and `-version-info' is set appropriately, having started from `3:0:0' in GMP 3.0. The GMP 3 series will be upwardly binary compatible in each release, but may be adding additional function interfaces. On systems where libtool versioning is not fully checked by the loader, an auxiliary mechanism may be needed to express that a dynamic linked application depends on a new enough minor version of GMP.
When building a package for a CPU family, care should be taken to use `--target' to choose the least common denominator among the CPUs which might use the package. For example this might necessitate `i386' for x86s, or plain `sparc' (meaning V7) for SPARCs.
Users who care about speed will want GMP built for their exact CPU type, to make use of the available optimizations. Providing a way to suitably rebuild a package may be useful. This could be as simple as making it possible for a user to omit `--target' in a build so `./config.guess' will detect the CPU. But a way to manually specify a `--target' will be wanted for systems where `./config.guess' is inexact.
m4 in this release of OpenBSD has a bug in eval that makes it
unsuitable for `.asm' file processing. `./configure' will detect
the problem and either abort or choose another m4 in the @env{PATH}. The bug
is fixed in OpenBSD 2.7, so either upgrade or use GNU m4.
/usr/bin/m4 lacks various features needed to process `.asm'
files, and instead `./configure' will automatically use
/usr/5bin/m4, which we believe is always available (if not then use
GNU m4).
You might find more up-to-date information at http://www.swox.com/gmp/.
unsigned long is 64 bits), BITS_PER_MP_LIMB,
BITS_PER_LONGINT and BYTES_PER_MP_LIMB in
`mpn/generic/gmp-mparam.h' need to be changed to 64 and 8. This will
hopefully be automated in a future version of GMP.
GSYM_PREFIX in `config.m4' may be incorrectly
determined when using the native grep, leading at link-time to
undefined symbols like ___gmpn_add_n. To fix this, after running
`./configure', change the relevant line in `config.m4' to
`define(<GSYM_PREFIX>, <_>)'.
The ranlib command will need to be run manually when building a
static library with the native ar. After `make', run
`ranlib .libs/libgmp.a', and when using @option{--enable-mpbsd} run
`ranlib .libs/libmp.a' too.
jsobgtr) that cannot be assembled by
the Ultrix assembler.
All declarations needed to use GMP are collected in the include file `gmp.h'. It is designed to work with both C and C++ compilers.
Using functions, macros, data types, etc. not documented in this manual is strongly discouraged. If you do so your application is guaranteed to be incompatible with future versions of GMP.
In this manual, integer usually means a multiple precision integer, as
defined by the GMP library. The C data type for such integers is mpz_t.
Here are some examples of how to declare such integers:
mpz_t sum;
struct foo { mpz_t x, y; };
mpz_t vec[20];
Rational number means a multiple precision fraction. The C data type
for these fractions is mpq_t. For example:
mpq_t quotient;
Floating point number or Float for short, is an arbitrary precision
mantissa with a limited precision exponent. The C data type for such objects
is mpf_t.
A limb means the part of a multi-precision number that fits in a single
word. (We chose this word because a limb of the human body is analogous to a
digit, only larger, and containing several digits.) Normally a limb contains
32 or 64 bits. The C data type for a limb is mp_limb_t.
There are six classes of functions in the GMP library:
mpz_. The associated type is mpz_t. There are about 100
functions in this class.
mpq_. The associated type is mpq_t. There are about 20
functions in this class, but the functions in the previous class can be used
for performing arithmetic on the numerator and denominator separately.
mpf_. The associated type is mpf_t. There are about 50
functions is this class.
itom, madd, and
mult. The associated type is MINT.
mpn_. There are about 30 (hard-to-use) functions in this class.
The associated type is array of mp_limb_t.
As a general rule, all GMP functions expect output arguments before input arguments. This notation is based on an analogy with the assignment operator. (The BSD MP compatibility functions disobey this rule, having the output argument(s) last.)
GMP lets you use the same variable for both input and output in one call. For
example, the main function for integer multiplication, mpz_mul, can be
used to square x and put the result back in x with
mpz_mul (x, x, x);
Before you can assign to a GMP variable, you need to initialize it by calling one of the special initialization functions. When you're done with a variable, you need to clear it out, using one of the functions for that purpose. Which function to use depends on the type of variable. See the chapters on integer functions, rational number functions, and floating-point functions for details.
A variable should only be initialized once, or at least cleared out between each initialization. After a variable has been initialized, it may be assigned to any number of times.
For efficiency reasons, avoid initializing and clearing out a GMP variable in a loop. Instead, initialize it before entering the loop, and clear it out after the loop has exited.
GMP variables are small, containing only a couple of sizes, and pointers to allocated data. Once you have initialized a GMP variable, you don't need to worry about space allocation. All functions in GMP automatically allocate additional space when a variable does not already have enough. They do not, however, reduce the space when a smaller value is stored. Most of the time this policy is best, since it avoids frequent re-allocation.
When a variable of type mpz_t is used as a function parameter, it's
effectively a call-by-reference, meaning anything the function does to it will
be be done to the original in the caller. When a function is going to return
an mpz_t result, it should provide a separate parameter or parameters
that it sets, like the GMP library functions do. A return of an
mpz_t doesn't return the object, only a pointer to it, and this is
almost certainly not what you want. All this applies to mpq_t and
mpf_t too.
Here's an example function accepting an mpz_t parameter, doing a
certain calculation, and returning a result.
void
myfunction (mpz_t result, mpz_t param, unsigned long n)
{
unsigned long i;
mpz_mul_ui (result, param, n);
for (i = 1; i < n; i++)
mpz_add_ui (result, result, i*7);
}
int
main (void)
{
mpz_t r, n;
mpz_init (r);
mpz_init_set_str (n, "123456", 0);
myfunction (r, n, 20L);
mpz_out_str (stdout, 10, r); printf ("\n");
return 0;
}
This example will work if result and param are the same
variable, just like the library functions. But sometimes this is tricky to
arrange, and an application might not want to bother for its own subroutines.
mpz_t is actually implemented as a one-element array of a certain
structure type. This is why using it to declare a variable gives an object
with the fields GMP needs, but then using it as a parameter passes a pointer
to the object. Note that the actual contents of an mpz_t are for
internal use only and you should not access them directly if you want your
code to be compatible with future GMP releases.
The GMP code is reentrant and thread-safe, with some exceptions:
mpf_set_default_prec saves the selected precision in
a global variable.
mp_set_memory_functions uses several global
variables for storing the selected memory allocation functions.
mp_set_memory_functions (or malloc and friends by default) are
not reentrant, GMP will not be reentrant either.
mpz_random, etc) use a random number
generator from the C library, usually mrand48 or random. These
routines are not reentrant, since they rely on global state.
(However the newer random number functions that accept a
gmp_randstate_t parameter are reentrant.)
alloca is not available, or GMP is configured with
`--disable-alloca', the library is not reentrant, due to the current
implementation of `stack-alloc.c'. In the generated `config.h',
USE_STACK_ALLOC set to 1 will mean not reentrant.
This version of GMP is upwardly binary compatible with versions 3.0 and 3.0.1, and upwardly compatible at the source level with versions 2.0, 2.0.1, and 2.0.2, with the following exceptions.
mpn_gcd had its source arguments swapped as of GMP 3.0 for consistency
with other mpn functions.
mpf_get_prec counted precision slightly differently in GMP 3.0 and
3.0.1, but in 3.1 has reverted to the 2.0.x style.
There are a number of compatibility issues between GMP 1 and GMP 2 that of course also apply when porting applications from GMP 1 to GMP 3. Please see the GMP 2 manual for details.
The latest version of the GMP library is available at ftp://ftp.gnu.org/pub/gnu/gmp. Many sites around the world mirror `ftp.gnu.org'; please use a mirror site near you, see http://www.gnu.org/order/ftp.html.
If you think you have found a bug in the GMP library, please investigate it and report it. We have made this library available to you, and it is not too much to ask you to report the bugs you find. Before you report a bug, you may want to check http://www.swox.com/gmp/ for patches for this release.
Please include the following in any report,
gdb, or `$C' in adb).
straces.
gcc, get the version
with `gcc -v', otherwise perhaps `what `which cc`', or similar.
It is not uncommon that an observed problem is actually due to a bug in the compiler; the GMP code tends to explore interesting corners in compilers.
If your bug report is good, we will do our best to help you get a corrected version of the library; if the bug report is poor, we won't do anything about it (except maybe ask you to send a better report).
Send your report to: bug-gmp@gnu.org.
If you think something in this manual is unclear, or downright incorrect, or if the language needs to be improved, please send a note to the same address.
This chapter describes the GMP functions for performing integer arithmetic.
These functions start with the prefix mpz_.
GMP integers are stored in objects of type mpz_t.
The functions for integer arithmetic assume that all integer objects are
initialized. You do that by calling the function mpz_init.
mpz_clear) between each initialization.
Here is an example of using mpz_init:
{
mpz_t integ;
mpz_init (integ);
...
mpz_add (integ, ...);
...
mpz_sub (integ, ...);
/* Unless the program is about to exit, do ... */
mpz_clear (integ);
}
As you can see, you can store new values any number of times, once an object is initialized.
mpz_t variables when you are done with them.
This function is useful for decreasing the working set for some algorithms that use large integer arrays.
There is no way to de-allocate the storage allocated by this function.
Don't call mpz_clear!
These functions assign new values to already initialized integers (see section Initialization Functions).
This function returns 0 if the entire string up to the '\0' is a valid number in base base. Otherwise it returns -1.
[It turns out that it is not entirely true that this function ignores white-space. It does ignore it between digits, but not after a minus sign or within or after "0x". We are considering changing the definition of this function, making it fail when there is any white-space in the input, since that makes a lot of sense. Please tell us your opinion about this change. Do you really want it to accept "3 14" as meaning 314 as it does now?]
For convenience, GMP provides a parallel series of initialize-and-set functions
which initialize the output and then store the value there. These functions'
names have the form mpz_init_set...
Here is an example of using one:
{
mpz_t pie;
mpz_init_set_str (pie, "3141592653589793238462643383279502884", 10);
...
mpz_sub (pie, ...);
...
mpz_clear (pie);
}
Once the integer has been initialized by any of the mpz_init_set...
functions, it can be used as the source or destination operand for the ordinary
integer functions. Don't use an initialize-and-set function on a variable
already initialized!
mpz_set_str (see its
documentation above for details).
If the string is a correct base base number, the function returns 0;
if an error occurs it returns -1. rop is initialized even if
an error occurs. (I.e., you have to call mpz_clear for it.)
This section describes functions for converting GMP integers to standard C types. Functions for converting to GMP integers are described in section Assignment Functions and section Input and Output Functions.
The function mpz_size can be used to determine the useful range for
n.
mpz_tdiv_q_2exp(..., op, CHAR_BIT*sizeof(unsigned long
int)) can be used to decompose an integer into unsigned longs.
signed long int return the value of op.
Otherwise return the least significant part of op, with the same sign
as op.
If op is too large to fit in a signed long int, the returned
result is probably not very useful. To find out if the value will fit, use
the function mpz_fits_slong_p.
If str is NULL, space for the result string is allocated using the
default allocation function.
If str is not NULL, it should point to a block of storage enough large
for the result. To find out the right amount of space to provide for
str, use mpz_sizeinbase (op, base) + 2. The two
extra bytes are for a possible minus sign, and for the terminating null
character.
A pointer to the result string is returned. This pointer will will either
equal str, or if that is NULL, will point to the allocated storage.
Division is undefined if the divisor is zero, and passing a zero divisor to the
divide or modulo functions, as well passing a zero mod argument to the
mpz_powm and mpz_powm_ui functions, will make these functions
intentionally divide by zero. This lets the user handle arithmetic exceptions
in these functions in the same manner as other arithmetic exceptions.
There are three main groups of division functions:
mpz_tdiv. The `t' in the name is short for
`truncate'.
mpz_fdiv. The `f' in the
name is short for `floor'.
mpz_cdiv. The `c' in the
name is short for `ceil'.
For each rounding mode, there are a couple of variants. Here `q' means that the quotient is computed, while `r' means that the remainder is computed. Functions that compute both the quotient and remainder have `qr' in the name.
The function mpz_tdiv_q_ui returns the absolute value of the true
remainder.
The function mpz_tdiv_r_ui returns the absolute value of the remainder.
The function mpz_tdiv_qr_ui returns the absolute value of the remainder.
mpz_tdiv_r_ui, but the remainder is not stored anywhere; its
absolute value is just returned.
The function mpz_fdiv_q_ui returns the remainder.
The function mpz_fdiv_r_ui returns the remainder.
The function mpz_fdiv_qr_ui returns the remainder.
mpz_fdiv_r_ui, but the remainder is not stored anywhere; it is just
returned.
The function mpz_cdiv_q_ui returns the negated remainder.
The function mpz_cdiv_r_ui returns the negated remainder.
The function mpz_cdiv_qr_ui returns the negated remainder.
mpz_tdiv_r_ui, but the remainder is not stored anywhere; its
negated value is just returned.
mod d. The sign of the divisor is ignored;
the result is always non-negative.
The function mpz_mod_ui returns the remainder.
Since mpz_divexact is much faster than any of the other routines that produce the quotient (see section References Jebelean), it is the best choice for instances in which exact division is known to occur, such as reducing a rational to lowest terms.
mod mod. If
exp is negative, the result is undefined.
mpz_sqrt. Set rop2 to
op-rop1*rop1,
(i.e., zero if op is a perfect square).
If rop1 and rop2 are the same variable, the results are undefined.
The function uses Miller-Rabin's probabilistic test.
This function uses a probabilistic algorithm to identify primes, but for for practical purposes it's adequate, since the chance of a composite passing will be extremely small.
NULL, store the result there.
If the result is small enough to fit in an unsigned long int, it is
returned. If the result does not fit, 0 is returned, and the result is equal
to the argument op1. Note that the result will always fit if op2
is non-zero.
gcd(a, b). If t is
NULL, that argument is not computed.
mpz_kronecker_ui.
mpz_bin_ui, using the identity
@ifnottex
bin(-n,k) = (-1)^k * bin(n+k-1,k)
(see Knuth volume 1 section 1.2.6 part G).
These functions are actually implemented as macros. They evaluate their arguments multiple times.
This function is actually implemented as a macro. It evaluates its arguments multiple times.
These functions behave as if two's complement arithmetic were used (although sign-magnitude is used by the actual implementation).
It is possible to extend this function to return a useful value when the operands are both negative, but the current implementation returns MAX_ULONG in this case. Do not depend on this behavior, since it will change in a future release.
Functions that perform input from a stdio stream, and functions that output to
a stdio stream. Passing a NULL pointer for a stream argument to any of
these functions will make them read from stdin and write to
stdout, respectively.
When using any of these functions, it is a good idea to include `stdio.h' before `gmp.h', since that will allow `gmp.h' to define prototypes for these functions.
Return the number of bytes written, or if an error occurred, return 0.
Return the number of bytes read, or if an error occurred, return 0.
The output can be read with mpz_inp_raw.
Return the number of bytes written, or if an error occurred, return 0.
The output of this can not be read by mpz_inp_raw from GMP 1, because
of changes necessary for compatibility between 32-bit and 64-bit machines.
mpz_out_raw, and put the result in rop. Return the number of
bytes read, or if an error occurred, return 0.
This routine can read the output from mpz_out_raw also from GMP 1, in
spite of changes necessary for compatibility between 32-bit and 64-bit
machines.
The random number functions of GMP come in two groups; older function that rely on a global state, and newer functions that accept a state parameter that is read and modified. Please see the section Random Number Functions for more information on how to use and not to use random number functions.
The variable state must be initialized by calling one of the
gmp_randinit functions (section Random State Initialization) before
invoking this function.
The variable state must be initialized by calling one of the
gmp_randinit functions (section Random State Initialization)
before invoking this function.
The variable state must be initialized by calling one of the
gmp_randinit functions (section Random State Initialization)
before invoking this function.
This function is obsolete. Use mpz_urandomb or
mpz_urandomm instead.
This function is obsolete. Use mpz_rrandomb instead.
unsigned long int,
signed long int, unsigned int, signed int, unsigned
short int, or signed short int, respectively. Otherwise, return zero.
This function is useful in order to allocate the right amount of space before
converting op to a string. The right amount of allocation is normally
two more than the value returned by mpz_sizeinbase (one extra for a
minus sign and one for the terminating '\0').
This chapter describes the GMP functions for performing arithmetic on rational
numbers. These functions start with the prefix mpq_.
Rational numbers are stored in objects of type mpq_t.
All rational arithmetic functions assume operands have a canonical form, and canonicalize their result. The canonical from means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1.
Pure assignment functions do not canonicalize the assigned variable. It is the responsibility of the user to canonicalize the assigned variable before any arithmetic operations are performed on that variable. Note that this is an incompatible change from version 1 of the library.
mpq_clear) between each initialization.
mpq_t variables when you are done with them.
mpq_canonicalize before any operations are performed on rop.
To determine if two rationals are equal, mpq_equal is faster than
mpq_cmp.
This routine allows that num2 and den2 have common factors.
This function is actually implemented as a macro. It evaluates its arguments multiple times.
This function is actually implemented as a macro. It evaluates its arguments multiple times.
mpq_cmp can be used for the same purpose, this
function is much faster.
The set of mpq functions is quite small. In particular, there are few
functions for either input or output. But there are two macros that allow us
to apply any mpz function on the numerator or denominator of a rational
number. If these macros are used to assign to the rational number,
mpq_canonicalize normally need to be called afterwards.
mpz functions can be used on the result of these macros.
Functions that perform input from a stdio stream, and functions that output to
a stdio stream. Passing a NULL pointer for a stream argument to
any of these functions will make them read from stdin and write to
stdout, respectively.
When using any of these functions, it is a good idea to include `stdio.h' before `gmp.h', since that will allow `gmp.h' to define prototypes for these functions.
Return the number of bytes written, or if an error occurred, return 0.
These functions assign between either the numerator or denominator of a
rational, and an integer. Instead of using these functions, it is preferable
to use the more general mechanisms mpq_numref and mpq_denref,
together with mpz_set.
mpq_canonicalize before any operations
are performed on rational.
This function is equivalent to
mpz_set (mpq_numref (rational), numerator).
mpq_canonicalize before any operations are performed on rational.
In version 1 of the library, negative denominators were handled by copying the sign to the numerator. That is no longer done.
This function is equivalent to
mpz_set (mpq_denref (rational), denominators).
This function is equivalent to
mpz_set (numerator, mpq_numref (rational)).
This function is equivalent to
mpz_set (denominator, mpq_denref (rational)).
This chapter describes the GMP functions for performing floating point
arithmetic. These functions start with the prefix mpf_.
GMP floating point numbers are stored in objects of type mpf_t.
The GMP floating-point functions have an interface that is similar to the GMP
integer functions. The function prefix for floating-point operations is
mpf_.
There is one significant characteristic of floating-point numbers that has motivated a difference between this function class and other GMP function classes: the inherent inexactness of floating point arithmetic. The user has to specify the precision of each variable. A computation that assigns a variable will take place with the precision of the assigned variable; the precision of variables used as input is ignored.
The precision of a calculation is defined as follows: Compute the requested operation exactly (with "infinite precision"), and truncate the result to the destination variable precision. Even if the user has asked for a very high precision, GMP will not calculate with superfluous digits. For example, if two low-precision numbers of nearly equal magnitude are added, the precision of the result will be limited to what is required to represent the result accurately.
The GMP floating-point functions are not intended as a smooth extension to the IEEE P754 arithmetic. Specifically, the results obtained on one computer often differs from the results obtained on a computer with a different word size.
mpf_init will use this precision, but previously
initialized variables are unaffected.
An mpf_t object must be initialized before storing the first value in
it. The functions mpf_init and mpf_init2 are used for that
purpose.
mpf_clear, between initializations. The
precision of x is undefined unless a default precision has already been
established by a call to mpf_set_default_prec.
mpf_clear, between initializations.
mpf_t variables when you are done with them.
Here is an example on how to initialize floating-point variables:
{
mpf_t x, y;
mpf_init (x); /* use default precision */
mpf_init2 (y, 256); /* precision at least 256 bits */
...
/* Unless the program is about to exit, do ... */
mpf_clear (x);
mpf_clear (y);
}
The following three functions are useful for changing the precision during a calculation. A typical use would be for adjusting the precision gradually in iterative algorithms like Newton-Raphson, making the computation precision closely match the actual accurate part of the numbers.
realloc, this routine
should not be called in a tight loop.
mpf_get_prec. It is crucial that the precision of rop is
ultimately reset to exactly the value returned by mpf_get_prec before
the first call to mpf_set_prec_raw.
These functions assign new values to already initialized floats (see section Initialization Functions).
The argument base may be in the ranges 2 to 36, or -36 to -2. Negative values are used to specify that the exponent is in decimal.
Unlike the corresponding mpz function, the base will not be determined
from the leading characters of the string if base is 0. This is so that
numbers like `0.23' are not interpreted as octal.
White space is allowed in the string, and is simply ignored. [This is not really true; white-space is ignored in the beginning of the string and within the mantissa, but not in other places, such as after a minus sign or in the exponent. We are considering changing the definition of this function, making it fail when there is any white-space in the input, since that makes a lot of sense. Please tell us your opinion about this change. Do you really want it to accept "3 14" as meaning 314 as it does now?]
This function returns 0 if the entire string up to the '\0' is a valid number in base base. Otherwise it returns -1.
For convenience, GMP provides a parallel series of initialize-and-set functions
which initialize the output and then store the value there. These functions'
names have the form mpf_init_set...
Once the float has been initialized by any of the mpf_init_set...
functions, it can be used as the source or destination operand for the ordinary
float functions. Don't use an initialize-and-set function on a variable
already initialized!
The precision of rop will be taken from the active default precision, as
set by mpf_set_default_prec.
mpf_set_str above for details on the assignment operation.
Note that rop is initialized even if an error occurs. (I.e., you have to
call mpf_clear for it.)
The precision of rop will be taken from the active default precision, as
set by mpf_set_default_prec.
If str is NULL, space for the mantissa is allocated using the default
allocation function.
If str is not NULL, it should point to a block of storage enough large
for the mantissa, i.e., n_digits + 2. The two extra bytes are for a
possible minus sign, and for the terminating null character.
The exponent is written through the pointer expptr.
If n_digits is 0, the maximum number of digits meaningfully achievable
from the precision of op will be generated. Note that the space
requirements for str in this case will be impossible for the user to
predetermine. Therefore, you need to pass NULL for the string argument
whenever n_digits is 0.
The generated string is a fraction, with an implicit radix point immediately to the left of the first digit. For example, the number 3.1416 would be returned as "31416" in the string and 1 written at expptr.
A pointer to the result string is returned. This pointer will will either
equal str, or if that is NULL, will point to the allocated storage.
Division is undefined if the divisor is zero, and passing a zero divisor to the divide functions will make these functions intentionally divide by zero. This lets the user handle arithmetic exceptions in these functions in the same manner as other arithmetic exceptions.
This function is actually implemented as a macro. It evaluates its arguments multiple times.
Functions that perform input from a stdio stream, and functions that output to
a stdio stream. Passing a NULL pointer for a stream argument to any of
these functions will make them read from stdin and write to
stdout, respectively.
When using any of these functions, it is a good idea to include `stdio.h' before `gmp.h', since that will allow `gmp.h' to define prototypes for these functions.
In addition to the significant digits, a leading `0.' and a trailing exponent, in the form `eNNN', are printed. If base is greater than 10, `@' will be used instead of `e' as exponent delimiter.
Return the number of bytes written, or if an error occurred, return 0.
The argument base may be in the ranges 2 to 36, or -36 to -2. Negative values are used to specify that the exponent is in decimal.
Unlike the corresponding mpz function, the base will not be determined
from the leading characters of the string if base is 0. This is so that
numbers like `0.23' are not interpreted as octal.
Return the number of bytes read, or if an error occurred, return 0.
mpf_ceil rounds to
the next higher integer, mpf_floor to the next lower, and
mpf_trunc to the integer towards zero.
The variable state must be initialized by calling one of the
gmp_randinit functions (section Random State Initialization)
before invoking this function.
This chapter describes low-level GMP functions, used to implement the high-level GMP functions, but also intended for time-critical user code.
These functions start with the prefix mpn_.
The mpn functions are designed to be as fast as possible, not
to provide a coherent calling interface. The different functions have somewhat
similar interfaces, but there are variations that make them hard to use. These
functions do as little as possible apart from the real multiple precision
computation, so that no time is spent on things that not all callers need.
A source operand is specified by a pointer to the least significant limb and a limb count. A destination operand is specified by just a pointer. It is the responsibility of the caller to ensure that the destination has enough space for storing the result.
With this way of specifying operands, it is possible to perform computations on subranges of an argument, and store the result into a subrange of a destination.
A common requirement for all functions is that each source area needs at least one limb. No size argument may be zero. Unless otherwise stated, in-place operations are allowed where source and destination are the same, but not where they only partly overlap.
The mpn functions are the base for the implementation of the
mpz_, mpf_, and mpq_ functions.
This example adds the number beginning at s1p and the number beginning at s2p and writes the sum at destp. All areas have size limbs.
cy = mpn_add_n (destp, s1p, s2p, size)
In the notation used here, a source operand is identified by the pointer to the least significant limb, and the limb count in braces. For example, {s1p, s1size}.
This is the lowest-level function for addition. It is the preferred function
for addition, since it is written in assembly for most targets. For addition
of a variable to itself (i.e., s1p equals s2p, use
mpn_lshift with a count of 1 for optimal speed.
This function requires that s1size is greater than or equal to s2size.
This is the lowest-level function for subtraction. It is the preferred function for subtraction, since it is written in assembly for most targets.
This function requires that s1size is greater than or equal to s2size.
The destination has to have space for 2*size limbs, even if the significant result might be one limb smaller.
This is a low-level function that is a building block for general multiplication as well as other operations in GMP. It is written in assembly for most targets.
Don't call this function if s2limb is a power of 2; use
mpn_lshift with a count equal to the logarithm of s2limb
instead, for optimal speed.
This is a low-level function that is a building block for general multiplication as well as other operations in GMP. It is written in assembly for most targets.
This is a low-level function that is a building block for general multiplication and division as well as other operations in GMP. It is written in assembly for most targets.
The destination has to have space for s1size + s2size limbs, even if the result might be one limb smaller.
This function requires that s1size is greater than or equal to s2size. The destination must be distinct from either input operands.
The quotient written at qp will be nn - dn + 1 limbs. The remainder written at rp will be dn limbs.
It is required that nn is greater than or equal to dn. The qxn operand must be zero.
The quotient is rounded towards 0.
No overlap between arguments is permitted.
mpn_tdiv_qr instead for
best performance.]
Divide {rs2p, rs2size} by {s3p, s3size}, and write the quotient at r1p, with the exception of the most significant limb, which is returned. The remainder replaces the dividend at rs2p; it will be s3size limbs long (i.e., as many limbs as the divisor).
In addition to an integer quotient, xsize fraction limbs are developed, and stored after the integral limbs. For most usages, xsize will be zero.
It is required that rs2size is greater than or equal to s3size. It is required that the most significant bit of the divisor is set.
If the quotient is not needed, pass rs2p + s3size as r1p. Aside from that special case, no overlap between arguments is permitted.
Return the most significant limb of the quotient, either 0 or 1.
The area at r1p needs to be rs2size - s3size + xsize limbs large.
The integer quotient is written to {r1p+xsize, s2size} and in addition xsize fraction limbs are developed and written to {r1p, xsize}. Either or both s2size and xsize can be zero. For most usages, xsize will be zero.
mpn_divmod_1 exists for upward source compatibility and is simply a
macro calling mpn_divrem_1 with an xsize of 0.
The areas at r1p and s2p have to be identical or completely separate, not partially overlapping.
mpn_divrem in its stead.
mpn_divexact_by3c takes an initial carry parameter, which can be the
return value from a previous call, so a large calculation can be done piece by
piece. mpn_divexact_by3