/doc/gmpydoc.txt

http://gmpy.googlecode.com/ · Plain Text · 845 lines · 691 code · 154 blank · 0 comment · 0 complexity · 1bf1ed5a11f3a0367f2f3f82cecc6f38 MD5 · raw file

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