PageRenderTime 31ms CodeModel.GetById 17ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

Plain Text | 845 lines | 691 code | 154 blank | 0 comment | 0 complexity | 1bf1ed5a11f3a0367f2f3f82cecc6f38 MD5 | raw file
  1gmpy module -- a complete Python 2.4+ and 3.x interface for GMP/MPIR.
  4*Notes on history of file gmpydoc.txt*
  6Notes for version 0.1 (pre-alpha), first one placed on sourceforge
  7-- A. Martelli,, 00/11/06.
  9Edited for version 0.2 (still pre-alpha), bugfixes & minor
 10performance tweaks, 00/11/15 -- many thanks to Pearu Peterson for
 11his contributions re 0.1 -> 0.2!
 13Edited for version 0.3 (ditto) -- cleanup, exposing more mpz
 14functions (almost all there...!), large performance-tweaks via
 15caching (tx to PP for the inspiration!), some unit-tests -- **NEED
 16MANY MORE TESTS FOR 0.4**!!! -- 00/11/18.
 18Small edits for version 0.4 (ditto) -- just a couple more
 19functions, and minor error-corrections -- 11/24.  (Added
 20docstrings in 0.4; would be nice to build a doc of some kind
 21automatically from ONE place...).
 23Edited for version 0.5 (ditto) -- documented the new functionality
 24(mostly mpq; also: random, jacobi/legendre/ kronecker), minor
 25cleanups & corrections -- 11/30.
 27Editing for versions 0.6 (12/07), 0.7 (12/16), 0.8 (12/26):
 28documented new functionalities, and performed minor cleanups
 29& corrections, each time.
 31Very minor editing for version 0.9 (2001/01/25).
 32Minor editing for version 0.9b (2002/02/28).
 33Minor editing for version 0.9c (2002/03/05).
 34Minor editing for version 1.0 (2003/08/08).
 35Minor editing for version 1.01 (2005/11/12);
 36maintainer's preferred email changed to .
 37Minor editing for version 1.02 (2007/02/19).
 38Minor editing for version 1.03 (2008/06/22).
 39Minor editing for version 1.04 (2008/10/16).
 40Minor editing for version 1.10 (2009/10/18)
 45gmpy 0.1 was based on previous versions of gmpmodule.c (for
 46earlier Python and GMP releases) by AMK and Niels Möller (only
 47removed feature: conditional possibility to substitute this
 48implementation in place of Python's built-in longs; lots and lots
 49of added features).
 51Special thanks are due to Pearu Peterson for his MANY important
 52inputs on design aspects, performance tweak suggestions, and bug
 55Thanks also to Keith Briggs for his precious feedback, and to Tim
 56Peters, Fredrik Lundh, "and a cast of thousands" (posters to and, in some few cases, gmpy's sf discussion groups) for their
 58suggestions.  Furthermore, thanks to Case Van Horsen, who provided
 59the Windows binary installers for gmpy 1.01.
 61Chip Turner and Daniel Lord helped with the changes leading to version
 621.02, so, thanks to them as well!
 64Case Van Horsen has done almost all of the work leading to version 1.03,
 65so, SUPER thanks!-)  (He's also pointed out the issues requiring the
 66enhancements in 1.04, mainly rich comparisons, and done other changes
 67leading from 1.03 to 1.04).
 70*Installation and testing*
 72Pre-requisites: Python 2.4+ or 3.x, and recent versions of GMP
 73( or MPIR ( gmpy has been tested
 74with GMP version 4.2+ and MPIR 1.2+.
 76To build gmpy from sources, get the sources from svn (or a sources
 77zipfile, such as from
 78Place the source code into a new, dedicated directory, cd to that
 79directory (from any shell on Unix/Linux, or from Terminal on Mac OS X),
 80and run:
 82    python install
 84The DistUtils that come with Python take over and build and
 85install the gmpy module for you (you may need to use 'sudo' or
 86'su' appropriately to actually perform the installation, depending
 87on the permissions you're using on Python's site-packages).
 89Detailed instructions for building on Windows are included in
 90"windows_build.txt" and "win_x64_sdk_build.txt". "windows_build.txt"
 91describes the build process using Mingw32 and MSYS and was used to
 92build the 32-bit Windows binaries. "win_x64_sdk_build.txt" describes
 93the build process using the Microsoft Platform SDK and was used to
 94build the 64-bit Windows binaries. The MPIR library offers better
 95support for Windows and is recommended.
 97The file "mac_build.txt" contains detailed instructions for compiling
 98GMP and GMPY on MacOSX (or getting GMP via mactools/darwintools).
100The sources zipfile also contains this file (gmpydoc.txt), an
101example C source file for a separate module that uses the C-API of
102gmpy to interoperate with it, a copy of the index.html for the
103gmpy sourceforge site, and python scripts that exemplify, show the
104performance of, and test, some functionality of the gmpy module.
106To test the installation, cd to the directory where you unpacked
107the gmpy sources, and run, at the command prompt:
109        cd test
111(Note: use "cd test3" if you are using Python 3.x.)
113and then, at the next prompt:
115        python
118Expected output is something like (details may differ!):
121Unit tests for gmpy 1.02 release candidate
122    on Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
123[GCC 4.0.1 (Apple Computer, Inc. build 5341)]
124Testing gmpy 1.02 (GMP 4.2), default caching (20, 20, -2..11)
125gmpy_test_cvr 270 tests, 0 failures
126gmpy_test_rnd  26 tests, 0 failures
127gmpy_test_mpf 155 tests, 0 failures
128gmpy_test_mpq 264 tests, 0 failures
129gmpy_test_mpz 386 tests, 0 failures
130gmpy_test_dec  16 tests, 0 failures
1317 items had no tests:
132    [[ snip snip ]]
13331 items passed all tests:
134    [[ snip snip ]]
1351117 tests in 38 items.
1361117 passed and 0 failed.
137Test passed.
140Should you wish to test some specific portion, please note that
141each of the various modules listed at the start can also be run
142independently, if so desired:
143        python
144        python
145and so on, expecting output analogous to the above example.  You
146may also run, for example,
147        python -v
148to get very verbose and detailed output.  However, in any case,
149the key issue is the 'Test passed' line at the end of each run!
151*PLEASE* report any failures to gmpy's maintainers, with all details you
152can supply on your machine, on your OS, and on your installation of GMP
1534, gmpy 1.04, Python 2.3, 2.4, 2.5, or 2.6, and any other relevant issue
154(your C/C++ compiler & libraries, &c).  *THANKS* in advance -- bug
155reporting and feedback is your key contribution to the gmpy project!
156(Reports of any _successful_ installations will also be welcome, if it's
157accompanied by enough details -- again, THANKS in advance!).  The best
158way to report bugs (including unit-test failures) is via the Google Code
159issue tracker.
162*General notes on gmpy*
164Note that the mpfr() type from the MPFR library replaced GMP's mpf()
165type in gmpy2.
167gmpy exposes to Python three types of numbers that are implemented
168in GMP and MPIR:
169    mpz unlimited-precision integers
170    mpq unlimited-precision rationals
171    mpf extended-precision floats
173See GMP documentation for general descriptions of them!
174    GNU MP Home Page:
176The MPIR documentation is available from:
177    MPIR Home Page:
179Licensing: gmpy is licensed under LGPL v2 or later. MPIR is also
180licensed under LGPL v2 or later. GMP converted to LGPL v3 beginning
181with version 4.2.2. IANAL, but, summarizing, this means: other
182_libraries_ that are derived from gmpy must also be distributed
183under the LPGL (or full-GPL), as must any modifications/additions to
184gmpy; but, no such restriction applies on code that just _uses_ these
185modules/libraries (such gmpy-using code may thus be licensed in whatever
186way is desired).
188Warranty: NONE -- as usual for open-source software (see the
189detailed disclaimers in GMP's license)!
192*gmpy.mpz -- unlimited-precision integral numbers*
194gmpy.mpz objects have the full arithmetic abilities of Python
195longs (in the future, there may also be mutable versions of them
196[for performance], but NOT yet).
198Specifically, arithmetic operators + and - (unary and binary), *,
199/ (truncating), %, **, bitwise operators such as &, |, ^, <<, >>,
200~, and builtin Python functions such as divmod and pow, all work
201as expected on mpz objects (basically, the same way as on builtin
202Python longs, except that the speed can be quite different -- from
203'a bit slower' for some things, up to much faster for others [such
204as multiplication of huge numbers]).
206Mixed-operand arithmetic is supported: the other operand (which
207must be a number of some kind) is coerced to a gmpy.mpz, unless
208it's of a floating type, in which case both operands are coerced into
209a gmpy.mpf object. Instances of the decimal.Decimal class are coerced
210into gmpy.mpf also. Instances of the fractions.Fraction class are
211coerced int gmpy.mpq.
213An mpz object can be  built by passing to the gmpy.mpz constructor
214function any Python built-in, non-complex number, another mpz
215(this *shares* object identity, does *not* copy it -- which should
216be indifferent, since such objects are in any case immutable), a
217mpq or mpf (which gets truncated, as also a Python float does), or
218a string (representing the number in base 10).
220gmpy.mpz can also be called with TWO arguments: the first one a
221string representing the number in some base N, the second one, the
222integer N.  N can be between 2 and 36, or it can be 256, which
223implies that the string is the _portable binary gmpy
224representation_ of the mpz (as produced by method .binary() of mpz
225objects, and function gmpy.binary() of the module).
227An N of 0 is also accepted, and means the string is interpreted as
228decimal, unless it starts with 0x (then, hexadecimal) or 0 (then,
229octal).  When N=16 a starting a leading '0x' is also accepted, but
230not required; leading 0's are always accepted and ignored (they do
231NOT mean the rest is taken as octal!) if the base N is explicitly
232given as a Python int, or if it's omitted (and defaults to 10).
234*NOTE* that the trailing-L in a Python's "long" string
235representation is NOT accepted in the string argument to
238(Please note that all from-string transformations are performed by
239GMP or MPIR, and thus may follow slightly different conventions from
240normal Python ones).
242An mpz object can be transformed into a Python number by passing
243it as the argument of a call to Python's built-in number types
244(int, long, float, complex); it can also be formatted as an octal
245or hex string with Python built-in functions oct and hex.
247mpz objects also support the hash built-in function, and can thus
248be used as dictionary keys; for any Python int or long N,
249hash(mpz(n)) and hash(n) are equal.
251Other operations on mpz objects are all exposed as functions of
252module gmpy, and some, also, as methods of mpz objects.  Unless
253otherwise noted, arguments to the following gmpy module functions
254are coerced to mpz (unless already of mpz type), and values
255returned from either functions or methods are also of mpz type.
257gmpy.binary(x) or x.binary(): returns a portable binary
258representation (base-256 little endian) of an mpz object, suitable
259for saving into a file (or db, whatever) -- this string can later
260be passed as the first argument to function gmpy.mpz (with a
261second argument with value 256) to reconstruct a copy of the
262original mpz object.  *NOTE*: the binary format used by gmpy
263release 0.7 and later is not compatible with that of 0.6 and
264earlier, as the latter, as a design limitation, could not
265represent any mpz number that was < 0.
267gmpy.digits(x[,base]) or x.digits([base]): returns a string
268representing x in the given base (between 2 and 36, defaulting to
26910 if omitted or zero); a leading '-' will be present if x<0, but
270no leading '+' if x>=0.  If base is 8 or 16, a decoration of a
271leading '0' (or, respectively, '0x') is present (after the '-'
272sign, if the number is negative).
274gmpy.numdigits(x[,base]) or x.numdigits([base]): returns an
275approximation to the number of digits for x in the given base
276(result is either exact [guaranteed if base is a power or 2] or 1
277more than actual length; space for a "sign", or leading
278decorations of '0' or '0x', is NOT considered).  Base must be
279between 2 and 36, defaulting to 10 if omitted or zero.
281gmpy.sign(x) or x.sign(): -1, 0, or 1, depending on whether x is
282negative, zero, or positive.
284gmpy.divm(a, b, M): x such that b*x == a modulo M (will raise a
285ZeroDivisionError exception if no such x exists).
287gmpy.fac(x): factorial of x (takes O(x) time; x must be an
288ordinary Python non-negative integer!)
290gmpy.fib(x): x-th Fibonacci number (takes O(x) time; x must be an
291ordinary Python non-negative integer).
293gmpy.gcd(a,b): greatest common divisor of a and b (an mpz, >= 0).
295gmpy.gcdext(a, b): a tuple (g,s,t) such that
296    g==gmpy.gcd(a,b) and g == a*s + b*t
297(g, s and t are all mpz).
299gmpy.lcm(a,b): least common multiple of a and b (an mpz, >= 0).
301gmpy.is_square(x) or x.is_square(): 1 iff x is a perfect square,
302else 0 (returns Python int).
304gmpy.is_power(x) or x.is_power(): 1 iff x is a perfect power
305(i.e., there exist a, b such that a**b==x and b>1), else 0
306(returns Python int).
308gmpy.is_prime(x [, count]) or x.is_prime([count]): 2 if x is
309_certainly_ prime, 1 if x is _probably_ prime, 0 if x is
310_certainly_ composite; count defaults to 25 (probability of
311non-primality, if is_prime returns 1, is guaranteed to be no
312higher than 1 in 2**count).  Returns Python int.
313NOTE: GMP believes negative numbers can be primes, and gmpy just
314reflects this stance (cfr discussion at
317gmpy.next_prime(x) or x.next_prime(): returns mpz that is the
318lowest prime > x; *probabilistic* algorithm for
319prime-determination (see is_prime).
321gmpy.sqrt(x) or x.sqrt(): integer square-root of non negative
322number (truncating, unless is_square(x)).
324gmpy.sqrtrem(x) or x.sqrtrem(): tuple (s,t) such that
325s==gmpy.sqrt(x) and x==s*s+t.  (s and t are mpz, >= 0).
327gmpy.root(x,n) or x.root(n): tuple (s,b) such that s is the
328truncated nth-root of x, b!=0 if s is the _exact_ root (i.e.
329x==s**n); n must be an ordinary Python int, >0.  (s is an mpz, b a
330Python int).
332gmpy.bincoef(x, N) or x.bincoef(N): binomial coefficient "x over
333N"; N must be an ordinary Python int, >=0! (x may be < 0 , see
334Knuth vol 1, sect 1.2.6, part G).  [Also known as: gmpy.comb(x, N)
335or x.comb(N), since the binomial coefficient is also the number of
336different combinations of x objects taken N at a time, with
337ordering ignored].
339gmpy.remove(x, f) or x.remove(f): "remove factors": returns a
340two-element tuple (y,m), where y, an mpz, is x without any factor
341of f, and m (an ordinary Python int) is the multiplicity of f in x
342(e.g.: m==0 and y==x unless x%f==0; and in any case, it's ensured
343that x==y*(f**m) and that y%f!=0).
345gmpy.invert(x, m) or x.invert(m): modulo-inverse; returns an y
346such that x*y mod m = 1, if one exists, else 0 (returns an mpz in
347either case).
350gmpy.lowbits(x, n) or x.lowbits(n): returns the n lowest bits of x
351(n must be an ordinary Python int, >0; returns an mpz, >= 0).
352Note that x<0 is assumed to be in 2's complement notation (i.e.,
353"extended on the left" with infinite 1-bits); so, for example, for
354any n>0, gmpy.lowbits(-1,n) returns an mpz>0 with the lowest n
355bits set to 1, i.e., (2**n)-1.
357gmpy.setbit(x, n, v) or x.setbit(n, v), n being a bitindex (0 and
358up, ordinary Python int) and v an int value (0 or 1, default 1):
359returns a copy of x with bit n set to v (mpz's are not mutable --
360yet...!).  [Any value v != 0 is equivalent to v=1, i.e., the bit
361is 'set'; so, for example, gmpy.setbit(0,n,-4) for any n>=0
362returns an mpz worth 2**n].
364gmp.getbit(x, n) or x.getbit(n), n being a bitindex (0 and up,
365ordinary Python int): returns an int which is 0 or 1, same as the
366value of bit n of x.  (See note on gmpy.lowbits for x<0).
368gmpy.scan0(x [, n]) or x.scan0([n]): returns the bit index of the
369next 0-bit starting at bit n (default 0); n must be an ordinary
370Python int, >=0; returns a Python int (-1 if there is no such
371bit-index, which can only happen for an x<0, which notionally is
372extended with infinite 1-bits).
374gmpy.scan1(x [, n]) or x.scan1([n]): returns the bit index of the
375next 1-bit starting at bit n (default 0); n must be an ordinary
376Python int, >=0; returns a Python int (-1 if there is no such
377bit-index, which can only happen for an x>=0, which notionally is
378extended with infinite 0-bits).
380gmpy.popcount(x) or x.popcount(): returns the "population count"
381(number of bits set to 1) of x; note that this is 'infinite' for
382x<0 (-1 is then returned).  Returns a Python int.
384gmpy.hamdist(x,y) or x.hamdist(y): returns the Hamming-distance
385|x,y| if both >=0 or both < 0 (returns -1 if one but not both are
386<0) (the hamming distance is defined as: the number of
387bit-positions in which the two numbers differ).  Returns a Python
388int.  Same as gmpy.popcount(x^y).
390gmpy._copy(x) or x._copy(): provide a separate copy of x (only
391relevant for future mutability of mpz... currently useless!).
393gmpy.divexact(x,y): returns the quotient of x divided by y. It uses
394a faster division algorithm but requires that the remainder is 0.
395It will return garbage if the remainder is not 0! (New in 1.04.)
397*gmpy module-level setting functions*
398[NOTE: the overall architecture of these functions is due to be
399reworked sooner or later, NOT backwards-compatibly].
401gmpy.set_debug(flag): turns on/off debugging output from the gmpy
402module (returns previous setting).  [Only of interest to
403develop/debug gmpy itself!] Argument must be an ordinary Python
404int: debug is set on if flag!=0, off if flag==0.  Returns a Python
405int (0 or 1, the _previous_ setting).
407gmpy.set_tagoff(flag): turns off/on the 'gmpy.' prefix to the
408"tag" that repr() places around the string-representation of gmpy
409objects (returns a Python int, 0 or 1, the previous setting).
411gmpy. get_zcache(), set_zcache(N), get_zconst(), set_zconst(N,M),
412get_qcache(), set_qcache(N)...: *internal tweaks/experimental
413stuff*, please don't use them unless you've read the C sources and
414understand what they do!  Not further documented here (docstrings
415for these functions in gmpy may give a little more detail).
418*gmpy.mpq -- unlimited-precision rational numbers*
420gmpy.mpq objects have a subset of the arithmetic abilities of
421Python floats (in the future, mutable versions will also be
422supplied, but, NOT YET!), but represent arbitrary rational numbers
423with no loss of precision whatsoever.
424[Note, in particular, that raising-to-power works only without a
425modulo, and, if the exponent is a fraction with a denominator D
426(or gets converted to one), the base must be an exact D-th power,
427or the operation fails raising a ValueError exception].
429Mixed-operand arithmetic is supported: the other operand is
430coerced to a gmpy.mpq.  NOTE: the % operator and the divmod
431built-in function are NOT supported.  mpq objects also support the
432hash built-in function, and can thus be used as dictionary keys;
433for any Python int or long N, hash(mpq(n)) and hash(n) are equal.
435A mpq object has a _numerator_ and a _denominator_; they can be
436obtained by calling on an mpq object the methods .numer() and
437.denom() -- each method has no arguments and returns an mpz (the
438denominator will always be >0; the numerator can be any; also, the
439numerator and denominator never have any common factors; mpq
440corresponding to integers, including 0, always have a denominator
441of exactly 1).
444An mpq is built by passing to the gmpy.mpq constructor function
445any Python number, another mpq (this *shares* object identity,
446does *not* copy it), a mpf or mpz, or a string (representing the
447number in base 10).  [If an mpf or float argument is passed, the
448mpq is built from it with an 'optimal' approach based on a
449Stern-Brocot tree; see also the f2q method of mpf objects, and
450gmpy.f2q module-level function, which differ from explicit
451mpq-construction in that it can return an mpz if the mpq's
452denominator would be 1].
454gmpy.mpq can also be called with TWO arguments: the first one a
455string representing the number in base N, the second one, the
456integer N.  N can be between 2 and 36, or, it can be 256, which
457implies that the string is the _portable binary gmpy
458representation_ of the mpq (as produced by method .binary() of mpq
459objects, and function gmpy.qbinary() of the module).
461gmpy.mpq is typically called with a string that contains a '/'
462character: the digits before it will then be taken as the
463numerator, those after it, as the denominator (the resulting
464number is normalized: denominator>0, no common factors).  A
465ZeroDivisionError is raised if the denominator thus supplied is
466zero; a ValueError, if the string is otherwise invalid (e.g., '/3'
467or '3/').  Hex and octal representations are supported if the base
468N is given as 0; see above gmpy.mpz; for example,
469mpq('0x13/011',0) is the same as mpq(19,9).
471gmpy.mpq can also be called with two number arguments: the first
472one is taken as the numerator, the second one as the denominator
473(the resulting number is normalized: denominator>0, no common
474factors).  A ZeroDivisionError is raised if the denominator thus
475supplied is zero.
478Other operations on mpq objects are all exposed as functions of
479modules gmpy, and some, also, as methods of mpq objects:
481gmpy.qbinary(x) or x.binary(): returns a portable binary
482representation of any mpq object.
484gmpy.qsign(x) or x.sign(): -1, 0, or 1, depending on whether x is
485negative, zero, or positive.
487gmpy.qdiv(x[,y]) or x.qdiv([y]), which is _also_ supplied as a
488method on mpz and mpf objects (which are implicitly converted to
489mpq's in this case): return x/y (or just x, if y is absent), as an
490mpz if possible (==if a resulting mpq would have a denominator of
4911), else as an mpq (with a denominator > 1).  The functions are
492optimized, so that, if x is an mpz and y is absent or 1, or if x
493is an mpq with a denom>1 and y is absent or 1, then the same
494object-identity as x is returned, so that the operation is very
495fast.  In other words, gmpy.qdiv only ever takes substantial time
496if it DOES have an important job to perform, and can thus be
497called rather freely, even in loops, to 'normalize' numeric
500Specifically, please note that, for an x that is an mpq, x.qdiv()
501returns either x, if x.denom()==1, or else the same mpz as
502x.numer() would return; if x is an mpz, x.qdiv() returns x (so it
503can be used polymorphically on an x that can be either, without
504any performance hit).
508*gmpy.mpf -- variable-precision floating numbers*
510gmpy.mpf objects have a subset of the arithmetic abilities of
511Python floats (in the future, mutable versions will also be
512supplied, but, NOT YET!).
514Mixed-operand arithmetic is supported: the other operand is
515coerced to a gmpy.mpf, except that, if the other operand is an
516mpq, then both are coerced to mpq.  NOTE: trigonometric and
517exponential functionalities on mpf objects are NOT currently
518supported [GMP 3.1.1 had none; waiting to expose the MPFR
519extensions to GMP.]  mpf objects also support the hash built-in
520function, and can thus be used as dictionary keys; for any Python
521float X, hash(mpf(x)) and hash(x) are equal.
523Each mpf object has a _precision_ -- a number of bits of precision
524to which values are stored in it.  The precision of all newly
525generated mpf's is at least that set at module level via module
526function gmpy.set_minprec(n); a specific mpf's precision can be
527set to >= n bits by x.setprec(n); it can be queried (the exact
528current number of bits of precision is returned) by x.getprec() or
529gmpy.getprec(x).  The granularity of precision of current MPF's is
530rough; exact precision setting is one of MPFR's enhancements.  To
531get the actual precision that was _requested_ for a given mpf
532object, x.getrprec() and gmpy.getrprec(x) are also supplied -- the
533value returned from getprec will always be greater than, or equal
534to, the one returned from getrprec.
536** The following behavior is in new in gmpy 1.04. **
538GMP only guarantees that the precision of a result is greater than
539or equal to the requested precision. But comparisons would use all
540the bits computed, regardless of whether they are accurate. This
541leads to situations where mpf('1.1') * mpf('1') != mpf('1.1').
542Beginning with gmpy 1.04, the results of all mpf calculations are
543rounded to the requested precision.
545Note: GMP uses radix 2**32 (or 2**64) arithmetic and rounding is
546done on those boundaries. Let's assume we request 53 bits of
547precision on a 32-bit system. GMP rounds the requested precision
548up to 64 bits and then allocates three 32-bit words to store the
549mantissa. GMP also allocates one additional 32-bit word to simplify
550their internal operations. The additional word may or may not be
551present on any particular result. So in our scenario, GMP can return
552a mantissa with anywhere between 65 and 128 bits. The presence of
553the additional word caused the strange behavior with comparisons.
554If the additional word is present, the mantissa is rounded and the
555additional word is set to 0 so the effective precision is between
55665 and 96 bits.
558** End new section. **
560An mpf is built by passing to the gmpy.mpf constructor function
561any Python built-in number, another mpf (this *shares* object
562identity, does *not* copy it -- unless specific precision is
563requested for the resulting mpf, see later), a mpq or mpz, or a
564string (representing the number in base 10, possibly with decimal
565point and/or exponent).
567If gmpy.mpf is called with a float argument, the exact steps used
568in conversion depend on the setting of module level option fcoform
569(set by gmpy.set_fcoform()).
571If fcoform is None, the float number is converted 'exactly' to an
572mpf (which often leaves spurious trailing bits from literals).  If
573fcoform is a string, it's used as the format (left operand of %)
574in a formatting operation (with the float being transformed as the
575right operand), and the resulting intermediate string is the one
576that actually gets transformed to mpf (this normally gives good
577results with formats somewhere between '%.12e' and '%.16e',
578depending on the actual precision of the float being transformed).
580fcoform also applies to _implicit_ conversions of float to mpf, as
581invoked for mixed-mode arithmetic or when gmpy functions expecting
582an mpf argument are called with a float argument (a string could
583not be passed _explicitly_ here -- an explicit mpz() around it
584would be needed -- but it's OK if a float gets _implicitly_
585converted-to-mpf-via-string in these cases, through the fcoform
588An optional second argument can always be supplied to gmpy.mpf,
589whether the first argument is a number or a string; if supplied,
590it must be a Python int, >=0.  If absent or 0, the precision of
591the mpf that is generated is determined by default depending on
592the input argument (in many cases, it's the number of significant
593bits in machine-floats; e.g., 53 on machines using IEEE 64-bit
594floating point).  If the second argument is supplied and > 0, it's
595used as the requested-precision for the resulting mpf, ignoring
596the bits-of-precision held or implied by the first argument.
597Note, that if x is an mpf with n bits of precision, gmpy.mpf(x,m)
598will be able to return the same object identity as x if, and only
599if, m==n; else, a new mpf object of the requested precision will
600be generated.
602Note that, in arithmetic operations, the bits of precision of the
603result are generally set to the _lowest_ number of
604bits-of-precision of all the operands involved.
607gmpy.mpf can also be called with *3* arguments: the first one a
608string representing the number in base N, the second one the bits
609of precision requested (or 0 to accept the default determination
610of the bits), the third one, the integer N.  N can be between 2
611and 36, or, it can be 256, which implies that the string is the
612_portable binary gmpy representation_ of the mpf (as produced by
613method .binary() of mpf objects, and function gmpy.fbinary() of
614the module).  (Hex and octal decorations are *not* supported here;
615an N of 0 is totally equivalent to one of 10).
617Note that therefore, if a reasonable fcoform is set, two
618constructor calls such as
619    gmpy.mpf(3.4)
621    gmpy.mpf('3.4')
622will produce the same mpf object, although the second way is
623faster (and does not depend on the module-level fcoform setting)
624and recommended as preferable to the first one.
627Other operations on mpf objects are all exposed as functions of
628modules gmpy, and some, also, as methods of mpf objects:
630gmpy.fbinary(x) or x.binary(): returns a portable binary
631representation of any mpf object.
633gmpy.fdigits(x[,args...]) or x.digits([args]): returns a string
634representing x.  Arguments (must currently be passed positionally,
635if at all -- keywords NOT accepted!) are...:
636    base: number-base (between 2 and 36), default 10
637    digits: how many digits are requested (default 0,
638        "all of them" within x's precision; fewer than
639        requested may be obtained, if fewer available)
640    minexp: minimum exponent for which the number is
641        still to be formatted in integer.fraction form
642        (it's formatted as fraction-exponent form if
643        exponent is lower than minexp), default 0
644    maxexp: maximum exponent for which the number is
645        still to be formatted in integer.fraction form
646        (it's formatted as fraction-exponent form if
647        exponent is higher than maxexp), default -1
648    option: bitmask argument, default 0 (no options)
650Note that, by default, the formatting is in fraction-and-exponent
652    [<sign>]<digit>.<digits><marker><signed exponent>
653sign is '-' if x is negative, omitted if x>=0
654<marker> is 'e' for base<=10, otherwise '@'
655the signed exponent (sign omitted if exponent>=0) is always
656expressed in base 10, whatever the base used for the significand's
659If option's bit 1 is set, the whole result string is enclosed
660between "gmpy.mpf('" at the start and "')" at the end, so it can
661be subject to eval to recover an approximation of the original
662number (depending on the settings of gmpy.set_tagoff(), the
663starting tag may actually be shortened to just "mpf('").  The
664precision, in bits, is also output in this case, just before the
665')', separated from the "first argument to gmpy.mpf" by a comma
666character (it is the same number as returned by .getrprec).
668If option's bit 2 is set, then minexp, maxexp, and option's bit 1,
669are ignored: the result is a tuple of 2 objects: first, a string
670made up of all the digits (and maybe a leading - sign) and nothing
671else; second, an integer that is the exponent to use. This can be
672used by Python code that wants finer-grained control on resulting
673string format.
676gmp.reldiff(x,y) or x.reldiff(y): returns the relative difference
677between x and y, a non-negative mpf roughly equal to
680gmpy._fcopy(x) or x._copy(): provide a separate copy of x (only
681relevant for future mutability of mpf..!).
683gmpy.fsign(x) or x.sign(): -1, 0, or 1, depending on whether x is
684negative, zero, or positive.
686gmpy.f2q(x) or x.f2q(): like gmpy.mpq(x), but, like qdiv, will
687return an mpz (instead of, as normally, an mpq), if the mpq's
688denominator would be 1.
690gmpy.fsqrt(x) or x.sqrt(): square-root of non negative number x.
692gmpy.set_fcoform([x]): sets or resets the format with which to
693build the intermediate-string to be used for float->mpf
694conversion.  If x is None, or is absent, then the format is reset,
695and such conversions proceed 'directly'.  If x is a Python int, it
696must be between 1 and 30, and is used as the number of digits in
697the format string '%.<x>e' (for example, set_fcoform(12) will set
698the format string for float-conversion to '%.12e').  Else, x must
699be a Python string usable as:
700    x%f
701to format a float object f in some suitable way.  set_fcoform also
702returns the previous setting of this option, None or a string.
703(See also the paragraph above about the float->mpf conversion
704mechanics, which gives more details about the way in which this
705format string is used by gmpy).
708*Experimental: function gmpy.rand*
710Support for these random number generation functions was removed
711in gmpy2. A new API will be introduced.
713Since gmpy 0.5, the linear congruential random number generator of
714GMP is exposed via gmpy (with some modest added-value
715functionality) through function gmpy.rand.  A couple of options were
716added in 0.6.  This will be refactored into separate functions in
717some future release.
719Its first parameter is a string 'opt' (4-characters, lowercase)
720which determines the exact functionality; it normally has a second
721parameter 'arg' (which is optional for most values of 'opt') and
722may return either None or a significant value (an mpz, except for
723opt='floa', when an mpf is returned).
726        Initialize the random-generator state (this
727        is _implicitly_ called by other options of
728        gmpy.rand, if needed, but should be explicitly
729        called) to ensure 32 bits' randomness per
730        each generation ('throw').  Returns None.
731gmpy.rand('init', arg)
732        ditto, but ensure 'arg' bits of randomness
733        (arg being an int between 1 and 128).  This
734        tweaks the linear congruential parameters
735        according to the number of needed bits (it
736        may be faster to generate just the needed
737        number of 'good' bits).  Returns None.
739        returns the current 'quality of random
740        numbers' (the arg value passed to 'init',
741        with a default of 32), or 0 if random
742        number generation is not initialized yet.
743        [ignores arg, if present]
744gmpy.rand('seed', arg)
745        set the current random-seed to 'arg', an
746        mpz (or coerced to mpz).  Returns None.
748        set the current random-seed 'randomly' in
749        its turn (uses C-level function 'rand()').
750        Returns None.
752        returns the current random-seed (an mpz)
753        so that it can be saved (e.g. for program
754        checkpointing) and later restored via
755        a gmpy.rand('seed', x) call.
756        [ignores arg, if present]
758        returns a uniformly distributed random
759        number in the range 0:2**31 (note that
760        the UPPER end is EXCLUDED) and advances
761        the random-number generation by 1 step.
762	(Basically, returns '31 random bits', if
763	the current quality of the generator is
764	at least 31; for lower-quality generators,
765	upper bits tend to be "better" than less
766	significant ones).
768        returns a uniformly distributed random
769        number in the range 0:arg (note that
770        the UPPER end is EXCLUDED) and advances
771        the random-number generation by 1 step.
772        Value returned is integral (mpz).
774        returns a uniformly distributed random
775        number in the range 0:1 (note that
776        the UPPER end is EXCLUDED), with arg
777        meaningful bits (default, if arg is 0,
778        is current 'quality'), and advances the
779        random-number generation by 1 step.
780        Value returned is floating-point (mpf).
782        returns a uniformly distributed random
783        number in the range 0:1 (note that
784        the UPPER end is EXCLUDED), with as many
785        meaningful bits as the current 'quality',
786        and advances random-number generation by 1
787        step. Value returned is floating-point (mpf).
789        randomly shuffles mutable-sequence 'arg'
790        (normally a list), in a way that ensures
791        all permutations are equally likely.  It
792        advances random-number generation by
793        len(arg)-1 steps.  Returns None.
796*Experimental: the callbacks-facility*
798The "callback" facilities were removed in gmpy 1.10. The documentation
799is left as-is for historical reference.
801Since gmpy 0.8, gmpy exposes 'callback' facilities to help
802client-code customize the handling of what, in pure-gmpy, would be
803error-cases.  This is mostly intended for the use of Pearu
804Peterson's PySymbolic package, and is not currently documented
805(nor tested) in great detail for general use.  You are welcome to
806contact gmpy's maintainer directly (and/or study gmpy's C
807sources:-) if you think you may have use for this facility, or are
808interested in doing something similar in other C modules for
809Python use -- it IS an interesting and reasonably novel approach.
811To summarize: with gmpy.set_callback(name, callable), client-code
812may set a Python callable as a callback for gmpy in a set of
813situations determined by the string 'name'.  For example,
814	gmpy.set_callback('ZD', myfun)
815sets 'myfun' as the callback that gmpy is to use in
816'zero-division' situations.  When gmpy is about to raise a
817ZeroDivision error, it checks if the 'ZD' callback is set; if so,
818then, instead of raising the exception itself, it delegates
819everything to the callback in question, passing it the name of the
820gmpy function involved, the arguments it was called with, and the
821error-string gmpy would use if it did raise the error.  It's up to
822the callback to either raise a ZeroDivision itself, OR return some
823special object to map this situation -- for example, PySymbolic
824may return an 'infinity' object and suppress the error.
826Basically, this works around Python's (excellent!) choice to adopt
827the terminating-model rather than the restartable one for
828exception handling, in a few cases of specific interest to numeric
829computation that's being used in a symbolic setting.
831Most callbacks are module-global, with one specific exception.
832When any gmpy function or method is trying to convert arguments to
833gmpy objects (mpz, mpq, mpf), and a conversion fails, all argument
834objects are examined, looking for a method called '__gmpy__' in
835any of them.
837If one is found, then, rather than raising an error to indicate
838the conversion failure, that method is called as a 'localized
839callback' as above.  This lets other, non-gmpy objects participate
840in gmpy computations (if they're willing to handle all cases
841involving them!): Python does much of this via __coerce__ etc, and
842this localized-callback facility does the rest for named
843module-functions and methods, where normal coercion would not