PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/gmpy2.c

http://gmpy.googlecode.com/
C | 1134 lines | 618 code | 88 blank | 428 comment | 53 complexity | d0637f12d60938be72aed290a315ad65 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, LGPL-2.1
  1. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2. * gmpy2.c *
  3. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  4. * Python interface to the GMP or MPIR, MPFR, and MPC multiple precision *
  5. * libraries. *
  6. * *
  7. * Copyright 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, *
  8. * 2008, 2009 Alex Martelli *
  9. * *
  10. * Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014 Case Van Horsen *
  11. * *
  12. * This file is part of GMPY2. *
  13. * *
  14. * GMPY2 is free software: you can redistribute it and/or modify it under *
  15. * the terms of the GNU Lesser General Public License as published by the *
  16. * Free Software Foundation, either version 3 of the License, or (at your *
  17. * option) any later version. *
  18. * *
  19. * GMPY2 is distributed in the hope that it will be useful, but WITHOUT *
  20. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
  21. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public *
  22. * License for more details. *
  23. * *
  24. * You should have received a copy of the GNU Lesser General Public *
  25. * License along with GMPY2; if not, see <http://www.gnu.org/licenses/> *
  26. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  27. /* Todo list
  28. * ---------
  29. * Add all MPFR and MPC functions as context methods.
  30. * All MPFR and MPC functions need to set exponent range on entry. The
  31. * current approach where only set_context() and context.__enter__ set
  32. * the exponent range fails for context methods.
  33. * Should a read-only (or template) context prevent the setting of
  34. * exception flags?
  35. * Add context option to control the result of integer division:
  36. * integer (mpz), exact (mpq), or true (mpfr).
  37. * Add modular arithmetic functions.
  38. * Implement Chinese Remainder Theorem.
  39. * Update PRP code.
  40. */
  41. /*
  42. * originally written for GMP-2.0 (by AMK...?)
  43. * Rewritten by Niels Möller, May 1996
  44. *
  45. * Version for GMP-4, Python 2.X, with support for MSVC++6,
  46. * addition of mpf's, &c: Alex Martelli (now aleaxit@gmail.com, Nov 2000).
  47. * cleanups & reorgs leading to 1.0: Alex Martelli (until Aug 2003)
  48. * further cleanups and bugfixes leading to 1.01, Alex Martelli (Nov 2005)
  49. * minor bugfixes+new decimal (&c) support to 1.02, Alex Martelli (Feb 2006)
  50. * various bugfixes for 64-bit platforms, 1.03, aleaxit and casevh (Jun 2008)
  51. * rich comparisons, 1.04, aleaxit and casevh (Jan 2009)
  52. * support for Python 3.x, 1.10, casevh (Oct 2009)
  53. *
  54. * Some hacks by Gustavo Niemeyer <niemeyer@conectiva.com>.
  55. *
  56. * 0.1, pre-alpha; date: 2000-11-06 first placed on sourceforge
  57. *
  58. * 0.2, still pre-alpha: 2000-11-15: bugfixes re formatting (tx, Peanu!)
  59. * no tags on oct() and hex() of mpz's
  60. * insert 'tagoff' in options (gmpy.mpz() vs mpz() in repr) (for Peanu!)
  61. * speedups for _nonzero & _cmp (tx, Peanu!)
  62. * slight speedup (7/8%?) for excess reallocs 4<->8 bytes (Peanu's help!)
  63. * added copy/fcopy; bin; fib; remove
  64. *
  65. * 0.3, still pre-alpha, but...:
  66. * performance tweaks via mpz-caching & fixed-constants
  67. * added get/set functions for zcache, zco min/max
  68. * added get-only function for versions (of gmp, and of gmpy)
  69. * removed all 'traces' of mutability (to be re-done... much later!)
  70. * cleaned up all of the mpz_cmp_ui(X,0) to mpz_sgn(X)
  71. * cleaned up Py_BuildValue usage (N vs O, explicit-() for tuples)
  72. * added numdigits, lowbits, root, next_prime, invert, popcount,
  73. * hamdist, scan0, scan1
  74. * renamed bin to bincoef
  75. *
  76. * 0.4:
  77. * split gmpy.c/gmpy.h introducing C-API interface (Pearu's suggestion)
  78. * cleanup some casts using Pearu's new macros
  79. * further cache-tweaks at Pearu's suggestion (macros introduced)
  80. * added sign (Pearu's request), getbit, setbit
  81. * added docstrings
  82. * renamed copy functions to start with _ ('internal, private')
  83. * added .comb as a synonym of .bincoef
  84. *
  85. * 0.5:
  86. * added jacobi, legendre, kronecker
  87. * added random-number generation, seed set/save, shuffling
  88. * added mpq (at last!-)
  89. *
  90. * 0.6: (lots of good ideas from Pearu once more!-):
  91. * fixed silly bugs in kronecker and mpq_abs
  92. * gmpy-level workaround for scan0/scan1 bugs (?) in GMP 3.1.1
  93. * added qdiv; anynum->mpq substituted for all such conversions
  94. * (also anynum->mpz and anynum->mpf by analogy, with care!)
  95. * added global.fcoform for optional use of intermediate string in
  96. * float2mpf (used for any float->mpf conversion)
  97. * added set_fcoform function for global.fcoform access
  98. * general cleanup of sources; added alloca for MSVC++;
  99. * many sundry minor bugfixes & uniformization;
  100. * a little useful refactoring (more would be good...)
  101. * added caching of mpq objects
  102. * power for mpq
  103. * Stern-Brocot algorithm for mpf->mpq (also exposed as f2q)
  104. * also used for float->mpq
  105. * with stricter tracking of mpf's requested-precision
  106. * added getrprec method to mpf, getrprec module-function
  107. * exposed ceil, floor and trunc methods/functions for mpf's
  108. * changed a couple exceptions from Value to ZeroDivision
  109. * added 'qual' and 'floa' options to gmpy.rand
  110. *
  111. * 0.7: (good feedback from Keith Briggs, some advice from Tim Peters
  112. * and Fred Lundh -- thanks all!):
  113. * fixed bug of '"%d" where "%ld" was meant' in many places
  114. * and other sundry minor warnings given by gcc
  115. * fixed hash (delegating to Python) so mp[nqz](x) will
  116. * produce the same value as hash(x) for any Python number x
  117. * workaround for GMP 3.1.1 bug, mpz_root wrongly returning
  118. * 'exact' for non-exact root if dest==source, which stopped
  119. * needed value-error for inexact mpq**mpq operations
  120. * determined correct 'actual precision' of floats
  121. * explicitly stored precision with binary-form mpf's
  122. * extended explicit-bits request to all ->mpf operations
  123. * (good in itself, plus, preparing for future MPFR)
  124. * removed the limitation of no binary-form for <0 mpz
  125. * introduced macros to parse args, for conciseness
  126. *
  127. * 0.8: (again, requests & suggestions by great Pearu!)
  128. * raise test coverage 72.5% -> 90.0%
  129. * introduced callbacks (not documented/tested for now;
  130. * Pearu will test/support/document in PySymbolic)
  131. * some errors went undiagnosed, caused crash: now fixed
  132. * workaround for GMP bug(?s?) in mpz_fits_... (?)
  133. * added exposure of mpf_ sqrt and pow_ui
  134. *
  135. * 0.9: (ditto)
  136. * change ValueError to OverflowError for 'too-large' errors
  137. * fix bug in mpq_pow (negative base, exp. with odd denominator)
  138. * (fix now corrected -- _even_ denominator is the error!)
  139. * fixed gcc warnings reported by K. Briggs
  140. *
  141. * 0.9b:
  142. * support GMP 4 (but added no GMP4-only functionality yet)
  143. *
  144. * 0.9c:
  145. * updated tests to 0.9, better coverage
  146. *
  147. * 1.0:
  148. * minor cleanups, ensure support for Python 2.3
  149. * fixed misdiagnosis of some argument counts in macro
  150. * SELF_ONE_ARG_CONVERTED (tx to Paul Rubin!)
  151. *
  152. * 1.01:
  153. * cleanups, ensure support for Python 2.4.1 on MacOSX 10.4/XCode 2.1
  154. * as well as Python 2.2 and 2.3 (on MacOSX and Linux)
  155. * fixed memory leak on divm (thanks to mensanator@aol.com)
  156. * fixed bug on mpq('123') [[str2mpq on string w/o a slash]]
  157. * added floordiv and truediv operators, and tests for them
  158. * NOT tested on GMP 3 (have none left around...), ONLY on GMP 4.*
  159. *
  160. * 1.02:
  161. * fix warning in comparison of mpq's
  162. * added support of mpq('12.34') [[string w/o a slash, but with a dot]]
  163. * fixes for 64-bit build (thanks to a patch by dmcooke)
  164. * added experimental support for decimal.Decimal (and user-coded types)
  165. * via wider use of special conversion methods (if present) and their
  166. * sly insertion on-the-fly into the decimal.Decimal class (!)
  167. * two bugfixes, thanks to Simon Burton
  168. * Brought back into C89 compliance (thanks to Chip Turner), had
  169. * drifted to C99 (declarations in the middle of the code).
  170. * Python 2.5 support (Py_ssize_t, __index__) thanks to Chip Turner
  171. * Pushed coverage to 93.3% (missing only "sanity check" level error
  172. * tests [mostly for out-of-memory conditions], output to stderr
  173. * conditioned by global.debug, & a couple of very obscure cases)
  174. *
  175. * 1.03:
  176. * Fixed the bug that caused crashes on gmpy.mpf(float('inf')) and
  177. * other such conversions, implicit and explicit
  178. * Fixed a bug in get_zconst's prototype affecting 64-bit machines,
  179. * thanks to Gary Bunting
  180. * Fixed a bug in hashing on 64-bit systems. hash(long) now equals
  181. * hash(mpz) for large values. (casevh)
  182. * Changed int() to return a long value instead of OverFlowError.
  183. * Complies with PEP 237. (casevh)
  184. * Added support in setup.py for darwinports/macports build of GMP
  185. * on MacOSX. (aleaxit)
  186. *
  187. * 1.04:
  188. * Avoid GMP/mingw32 bug when converting very small floats to mpz.
  189. * (casevh)
  190. * Significant performance improvement for long->mpz and mpz->long.
  191. * (casevh)
  192. * Added "rich comparisons" to mpz, mpq and mpf types (aleaxit)
  193. * Added additional tests (casevh, aleaxit)
  194. * Fixed bug when converting very large mpz to str (casevh)
  195. * Faster conversion from mpz->binary and binary->mpz (casevh)
  196. * Added support for pickling (casevh)
  197. * Added divexact (casevh)
  198. * Fixed mpf comparisons by rounding mpf results when GMP returns
  199. * a longer result. Added fround() (casevh)
  200. * Added bit_length (Thanks Mario Pernici)
  201. * Added helper functions for mpmath (casevh)
  202. * Faster conversion from mpq->binary and binary->mpq (casevh)
  203. * Recognize MPIR, mpir_version() (casevh)
  204. *
  205. * 1.10:
  206. * Remove dependancy on pymemcompat.h (casevh)
  207. * Remove callback (casevh)
  208. * Added support for -DMPIR to include MPIR instead of GMP (casevh)
  209. * Major code revisions to add support for Python 3.x (casevh)
  210. * Fixed bug in binary() and qbinary() (casevh)
  211. * Fixed bug in rich comparisons (casevh)
  212. * Added % and divmod support to mpq and mpf (casevh)
  213. * Changed memory allocation functions to use PyMem (casevh)
  214. * Removed small number interning (casevh)
  215. * Added tdivmod, cdivmod, and fdivmod (casevh)
  216. * Added more helper functions for mpmath (casevh)
  217. * Faster mpz<>PyLong conversion (casevh)
  218. * Faster hash(mpz) (casevh)
  219. *
  220. * 1.11:
  221. * Recognize True/False (bug in 1.10) (casevh)
  222. * Optimize argument handling (casevh)
  223. * Added caching for mpz (casevh)
  224. *
  225. ************************************************************************
  226. *
  227. * 2.0.0 alpha and b1:
  228. * Added caching for mpq (casevh)
  229. * Added rootrem, fib2, lucas, lucas2 (casevh)
  230. * Removed mpf.setprec(), use mpf.round() (casevh)
  231. * Fix test compatibility with Python 3.1.2 and 3.2 (casevh)
  232. * Support changed hash function in Python 3.2 (casevh)
  233. * Added is_even, is_odd (casevh)
  234. * Rename to gmpy2 to allow backwards incompatible changes (casevh)
  235. * Remove old random number functions, to be replaced later (casevh)
  236. * Add caching of the calculated hash value (casevh)
  237. * Add xmpz (mutable mpz) type (casevh)
  238. * Fix mpq formatting issue (casevh)
  239. * Add read/write bit access using slices to xmpz (casevh)
  240. * Add read-only bit access using slices to mpz (casevh)
  241. * Add pack()/unpack() methods (casevh)
  242. * Remove tagoff option (casevh)
  243. * Add support for MPFR (casevh)
  244. * Debug messages only available if compiled with -DDEBUG (casevh)
  245. * Removed fcoform float conversion modifier (casevh)
  246. * Add support for MPC (casevh)
  247. * Renamed 'mpf' to 'mpfr' to reflect use of MPFR (casevh)
  248. * Added context manager (casevh)
  249. * Allow building with just GMP/MPIR if MPFR not available (casevh)
  250. * Allow building with GMP/MPIR and MPFR if MPC not available (casevh)
  251. * Removed most instance methods in favor of gmpy2.method (casevh)
  252. * Added __ceil__, __floor__, and __trunc__ methods (casevh)
  253. * Removed gmpy2.pow to avoid conflicts (casevh)
  254. * Removed gmpy2._copy and added xmpz.copy (casevh)
  255. * Added support for __format__ (casevh)
  256. * Completed support for MPC (casevh)
  257. * Added as_integer_ratio, as_mantissa_exp, as_simple_fraction (casevh)
  258. * Update rich_compare (casevh)
  259. * Require MPFR 3.1.0+ to get divby0 support (casevh)
  260. * Added fsum(), degrees(), radians() (casevh)
  261. * Renamed context() -> local_context(), new_context() -> context() (casevh)
  262. * Added get_context() (casevh)
  263. * Added random number generation support (casevh)
  264. * Changed license to LGPL 3+ (casevh)
  265. * Added lucasu, lucasu_mod, lucasv, and lucasv_mod (casevh)
  266. * (Based on code contributed by David Cleaver.)
  267. * Added probable-prime tests (casevh)
  268. * (Based on code contributed by David Cleaver.)
  269. * Added to_binary()/from_binary (casevh)
  270. * Renamed numdigits() to num_digits() (casevh)
  271. * Added keyword precision to constants (casevh)
  272. * Added addmul() and submul() (casevh)
  273. * Added __round__(), round2(), round_away() for mpfr (casevh)
  274. * round() is no longer a module level function (casevh)
  275. * pow() is no longer a module level function (casevh)
  276. * Renamed module functions min()/max() to min2()/max2() (casevh)
  277. * No longer conflicts with builtin min() and max()
  278. * Removed set_debug() and related functionality (casevh)
  279. * Released as 2.0.0b1
  280. *
  281. * 2.0.0b2
  282. * Allow xmpz slice assignment to increase length of xmpz instance by
  283. * specifying a value for stop (casevh)
  284. * Fixed ref-count bug in several is_xxx_prp tests (casevh)
  285. * Added iter_bits, iter_clear, iter_set methods to xmpz (casevh)
  286. * Added powmod() for easy access to three argument pow() (casevh)
  287. * Removed addmul() and submul() since they are slower than (casevh)
  288. * just using Python code
  289. * Bug fix in gcd_ext when both arguments are not mpz (casevh)
  290. * Added ieee() to create contexts for 32, 64, or 128 bit floats (casevh)
  291. * Bug fix in context() not setting emax/emin correctly if they (casevh)
  292. * had been changed earlier
  293. * Contexts can be directly used in with statement without (casevh)
  294. * requiring set_context()/local_context() sequence
  295. * local_context() now accepts an optional context (casevh)
  296. *
  297. * 2.0.0b3
  298. * mp_version(), mpc_version(), and mpfr_version() shouldn't (casevh)
  299. * return Unicode on Python 2.x
  300. * Fix warnings when shifting 32-bit integer by 32 bits (casevh)
  301. * Faster conversion of Fraction to gmpy2 types (casevh)
  302. * Fix conversion with Decimal, especially on Python 3.3 (casevh)
  303. * Consistently return OverflowError when converting "inf" (casevh)
  304. * Fix mpz.__format__() with # code (casevh)
  305. * Add is_infinite(), deprecate is_inf() (casevh)
  306. * Add is_finite(), deprecate is_number() (casevh)
  307. * Fixed issues with mpc() and various is_XXX() functions (casevh)
  308. * Fixed error handling with mpc(); mpc(1,"nan") is properly (casevh)
  309. * handled
  310. * Added caching for mpc objects; faster when real and (casevh)
  311. * imaginary precisions are equal
  312. * Add optimal path for mpfr/mpc + - * / when both operands (casevh)
  313. * have the same type
  314. * Fix mpfr + float segmentation fault (casevh)
  315. *
  316. * 2.0.0b4
  317. * Add __ceil__, __floor__, __trunc__, __round__ to mpz & mpq (casevh)
  318. * Add __complex__ to mpc (casevh)
  319. * round(mpfr) now correctly returns an mpz (casevh)
  320. * Add mpz.denominator and mpz.numerator (casevh)
  321. * mpz() returns mpz(0); also xmpz, mpq, mpfr, and mpc (casevh)
  322. * Fix bug when comparing mpz to mpq (with mpz on left) (casevh)
  323. * Add __sizeof__ (casevh)
  324. *
  325. * 2.0.0
  326. * Fix segfault in _mpmath_normalize if rnd not specified (casevh)
  327. * Improved setup.py (casevh)
  328. * Fix issues encountered when compiled without MPFR support (casevh)
  329. * Conversion of too large an mpz to float now raises OverflowError (casevh)
  330. * Renamed module functions min2()/max2() to minnum()/maxnum() (casevh)
  331. * Added copy() method to contexts (casevh)
  332. * get_context() no longer supports keyword arguments (casevh)
  333. *
  334. ************************************************************************
  335. *
  336. * 2.1.0
  337. * Improvements to setup.py (casevh)
  338. * Add thread-safe contexts (casevh)
  339. * MPFR and MPC are now required (casevh)
  340. * Invalid Operation exception now raised for addition, etc. (casevh)
  341. * inverse() now raises exception if inverse does not exist (casevh)
  342. * Add context methods (casevh)
  343. * Major code refactoring required to properly support thread-safe
  344. * contexts. (casevh)
  345. * __str__ and __repr__ no longer append "L" on Python 2 (casevh)
  346. * mpq(mpfr) now returns the exact result (casevh)
  347. * Fix repr(mpc) for precision >325 bits.
  348. *
  349. ************************************************************************
  350. *
  351. * Discussion on sizes of C integer types.
  352. *
  353. * GMP, MPIR, MPFR, and MPC use typedef to create integer objects with
  354. * different sizes. It can become confusing to map the different types
  355. * onto the standard C types used by Python's C API. Below are external
  356. * types and how they map to C types. The assumptions are verified when
  357. * the module is initialized.
  358. *
  359. * mp_limb_t: This is usually an 'unsigned long' but is an 'unsigned
  360. * long long' on MPIR/64-bit Windows.
  361. *
  362. * mp_bitcnt_t: This is usually an 'unsigned long' but is an 'unsigned
  363. * long long' on MPIR/64-bit Windows. 'size_t' is the best match.
  364. *
  365. * mp_size_t: This is a 'long'.
  366. *
  367. * mpfr_rnd_t: This is an 'int'.
  368. *
  369. * mpfr_prec_t: This is a 'long'.
  370. *
  371. * mpfr_sign_t: This is an 'int'.
  372. *
  373. * mpfr_exp_t: This is currently the same as mp_exp_t but will change
  374. * to a signed 64-bit integer in the future.
  375. *
  376. * mpc_rnd_t: This is an 'int'.
  377. *
  378. * mpc_prec_t: See mpfr_exp_t.
  379. *
  380. ************************************************************************
  381. */
  382. #define PY_SSIZE_T_CLEAN
  383. #include "Python.h"
  384. /*
  385. * we do have a dependence on Python's internals, specifically:
  386. * how Python "long int"s are internally represented.
  387. */
  388. #include "longintrepr.h"
  389. #include <assert.h>
  390. #include <math.h>
  391. #include <float.h>
  392. #include <stdio.h>
  393. #include <ctype.h>
  394. #include "gmpy2.h"
  395. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  396. * Global data declarations begin here. *
  397. * NOTE: Because of these global declarations, GMPY2 is not thread-safe! *
  398. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  399. /* The following global strings are used by gmpy_misc.c. */
  400. char gmpy_version[] = "2.1.0a0";
  401. char _gmpy_cvs[] = "$Id: gmpy2.c 1028 2015-02-11 06:16:56Z casevh $";
  402. char gmpy_license[] = "\
  403. The GMPY2 source code is licensed under LGPL 3 or later. The supported \
  404. versions of the GMP/MPIR, MPFR, and MPC libraries are also licensed under \
  405. LGPL 3 or later.";
  406. /* The following global structures are used by gmpy_cache.c.
  407. */
  408. static struct gmpy_global {
  409. int cache_size; /* size of cache, for all caches */
  410. int cache_obsize; /* maximum size of the objects that are cached */
  411. } global = {
  412. 100, /* cache_size */
  413. 128, /* cache_obsize */
  414. };
  415. static mpz_t* zcache;
  416. static int in_zcache;
  417. static MPZ_Object **gmpympzcache;
  418. static int in_gmpympzcache;
  419. static XMPZ_Object **gmpyxmpzcache;
  420. static int in_gmpyxmpzcache;
  421. static MPQ_Object **gmpympqcache;
  422. static int in_gmpympqcache;
  423. static MPFR_Object **gmpympfrcache;
  424. static int in_gmpympfrcache;
  425. static MPC_Object **gmpympccache;
  426. static int in_gmpympccache;
  427. /* Support for context manager. */
  428. #ifdef WITHOUT_THREADS
  429. /* Use a module-level context. */
  430. static CTXT_Object *module_context = NULL;
  431. #else
  432. /* Key for thread state dictionary */
  433. static PyObject *tls_context_key = NULL;
  434. /* Invariant: NULL or the most recently accessed thread local context */
  435. static CTXT_Object *cached_context = NULL;
  436. #endif
  437. /* Define gmpy2 specific errors for mpfr and mpc data types. No change will
  438. * be made the exceptions raised by mpz, xmpz, and mpq.
  439. */
  440. static PyObject *GMPyExc_GmpyError = NULL;
  441. static PyObject *GMPyExc_DivZero = NULL;
  442. static PyObject *GMPyExc_Inexact = NULL;
  443. static PyObject *GMPyExc_Invalid = NULL;
  444. static PyObject *GMPyExc_Overflow = NULL;
  445. static PyObject *GMPyExc_Underflow = NULL;
  446. static PyObject *GMPyExc_Erange = NULL;
  447. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  448. * End of global data declarations. *
  449. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  450. /* The code for object creation, deletion, and caching is in gmpy_cache.c. */
  451. #include "gmpy2_cache.c"
  452. /* Miscellaneous helper functions and simple methods are in gmpy_misc.c. */
  453. #include "gmpy2_misc.c"
  454. /* Include fast mpz to/from PyLong conversion from sage. */
  455. #include "mpz_pylong.c"
  456. /* Support for conversion to/from binary representation. */
  457. #include "gmpy2_binary.c"
  458. /* Support for conversions to/from numeric types. */
  459. #include "gmpy2_convert.c"
  460. #include "gmpy2_convert_utils.c"
  461. #include "gmpy2_convert_gmp.c"
  462. #include "gmpy2_convert_mpfr.c"
  463. #include "gmpy2_convert_mpc.c"
  464. /* Support for random numbers. */
  465. #include "gmpy2_random.c"
  466. /* Support for Lucas sequences. */
  467. #include "gmpy_mpz_lucas.c"
  468. /* Support for probable-prime tests. */
  469. #include "gmpy_mpz_prp.c"
  470. /* Include helper functions for mpmath. */
  471. #include "gmpy2_mpmath.c"
  472. #include "gmpy2_mpz_divmod.c"
  473. #include "gmpy2_mpz_divmod2exp.c"
  474. #include "gmpy2_mpz_pack.c"
  475. #include "gmpy2_mpz_bitops.c"
  476. #include "gmpy2_mpz_inplace.c"
  477. #include "gmpy2_xmpz_inplace.c"
  478. /* Begin includes of refactored code. */
  479. #include "gmpy2_abs.c"
  480. #include "gmpy2_add.c"
  481. #include "gmpy2_divmod.c"
  482. #include "gmpy2_floordiv.c"
  483. #include "gmpy2_minus.c"
  484. #include "gmpy2_mod.c"
  485. #include "gmpy2_mul.c"
  486. #include "gmpy2_plus.c"
  487. #include "gmpy2_pow.c"
  488. #include "gmpy2_sub.c"
  489. #include "gmpy2_truediv.c"
  490. #include "gmpy2_math.c"
  491. #include "gmpy2_const.c"
  492. #include "gmpy2_square.c"
  493. #include "gmpy2_format.c"
  494. #include "gmpy2_hash.c"
  495. #include "gmpy2_fused.c"
  496. #include "gmpy2_muldiv_2exp.c"
  497. #include "gmpy2_predicate.c"
  498. #include "gmpy2_sign.c"
  499. #include "gmpy2_richcompare.c"
  500. #include "gmpy2_mpc_misc.c"
  501. #include "gmpy2_mpfr_misc.c"
  502. #include "gmpy2_mpq_misc.c"
  503. #include "gmpy2_mpz_misc.c"
  504. #include "gmpy2_xmpz_misc.c"
  505. /* Include gmpy_context last to avoid adding doc names to .h files. */
  506. #include "gmpy2_mpz.c"
  507. #include "gmpy2_xmpz.c"
  508. #include "gmpy2_mpq.c"
  509. #include "gmpy2_mpfr.c"
  510. #include "gmpy2_mpc.c"
  511. #include "gmpy2_context.c"
  512. static PyMethodDef Pygmpy_methods [] =
  513. {
  514. { "_cvsid", GMPy_get_cvsid, METH_NOARGS, GMPy_doc_cvsid },
  515. { "_printf", GMPy_printf, METH_VARARGS, GMPy_doc_function_printf },
  516. { "add", GMPy_Context_Add, METH_VARARGS, GMPy_doc_function_add },
  517. { "bit_clear", GMPy_MPZ_bit_clear_function, METH_VARARGS, doc_bit_clear_function },
  518. { "bit_flip", GMPy_MPZ_bit_flip_function, METH_VARARGS, doc_bit_flip_function },
  519. { "bit_length", GMPy_MPZ_bit_length_function, METH_O, doc_bit_length_function },
  520. { "bit_mask", GMPy_MPZ_bit_mask, METH_O, doc_bit_mask },
  521. { "bit_scan0", GMPy_MPZ_bit_scan0_function, METH_VARARGS, doc_bit_scan0_function },
  522. { "bit_scan1", GMPy_MPZ_bit_scan1_function, METH_VARARGS, doc_bit_scan1_function },
  523. { "bit_set", GMPy_MPZ_bit_set_function, METH_VARARGS, doc_bit_set_function },
  524. { "bit_test", GMPy_MPZ_bit_test_function, METH_VARARGS, doc_bit_test_function },
  525. { "bincoef", GMPy_MPZ_Function_Bincoef, METH_VARARGS, GMPy_doc_mpz_function_bincoef },
  526. { "comb", GMPy_MPZ_Function_Bincoef, METH_VARARGS, GMPy_doc_mpz_function_comb },
  527. { "c_div", GMPy_MPZ_c_div, METH_VARARGS, doc_c_div },
  528. { "c_div_2exp", GMPy_MPZ_c_div_2exp, METH_VARARGS, doc_c_div_2exp },
  529. { "c_divmod", GMPy_MPZ_c_divmod, METH_VARARGS, doc_c_divmod },
  530. { "c_divmod_2exp", GMPy_MPZ_c_divmod_2exp, METH_VARARGS, doc_c_divmod_2exp },
  531. { "c_mod", GMPy_MPZ_c_mod, METH_VARARGS, doc_c_mod },
  532. { "c_mod_2exp", GMPy_MPZ_c_mod_2exp, METH_VARARGS, doc_c_mod_2exp },
  533. { "denom", GMPy_MPQ_Function_Denom, METH_O, GMPy_doc_mpq_function_denom },
  534. { "digits", GMPy_Context_Digits, METH_VARARGS, GMPy_doc_context_digits },
  535. { "div", GMPy_Context_TrueDiv, METH_VARARGS, GMPy_doc_truediv },
  536. { "divexact", GMPy_MPZ_Function_Divexact, METH_VARARGS, GMPy_doc_mpz_function_divexact },
  537. { "divm", GMPy_MPZ_Function_Divm, METH_VARARGS, GMPy_doc_mpz_function_divm },
  538. { "div_mod", GMPy_Context_DivMod, METH_VARARGS, GMPy_doc_divmod },
  539. { "double_fac", GMPy_MPZ_Function_DoubleFac, METH_O, GMPy_doc_mpz_function_double_fac },
  540. { "fac", GMPy_MPZ_Function_Fac, METH_O, GMPy_doc_mpz_function_fac },
  541. { "fib", GMPy_MPZ_Function_Fib, METH_O, GMPy_doc_mpz_function_fib },
  542. { "fib2", GMPy_MPZ_Function_Fib2, METH_O, GMPy_doc_mpz_function_fib2 },
  543. { "floor_div", GMPy_Context_FloorDiv, METH_VARARGS, GMPy_doc_floordiv },
  544. { "from_binary", GMPy_MPANY_From_Binary, METH_O, doc_from_binary },
  545. { "f_div", GMPy_MPZ_f_div, METH_VARARGS, doc_f_div },
  546. { "f_div_2exp", GMPy_MPZ_f_div_2exp, METH_VARARGS, doc_f_div_2exp },
  547. { "f_divmod", GMPy_MPZ_f_divmod, METH_VARARGS, doc_f_divmod },
  548. { "f_divmod_2exp", GMPy_MPZ_f_divmod_2exp, METH_VARARGS, doc_f_divmod_2exp },
  549. { "f_mod", GMPy_MPZ_f_mod, METH_VARARGS, doc_f_mod },
  550. { "f_mod_2exp", GMPy_MPZ_f_mod_2exp, METH_VARARGS, doc_f_mod_2exp },
  551. { "gcd", GMPy_MPZ_Function_GCD, METH_VARARGS, GMPy_doc_mpz_function_gcd },
  552. { "gcdext", GMPy_MPZ_Function_GCDext, METH_VARARGS, GMPy_doc_mpz_function_gcdext },
  553. { "get_cache", GMPy_get_cache, METH_NOARGS, GMPy_doc_get_cache },
  554. { "hamdist", GMPy_MPZ_hamdist, METH_VARARGS, doc_hamdist },
  555. { "invert", GMPy_MPZ_Function_Invert, METH_VARARGS, GMPy_doc_mpz_function_invert },
  556. { "iroot", GMPy_MPZ_Function_Iroot, METH_VARARGS, GMPy_doc_mpz_function_iroot },
  557. { "iroot_rem", GMPy_MPZ_Function_IrootRem, METH_VARARGS, GMPy_doc_mpz_function_iroot_rem },
  558. { "isqrt", GMPy_MPZ_Function_Isqrt, METH_O, GMPy_doc_mpz_function_isqrt },
  559. { "isqrt_rem", GMPy_MPZ_Function_IsqrtRem, METH_O, GMPy_doc_mpz_function_isqrt_rem },
  560. { "is_bpsw_prp", GMPY_mpz_is_bpsw_prp, METH_VARARGS, doc_mpz_is_bpsw_prp },
  561. { "is_congruent", GMPy_MPZ_Function_IsCongruent, METH_VARARGS, GMPy_doc_mpz_function_is_congruent },
  562. { "is_divisible", GMPy_MPZ_Function_IsDivisible, METH_VARARGS, GMPy_doc_mpz_function_is_divisible },
  563. { "is_even", GMPy_MPZ_Function_IsEven, METH_O, GMPy_doc_mpz_function_is_even },
  564. { "is_euler_prp", GMPY_mpz_is_euler_prp, METH_VARARGS, doc_mpz_is_euler_prp },
  565. { "is_extra_strong_lucas_prp", GMPY_mpz_is_extrastronglucas_prp, METH_VARARGS, doc_mpz_is_extrastronglucas_prp },
  566. { "is_fermat_prp", GMPY_mpz_is_fermat_prp, METH_VARARGS, doc_mpz_is_fermat_prp },
  567. { "is_fibonacci_prp", GMPY_mpz_is_fibonacci_prp, METH_VARARGS, doc_mpz_is_fibonacci_prp },
  568. { "is_lucas_prp", GMPY_mpz_is_lucas_prp, METH_VARARGS, doc_mpz_is_lucas_prp },
  569. { "is_odd", GMPy_MPZ_Function_IsOdd, METH_O, GMPy_doc_mpz_function_is_odd },
  570. { "is_power", GMPy_MPZ_Function_IsPower, METH_O, GMPy_doc_mpz_function_is_power },
  571. { "is_prime", GMPy_MPZ_Function_IsPrime, METH_VARARGS, GMPy_doc_mpz_function_is_prime },
  572. { "is_selfridge_prp", GMPY_mpz_is_selfridge_prp, METH_VARARGS, doc_mpz_is_selfridge_prp },
  573. { "is_square", GMPy_MPZ_Function_IsSquare, METH_O, GMPy_doc_mpz_function_is_square },
  574. { "is_strong_prp", GMPY_mpz_is_strong_prp, METH_VARARGS, doc_mpz_is_strong_prp },
  575. { "is_strong_bpsw_prp", GMPY_mpz_is_strongbpsw_prp, METH_VARARGS, doc_mpz_is_strongbpsw_prp },
  576. { "is_strong_lucas_prp", GMPY_mpz_is_stronglucas_prp, METH_VARARGS, doc_mpz_is_stronglucas_prp },
  577. { "is_strong_selfridge_prp", GMPY_mpz_is_strongselfridge_prp, METH_VARARGS, doc_mpz_is_strongselfridge_prp },
  578. { "jacobi", GMPy_MPZ_Function_Jacobi, METH_VARARGS, GMPy_doc_mpz_function_jacobi },
  579. { "kronecker", GMPy_MPZ_Function_Kronecker, METH_VARARGS, GMPy_doc_mpz_function_kronecker },
  580. { "lcm", GMPy_MPZ_Function_LCM, METH_VARARGS, GMPy_doc_mpz_function_lcm },
  581. { "legendre", GMPy_MPZ_Function_Legendre, METH_VARARGS, GMPy_doc_mpz_function_legendre },
  582. { "license", GMPy_get_license, METH_NOARGS, GMPy_doc_license },
  583. { "lucas", GMPy_MPZ_Function_Lucas, METH_O, GMPy_doc_mpz_function_lucas },
  584. { "lucasu", GMPY_mpz_lucasu, METH_VARARGS, doc_mpz_lucasu },
  585. { "lucasu_mod", GMPY_mpz_lucasu_mod, METH_VARARGS, doc_mpz_lucasu_mod },
  586. { "lucasv", GMPY_mpz_lucasv, METH_VARARGS, doc_mpz_lucasv },
  587. { "lucasv_mod", GMPY_mpz_lucasv_mod, METH_VARARGS, doc_mpz_lucasv_mod },
  588. { "lucas2", GMPy_MPZ_Function_Lucas2, METH_O, GMPy_doc_mpz_function_lucas2 },
  589. { "mod", GMPy_Context_Mod, METH_VARARGS, GMPy_doc_mod },
  590. { "mp_version", GMPy_get_mp_version, METH_NOARGS, GMPy_doc_mp_version },
  591. { "mp_limbsize", GMPy_get_mp_limbsize, METH_NOARGS, GMPy_doc_mp_limbsize },
  592. { "mpc_version", GMPy_get_mpc_version, METH_NOARGS, GMPy_doc_mpc_version },
  593. { "mpfr_version", GMPy_get_mpfr_version, METH_NOARGS, GMPy_doc_mpfr_version },
  594. { "mpq", (PyCFunction)GMPy_MPQ_Factory, METH_VARARGS | METH_KEYWORDS, GMPy_doc_mpq_factory },
  595. { "mpq_from_old_binary", GMPy_MPQ_From_Old_Binary, METH_O, doc_mpq_from_old_binary },
  596. { "mpz", (PyCFunction)GMPy_MPZ_Factory, METH_VARARGS | METH_KEYWORDS, GMPy_doc_mpz_factory },
  597. { "mpz_from_old_binary", GMPy_MPZ_From_Old_Binary, METH_O, doc_mpz_from_old_binary },
  598. { "mpz_random", GMPy_MPZ_random_Function, METH_VARARGS, GMPy_doc_mpz_random_function },
  599. { "mpz_rrandomb", GMPy_MPZ_rrandomb_Function, METH_VARARGS, GMPy_doc_mpz_rrandomb_function },
  600. { "mpz_urandomb", GMPy_MPZ_urandomb_Function, METH_VARARGS, GMPy_doc_mpz_urandomb_function },
  601. { "mul", GMPy_Context_Mul, METH_VARARGS, GMPy_doc_function_mul },
  602. { "multi_fac", GMPy_MPZ_Function_MultiFac, METH_VARARGS, GMPy_doc_mpz_function_multi_fac },
  603. { "next_prime", GMPy_MPZ_Function_NextPrime, METH_O, GMPy_doc_mpz_function_next_prime },
  604. { "numer", GMPy_MPQ_Function_Numer, METH_O, GMPy_doc_mpq_function_numer },
  605. { "num_digits", GMPy_MPZ_Function_NumDigits, METH_VARARGS, GMPy_doc_mpz_function_num_digits },
  606. { "pack", GMPy_MPZ_pack, METH_VARARGS, doc_pack },
  607. { "popcount", GMPy_MPZ_popcount, METH_O, doc_popcount },
  608. { "powmod", GMPy_Integer_PowMod, METH_VARARGS, GMPy_doc_integer_powmod },
  609. { "primorial", GMPy_MPZ_Function_Primorial, METH_O, GMPy_doc_mpz_function_primorial },
  610. { "qdiv", GMPy_MPQ_Function_Qdiv, METH_VARARGS, GMPy_doc_function_qdiv },
  611. { "remove", GMPy_MPZ_Function_Remove, METH_VARARGS, GMPy_doc_mpz_function_remove },
  612. { "random_state", GMPy_RandomState_Factory, METH_VARARGS, GMPy_doc_random_state_factory },
  613. { "set_cache", GMPy_set_cache, METH_VARARGS, GMPy_doc_set_cache },
  614. { "sign", GMPy_Context_Sign, METH_O, GMPy_doc_function_sign },
  615. { "square", GMPy_Context_Square, METH_O, GMPy_doc_function_square },
  616. { "sub", GMPy_Context_Sub, METH_VARARGS, GMPy_doc_sub },
  617. { "to_binary", GMPy_MPANY_To_Binary, METH_O, doc_to_binary },
  618. { "t_div", GMPy_MPZ_t_div, METH_VARARGS, doc_t_div },
  619. { "t_div_2exp", GMPy_MPZ_t_div_2exp, METH_VARARGS, doc_t_div_2exp },
  620. { "t_divmod", GMPy_MPZ_t_divmod, METH_VARARGS, doc_t_divmod },
  621. { "t_divmod_2exp", GMPy_MPZ_t_divmod_2exp, METH_VARARGS, doc_t_divmod_2exp },
  622. { "t_mod", GMPy_MPZ_t_mod, METH_VARARGS, doc_t_mod },
  623. { "t_mod_2exp", GMPy_MPZ_t_mod_2exp, METH_VARARGS, doc_t_mod_2exp },
  624. { "unpack", GMPy_MPZ_unpack, METH_VARARGS, doc_unpack },
  625. { "version", GMPy_get_version, METH_NOARGS, GMPy_doc_version },
  626. { "xbit_mask", GMPy_XMPZ_Function_XbitMask, METH_O, GMPy_doc_xmpz_function_xbit_mask },
  627. { "xmpz", (PyCFunction)GMPy_XMPZ_Factory, METH_VARARGS | METH_KEYWORDS, GMPy_doc_xmpz_factory },
  628. { "_mpmath_normalize", Pympz_mpmath_normalize, METH_VARARGS, doc_mpmath_normalizeg },
  629. { "_mpmath_create", Pympz_mpmath_create, METH_VARARGS, doc_mpmath_createg },
  630. { "acos", GMPy_Context_Acos, METH_O, GMPy_doc_function_acos },
  631. { "acosh", GMPy_Context_Acosh, METH_O, GMPy_doc_function_acosh },
  632. { "ai", GMPy_Context_Ai, METH_O, GMPy_doc_function_ai },
  633. { "agm", GMPy_Context_AGM, METH_VARARGS, GMPy_doc_function_agm },
  634. { "asin", GMPy_Context_Asin, METH_O, GMPy_doc_function_asin },
  635. { "asinh", GMPy_Context_Asinh, METH_O, GMPy_doc_function_asinh },
  636. { "atan", GMPy_Context_Atan, METH_O, GMPy_doc_function_atan },
  637. { "atanh", GMPy_Context_Atanh, METH_O, GMPy_doc_function_atanh },
  638. { "atan2", GMPy_Context_Atan2, METH_VARARGS, GMPy_doc_function_atan2 },
  639. { "can_round", GMPy_MPFR_Can_Round, METH_VARARGS, GMPy_doc_mpfr_can_round },
  640. { "cbrt", GMPy_Context_Cbrt, METH_O, GMPy_doc_function_cbrt },
  641. { "ceil", GMPy_Context_Ceil, METH_O, GMPy_doc_function_ceil },
  642. { "check_range", GMPy_Context_CheckRange, METH_O, GMPy_doc_function_check_range },
  643. { "const_catalan", (PyCFunction)GMPy_Function_Const_Catalan, METH_VARARGS | METH_KEYWORDS, GMPy_doc_function_const_catalan },
  644. { "const_euler", (PyCFunction)GMPy_Function_Const_Euler, METH_VARARGS | METH_KEYWORDS, GMPy_doc_function_const_euler },
  645. { "const_log2", (PyCFunction)GMPy_Function_Const_Log2, METH_VARARGS | METH_KEYWORDS, GMPy_doc_function_const_log2 },
  646. { "const_pi", (PyCFunction)GMPy_Function_Const_Pi, METH_VARARGS | METH_KEYWORDS, GMPy_doc_function_const_pi },
  647. { "context", (PyCFunction)GMPy_CTXT_Context, METH_VARARGS | METH_KEYWORDS, GMPy_doc_context },
  648. { "copy_sign", GMPy_MPFR_copy_sign, METH_VARARGS, GMPy_doc_mpfr_copy_sign },
  649. { "cos", GMPy_Context_Cos, METH_O, GMPy_doc_function_cos },
  650. { "cosh", GMPy_Context_Cosh, METH_O, GMPy_doc_function_cosh },
  651. { "cot", GMPy_Context_Cot, METH_O, GMPy_doc_function_cot },
  652. { "coth", GMPy_Context_Coth, METH_O, GMPy_doc_function_coth },
  653. { "csc", GMPy_Context_Csc, METH_O, GMPy_doc_function_csc },
  654. { "csch", GMPy_Context_Csch, METH_O, GMPy_doc_function_csch },
  655. { "degrees", GMPy_Context_Degrees, METH_O, GMPy_doc_function_degrees },
  656. { "digamma", GMPy_Context_Digamma, METH_O, GMPy_doc_function_digamma },
  657. { "div_2exp", GMPy_Context_Div_2exp, METH_VARARGS, GMPy_doc_function_div_2exp },
  658. { "eint", GMPy_Context_Eint, METH_O, GMPy_doc_function_eint },
  659. { "erf", GMPy_Context_Erf, METH_O, GMPy_doc_function_erf },
  660. { "erfc", GMPy_Context_Erfc, METH_O, GMPy_doc_function_erfc },
  661. { "exp", GMPy_Context_Exp, METH_O, GMPy_doc_function_exp },
  662. { "expm1", GMPy_Context_Expm1, METH_O, GMPy_doc_function_expm1 },
  663. { "exp10", GMPy_Context_Exp10, METH_O, GMPy_doc_function_exp10 },
  664. { "exp2", GMPy_Context_Exp2, METH_O, GMPy_doc_function_exp2 },
  665. { "f2q", GMPy_Context_F2Q, METH_VARARGS, GMPy_doc_function_f2q },
  666. { "factorial", GMPy_Context_Factorial, METH_O, GMPy_doc_function_factorial },
  667. { "floor", GMPy_Context_Floor, METH_O, GMPy_doc_function_floor },
  668. { "fma", GMPy_Context_FMA, METH_VARARGS, GMPy_doc_function_fma },
  669. { "fms", GMPy_Context_FMS, METH_VARARGS, GMPy_doc_function_fms },
  670. { "fmod", GMPy_Context_Fmod, METH_VARARGS, GMPy_doc_function_fmod },
  671. { "frac", GMPy_Context_Frac, METH_O, GMPy_doc_function_frac },
  672. { "free_cache", GMPy_MPFR_Free_Cache, METH_NOARGS, GMPy_doc_mpfr_free_cache },
  673. { "frexp", GMPy_Context_Frexp, METH_O, GMPy_doc_function_frexp },
  674. { "fsum", GMPy_Context_Fsum, METH_O, GMPy_doc_function_fsum },
  675. { "gamma", GMPy_Context_Gamma, METH_O, GMPy_doc_function_gamma },
  676. { "get_context", GMPy_CTXT_Get, METH_NOARGS, GMPy_doc_get_context },
  677. { "get_emax_max", GMPy_MPFR_get_emax_max, METH_NOARGS, GMPy_doc_mpfr_get_emax_max },
  678. { "get_emin_min", GMPy_MPFR_get_emin_min, METH_NOARGS, GMPy_doc_mpfr_get_emin_min },
  679. { "get_exp", GMPy_MPFR_get_exp, METH_O, GMPy_doc_mpfr_get_exp },
  680. { "get_max_precision", GMPy_MPFR_get_max_precision, METH_NOARGS, GMPy_doc_mpfr_get_max_precision },
  681. { "hypot", GMPy_Context_Hypot, METH_VARARGS, GMPy_doc_function_hypot },
  682. { "ieee", GMPy_CTXT_ieee, METH_O, GMPy_doc_context_ieee },
  683. { "inf", GMPy_MPFR_set_inf, METH_VARARGS, GMPy_doc_mpfr_set_inf },
  684. { "is_finite", GMPy_Context_Is_Finite, METH_O, GMPy_doc_function_is_finite },
  685. { "is_infinite", GMPy_Context_Is_Infinite, METH_O, GMPy_doc_function_is_infinite },
  686. { "is_integer", GMPy_Context_Is_Integer, METH_O, GMPy_doc_function_is_integer },
  687. { "is_lessgreater", GMPy_Context_Is_LessGreater, METH_VARARGS, GMPy_doc_function_is_lessgreater },
  688. { "is_nan", GMPy_Context_Is_NAN, METH_O, GMPy_doc_function_is_nan },
  689. { "is_regular", GMPy_Context_Is_Regular, METH_O, GMPy_doc_function_is_regular },
  690. { "is_signed", GMPy_Context_Is_Signed, METH_O, GMPy_doc_function_is_signed },
  691. { "is_unordered", GMPy_Context_Is_Unordered, METH_VARARGS, GMPy_doc_function_is_unordered },
  692. { "is_zero", GMPy_Context_Is_Zero, METH_O, GMPy_doc_function_is_zero },
  693. { "jn", GMPy_Context_Jn, METH_VARARGS, GMPy_doc_function_jn },
  694. { "j0", GMPy_Context_J0, METH_O, GMPy_doc_function_j0 },
  695. { "j1", GMPy_Context_J1, METH_O, GMPy_doc_function_j1 },
  696. { "lgamma", GMPy_Context_Lgamma, METH_O, GMPy_doc_function_lgamma },
  697. { "li2", GMPy_Context_Li2, METH_O, GMPy_doc_function_li2 },
  698. { "lngamma", GMPy_Context_Lngamma, METH_O, GMPy_doc_function_lngamma },
  699. { "local_context", (PyCFunction)GMPy_CTXT_Local, METH_VARARGS | METH_KEYWORDS, GMPy_doc_local_context },
  700. { "log", GMPy_Context_Log, METH_O, GMPy_doc_function_log },
  701. { "log1p", GMPy_Context_Log1p, METH_O, GMPy_doc_function_log1p },
  702. { "log10", GMPy_Context_Log10, METH_O, GMPy_doc_function_log10 },
  703. { "log2", GMPy_Context_Log2, METH_O, GMPy_doc_function_log2 },
  704. { "maxnum", GMPy_Context_Maxnum, METH_VARARGS, GMPy_doc_function_maxnum },
  705. { "minnum", GMPy_Context_Minnum, METH_VARARGS, GMPy_doc_function_minnum },
  706. { "modf", GMPy_Context_Modf, METH_O, GMPy_doc_function_modf },
  707. { "mpfr", (PyCFunction)GMPy_MPFR_Factory, METH_VARARGS | METH_KEYWORDS, GMPy_doc_mpfr_factory },
  708. { "mpfr_from_old_binary", GMPy_MPFR_From_Old_Binary, METH_O, doc_mpfr_from_old_binary },
  709. { "mpfr_random", GMPy_MPFR_random_Function, METH_VARARGS, GMPy_doc_mpfr_random_function },
  710. { "mpfr_grandom", GMPy_MPFR_grandom_Function, METH_VARARGS, GMPy_doc_mpfr_grandom_function },
  711. { "mul_2exp", GMPy_Context_Mul_2exp, METH_VARARGS, GMPy_doc_function_mul_2exp },
  712. { "nan", GMPy_MPFR_set_nan, METH_NOARGS, GMPy_doc_mpfr_set_nan },
  713. { "next_above", GMPy_Context_NextAbove, METH_O, GMPy_doc_function_next_above },
  714. { "next_below", GMPy_Context_NextBelow, METH_O, GMPy_doc_function_next_below },
  715. { "next_toward", GMPy_Context_NextToward, METH_VARARGS, GMPy_doc_function_next_toward },
  716. { "radians", GMPy_Context_Radians, METH_O, GMPy_doc_function_radians },
  717. { "rec_sqrt", GMPy_Context_RecSqrt, METH_O, GMPy_doc_function_rec_sqrt },
  718. { "reldiff", GMPy_Context_RelDiff, METH_VARARGS, GMPy_doc_function_reldiff },
  719. { "remainder", GMPy_Context_Remainder, METH_VARARGS, GMPy_doc_function_remainder },
  720. { "remquo", GMPy_Context_RemQuo, METH_VARARGS, GMPy_doc_function_remquo },
  721. { "rint", GMPy_Context_Rint, METH_O, GMPy_doc_function_rint },
  722. { "rint_ceil", GMPy_Context_RintCeil, METH_O, GMPy_doc_function_rint_ceil },
  723. { "rint_floor", GMPy_Context_RintFloor, METH_O, GMPy_doc_function_rint_floor },
  724. { "rint_round", GMPy_Context_RintRound, METH_O, GMPy_doc_function_rint_round },
  725. { "rint_trunc", GMPy_Context_RintTrunc, METH_O, GMPy_doc_function_rint_trunc },
  726. { "root", GMPy_Context_Root, METH_VARARGS, GMPy_doc_function_root },
  727. { "round_away", GMPy_Context_RoundAway, METH_O, GMPy_doc_function_round_away },
  728. { "round2", GMPy_Context_Round2, METH_VARARGS, GMPy_doc_function_round2 },
  729. { "sec", GMPy_Context_Sec, METH_O, GMPy_doc_function_sec },
  730. { "sech", GMPy_Context_Sech, METH_O, GMPy_doc_function_sech },
  731. { "set_context", GMPy_CTXT_Set, METH_O, GMPy_doc_set_context },
  732. { "set_exp", GMPy_MPFR_set_exp, METH_VARARGS, GMPy_doc_mpfr_set_exp },
  733. { "set_sign", GMPy_MPFR_set_sign, METH_VARARGS, GMPy_doc_mpfr_set_sign },
  734. { "sin", GMPy_Context_Sin, METH_O, GMPy_doc_function_sin },
  735. { "sin_cos", GMPy_Context_Sin_Cos, METH_O, GMPy_doc_function_sin_cos },
  736. { "sinh", GMPy_Context_Sinh, METH_O, GMPy_doc_function_sinh },
  737. { "sinh_cosh", GMPy_Context_Sinh_Cosh, METH_O, GMPy_doc_function_sinh_cosh },
  738. { "sqrt", GMPy_Context_Sqrt, METH_O, GMPy_doc_function_sqrt },
  739. { "tan", GMPy_Context_Tan, METH_O, GMPy_doc_function_tan },
  740. { "tanh", GMPy_Context_Tanh, METH_O, GMPy_doc_function_tanh },
  741. { "trunc", GMPy_Context_Trunc, METH_O, GMPy_doc_function_trunc},
  742. { "yn", GMPy_Context_Yn, METH_VARARGS, GMPy_doc_function_yn },
  743. { "y0", GMPy_Context_Y0, METH_O, GMPy_doc_function_y0 },
  744. { "y1", GMPy_Context_Y1, METH_O, GMPy_doc_function_y1 },
  745. { "zero", GMPy_MPFR_set_zero, METH_VARARGS, GMPy_doc_mpfr_set_zero },
  746. { "zeta", GMPy_Context_Zeta, METH_O, GMPy_doc_function_zeta },
  747. { "mpc", (PyCFunction)GMPy_MPC_Factory, METH_VARARGS | METH_KEYWORDS, GMPy_doc_mpc_factory },
  748. { "mpc_random", GMPy_MPC_random_Function, METH_VARARGS, GMPy_doc_mpc_random_function },
  749. { "norm", GMPy_Context_Norm, METH_O, GMPy_doc_function_norm },
  750. { "polar", GMPy_Context_Polar, METH_O, GMPy_doc_function_polar },
  751. { "phase", GMPy_Context_Phase, METH_O, GMPy_doc_function_phase },
  752. { "proj", GMPy_Context_Proj, METH_O, GMPy_doc_function_proj },
  753. { "rect", GMPy_Context_Rect, METH_VARARGS, GMPy_doc_function_rect },
  754. { NULL, NULL, 1}
  755. };
  756. /* The custom memory allocation routines either use PyMem_* or the standard
  757. * libraries. See gmpy.h for defines.
  758. */
  759. static void *
  760. gmpy_allocate(size_t size)
  761. {
  762. void *res;
  763. if (!(res = GMPY_MALLOC(size)))
  764. Py_FatalError("Insufficient memory");
  765. return res;
  766. }
  767. static void *
  768. gmpy_reallocate(void *ptr, size_t old_size, size_t new_size)
  769. {
  770. void *res;
  771. if (!(res = GMPY_REALLOC(ptr, new_size)))
  772. Py_FatalError("Insufficient memory");
  773. return res;
  774. }
  775. static void
  776. gmpy_free( void *ptr, size_t size)
  777. {
  778. GMPY_FREE(ptr);
  779. }
  780. static char _gmpy_docs[] =
  781. "gmpy2 2.1.0a0 - General Multiple-precision arithmetic for Python\n"
  782. "\n"
  783. "gmpy2 supports several multiple-precision libraries. Integer and\n"
  784. "rational arithmetic is provided by either the GMP or MPIR libraries.\n"
  785. "Real floating-point arithmetic is provided by the MPFR library.\n"
  786. "Complex floating-point arithmetic is provided by the MPC library.\n"
  787. "\n"
  788. "The integer type 'mpz' has comparable functionality to Python's\n"
  789. "builtin integers, but is faster for operations on large numbers.\n"
  790. "A wide variety of additional functions are provided:\n"
  791. " - bit manipulations\n"
  792. " - GCD, Extended GCD, LCM\n"
  793. " - Fibonacci and Lucas sequences\n"
  794. " - primality testing\n"
  795. " - powers and integer Nth roots\n"
  796. "\n"
  797. "The rational type 'mpq' is equivalent to Python's fractions\n"
  798. "module, but is faster.\n"
  799. "\n"
  800. "The real type 'mpfr' and complex type 'mpc' provide multiple-\n"
  801. "precision real and complex numbers with user-definable precision,\n"
  802. "rounding, and exponent range. All the advanced functions from the\n"
  803. "MPFR and MPC libraries are available.\n\
  804. ";
  805. /* Notes on Python 3.x support: Full support for PEP-3121 has not been
  806. * implemented. No per-module state has been defined.
  807. */
  808. #ifdef PY3
  809. #define INITERROR return NULL
  810. static struct PyModuleDef moduledef = {
  811. PyModuleDef_HEAD_INIT,
  812. "gmpy2",
  813. _gmpy_docs,
  814. -1, /*sizeof(struct module_state) */
  815. Pygmpy_methods,
  816. NULL,
  817. NULL, /* gmpy_traverse */
  818. NULL, /* gmpy_clear */
  819. NULL
  820. };
  821. #else
  822. #define INITERROR return
  823. #endif
  824. #ifdef PY3
  825. PyMODINIT_FUNC PyInit_gmpy2(void)
  826. #else
  827. PyMODINIT_FUNC initgmpy2(void)
  828. #endif
  829. {
  830. PyObject* gmpy_module = NULL;
  831. PyObject* copy_reg_module = NULL;
  832. PyObject *temp = NULL;
  833. /* Validate the sizes of the various typedef'ed integer types. */
  834. #if defined _WIN64 && (MPIR || MSYS2)
  835. if (sizeof(mp_bitcnt_t) != sizeof(PY_LONG_LONG)) {
  836. SYSTEM_ERROR("Size of PY_LONG_LONG and mp_bitcnt_t not compatible (_WIN64 && MPIR)");
  837. INITERROR;
  838. }
  839. #else
  840. if (sizeof(mp_bitcnt_t) != sizeof(long)) {
  841. SYSTEM_ERROR("Size of long and mp_bitcnt_t not compatible");
  842. INITERROR;
  843. }
  844. #endif
  845. if (sizeof(mp_bitcnt_t) > sizeof(size_t)) {
  846. SYSTEM_ERROR("Size of size_t and mp_bitcnt_t not compatible");
  847. INITERROR;
  848. }
  849. if (sizeof(mpfr_prec_t) != sizeof(long)) {
  850. SYSTEM_ERROR("Size of mpfr_prec_t and long not compatible");
  851. INITERROR;
  852. }
  853. if (sizeof(mpfr_exp_t) != sizeof(long)) {
  854. SYSTEM_ERROR("Size of mpfr_exp_t and long not compatible");
  855. INITERROR;
  856. }
  857. /* Initialize the types. */
  858. if (PyType_Ready(&MPZ_Type) < 0)
  859. INITERROR;
  860. if (PyType_Ready(&MPQ_Type) < 0)
  861. INITERROR;
  862. if (PyType_Ready(&XMPZ_Type) < 0)
  863. INITERROR;
  864. if (PyType_Ready(&GMPy_Iter_Type) < 0)
  865. INITERROR;
  866. if (PyType_Ready(&MPFR_Type) < 0)
  867. INITERROR;
  868. if (PyType_Ready(&CTXT_Type) < 0)
  869. INITERROR;
  870. if (PyType_Ready(&CTXT_Manager_Type) < 0)
  871. INITERROR;
  872. if (PyType_Ready(&MPC_Type) < 0)
  873. INITERROR;
  874. /* Initialize the custom memory handlers. */
  875. mp_set_memory_functions(gmpy_allocate, gmpy_reallocate, gmpy_free);
  876. /* Initialize object caching. */
  877. set_zcache();
  878. set_gmpympzcache();
  879. set_gmpympqcache();
  880. set_gmpyxmpzcache();
  881. set_gmpympfrcache();
  882. set_gmpympccache();
  883. /* Initialize exceptions. */
  884. GMPyExc_GmpyError = PyErr_NewException("gmpy2.gmpyError",
  885. PyExc_ArithmeticError, NULL);
  886. if (!GMPyExc_GmpyError)
  887. INITERROR;
  888. GMPyExc_Erange = PyErr_NewException("gmpy2.RangeError",
  889. GMPyExc_GmpyError, NULL);
  890. if (!GMPyExc_Erange)
  891. INITERROR;
  892. GMPyExc_Inexact = PyErr_NewException("gmpy2.InexactResultError",
  893. GMPyExc_GmpyError, NULL);
  894. if (!GMPyExc_Inexact)
  895. INITERROR;
  896. GMPyExc_Overflow = PyErr_NewException("gmpy2.OverflowResultError",
  897. GMPyExc_Inexact, NULL);
  898. if (!GMPyExc_Overflow)
  899. INITERROR;
  900. GMPyExc_Underflow = PyErr_NewException("gmpy2.UnderflowResultError",
  901. GMPyExc_Inexact, NULL);
  902. if (!GMPyExc_Underflow)
  903. INITERROR;
  904. temp = PyTuple_Pack(2, GMPyExc_GmpyError, PyExc_ValueError);
  905. if (!temp)
  906. INITERROR;
  907. GMPyExc_Invalid = PyErr_NewException("gmpy2.InvalidOperationError",
  908. temp, NULL);
  909. Py_DECREF(temp);
  910. if (!GMPyExc_Invalid)
  911. INITERROR;
  912. temp = PyTuple_Pack(2, GMPyExc_GmpyError, PyExc_ZeroDivisionError);
  913. if (!temp)
  914. INITERROR;
  915. GMPyExc_DivZero = PyErr_NewException("gmpy2.DivisionByZeroError",
  916. temp, NULL);
  917. Py_DECREF(temp);
  918. if (!GMPyExc_DivZero)
  919. INITERROR;
  920. #ifdef PY3
  921. gmpy_module = PyModule_Create(&moduledef);
  922. #else
  923. gmpy_module = Py_InitModule3("gmpy2", Pygmpy_methods, _gmpy_docs);
  924. #endif
  925. if (gmpy_module == NULL)
  926. INITERROR;
  927. /* Initialize thread local contexts. */
  928. #ifdef WITHOUT_THREADS
  929. module_context = (CTXT_Object*)GMPy_CTXT_New();
  930. if (!module_context)
  931. INITERROR;
  932. Py_INCREF(Py_False);
  933. if (PyModule_AddObject(gmpy_module, "HAVE_THREADS", Py_False) < 0) {
  934. Py_DECREF(Py_False);
  935. INITERROR;
  936. }
  937. #else
  938. tls_context_key = PyUnicode_FromString("__GMPY2_CTX__");
  939. Py_INCREF(Py_True);
  940. if (PyModule_AddObject(gmpy_module, "HAVE_THREADS", Py_True) < 0) {
  941. Py_DECREF(Py_True);
  942. INITERROR;
  943. }
  944. #endif
  945. /* Add the constants for defining rounding modes. */
  946. if (PyModule_AddIntConstant(gmpy_module, "RoundToNearest", MPFR_RNDN) < 0)
  947. INITERROR;
  948. if (PyModule_AddIntConstant(gmpy_module, "RoundToZero", MPFR_RNDZ) < 0)
  949. INITERROR;
  950. if (PyModule_AddIntConstant(gmpy_module, "RoundUp", MPFR_RNDU) < 0)
  951. INITERROR;
  952. if (PyModule_AddIntConstant(gmpy_module, "RoundDown", MPFR_RNDD) < 0)
  953. INITERROR;
  954. if (PyModule_AddIntConstant(gmpy_module, "RoundAwayZero", MPFR_RNDA) < 0)
  955. INITERROR;
  956. if (PyModule_AddIntConstant(gmpy_module, "Default", GMPY_DEFAULT) < 0)
  957. INITERROR;
  958. /* Add the exceptions. */
  959. Py_INCREF(GMPyExc_DivZero);
  960. if (PyModule_AddObject(gmpy_module, "DivisionByZeroError", GMPyExc_DivZero) < 0) {
  961. Py_DECREF(GMPyExc_DivZero);
  962. INITERROR;
  963. }
  964. Py_INCREF(GMPyExc_Inexact);
  965. if (PyModule_AddObject(gmpy_module, "InexactResultError", GMPyExc_Inexact) < 0) {
  966. Py_DECREF(GMPyExc_Inexact);
  967. INITERROR;
  968. }
  969. Py_INCREF(GMPyExc_Invalid);
  970. if (PyModule_AddObject(gmpy_module, "InvalidOperationError", GMPyExc_Invalid) < 0 ) {
  971. Py_DECREF(GMPyExc_Invalid);
  972. INITERROR;
  973. }
  974. Py_INCREF(GMPyExc_Overflow);
  975. if (PyModule_AddObject(gmpy_module, "OverflowResultError", GMPyExc_Overflow) < 0) {
  976. Py_DECREF(GMPyExc_Overflow);
  977. INITERROR;
  978. }
  979. Py_INCREF(GMPyExc_Underflow);
  980. if (PyModule_AddObject(gmpy_module, "UnderflowResultError", GMPyExc_Underflow) < 0) {
  981. Py_DECREF(GMPyExc_Underflow);
  982. INITERROR;
  983. }
  984. Py_INCREF(GMPyExc_Erange);
  985. if (PyModule_AddObject(gmpy_module, "RangeError", GMPyExc_Erange) < 0) {
  986. Py_DECREF(GMPyExc_Erange);
  987. INITERROR;
  988. }
  989. /* Add support for pickling. */
  990. #ifdef PY3
  991. copy_reg_module = PyImport_ImportModule("copyreg");
  992. if (copy_reg_module) {
  993. char* enable_pickle =
  994. "def gmpy2_reducer(x): return (gmpy2.from_binary, (gmpy2.to_binary(x),))\n"
  995. "copyreg.pickle(type(gmpy2.mpz(0)), gmpy2_reducer)\n"
  996. "copyreg.pickle(type(gmpy2.xmpz(0)), gmpy2_reducer)\n"
  997. "copyreg.pickle(type(gmpy2.mpq(0)), gmpy2_reducer)\n"
  998. "copyreg.pickle(type(gmpy2.mpfr(0)), gmpy2_reducer)\n"
  999. "copyreg.pickle(type(gmpy2.mpc(0,0)), gmpy2_reducer)\n";
  1000. PyObject* namespace = PyDict_New();
  1001. PyObject* result = NULL;
  1002. PyDict_SetItemString(namespace, "copyreg", copy_reg_module);
  1003. PyDict_SetItemString(namespace, "gmpy2", gmpy_module);
  1004. PyDict_SetItemString(namespace, "type", (PyObject*)&PyType_Type);
  1005. result = PyRun_String(enable_pickle, Py_file_input,
  1006. namespace, namespace);
  1007. if (!result)
  1008. PyErr_Clear();
  1009. Py_DECREF(namespace);
  1010. Py_DECREF(copy_reg_module);
  1011. Py_XDECREF(result);
  1012. }
  1013. else {
  1014. PyErr_Clear();
  1015. }
  1016. #else
  1017. copy_reg_module = PyImport_ImportModule("copy_reg");
  1018. if (copy_reg_module) {
  1019. char* enable_pickle =
  1020. "def gmpy2_reducer(x): return (gmpy2.from_binary, (gmpy2.to_binary(x),))\n"
  1021. "copy_reg.pickle(type(gmpy2.mpz(0)), gmpy2_reducer)\n"
  1022. "copy_reg.pickle(type(gmpy2.xmpz(0)), gmpy2_reducer)\n"
  1023. "copy_reg.pickle(type(gmpy2.mpq(0)), gmpy2_reducer)\n"
  1024. "copy_reg.pickle(type(gmpy2.mpfr(0)), gmpy2_reducer)\n"
  1025. "copy_reg.pickle(type(gmpy2.mpc(0,0)), gmpy2_reducer)\n";
  1026. PyObject* namespace = PyDict_New();
  1027. PyObject* result = NULL;
  1028. PyDict_SetItemString(namespace, "copy_reg", copy_reg_module);
  1029. PyDict_SetItemString(namespace, "gmpy2", gmpy_module);
  1030. PyDict_SetItemString(namespace, "type", (PyObject*)&PyType_Type);
  1031. result = PyRun_String(enable_pickle, Py_file_input,
  1032. namespace, namespace);
  1033. if (!result)
  1034. PyErr_Clear();
  1035. Py_DECREF(namespace);
  1036. Py_DECREF(copy_reg_module);
  1037. Py_XDECREF(result);
  1038. }
  1039. else {
  1040. PyErr_Clear();
  1041. }
  1042. #endif
  1043. #ifdef PY3
  1044. return gmpy_module;
  1045. #endif
  1046. }