ctx_mp.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  1. """
  2. This module defines the mpf, mpc classes, and standard functions for
  3. operating with them.
  4. """
  5. __docformat__ = 'plaintext'
  6. import functools
  7. import re
  8. from .ctx_base import StandardBaseContext
  9. from .libmp.backend import basestring, BACKEND
  10. from . import libmp
  11. from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,
  12. round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,
  13. ComplexResult, to_pickable, from_pickable, normalize,
  14. from_int, from_float, from_str, to_int, to_float, to_str,
  15. from_rational, from_man_exp,
  16. fone, fzero, finf, fninf, fnan,
  17. mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,
  18. mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,
  19. mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,
  20. mpf_hash, mpf_rand,
  21. mpf_sum,
  22. bitcount, to_fixed,
  23. mpc_to_str,
  24. mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,
  25. mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,
  26. mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,
  27. mpc_mpf_div,
  28. mpf_pow,
  29. mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,
  30. mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,
  31. mpf_glaisher, mpf_twinprime, mpf_mertens,
  32. int_types)
  33. from . import function_docs
  34. from . import rational
  35. new = object.__new__
  36. get_complex = re.compile(r'^\(?(?P<re>[\+\-]?\d*\.?\d*(e[\+\-]?\d+)?)??'
  37. r'(?P<im>[\+\-]?\d*\.?\d*(e[\+\-]?\d+)?j)?\)?$')
  38. if BACKEND == 'sage':
  39. from sage.libs.mpmath.ext_main import Context as BaseMPContext
  40. # pickle hack
  41. import sage.libs.mpmath.ext_main as _mpf_module
  42. else:
  43. from .ctx_mp_python import PythonMPContext as BaseMPContext
  44. from . import ctx_mp_python as _mpf_module
  45. from .ctx_mp_python import _mpf, _mpc, mpnumeric
  46. class MPContext(BaseMPContext, StandardBaseContext):
  47. """
  48. Context for multiprecision arithmetic with a global precision.
  49. """
  50. def __init__(ctx):
  51. BaseMPContext.__init__(ctx)
  52. ctx.trap_complex = False
  53. ctx.pretty = False
  54. ctx.types = [ctx.mpf, ctx.mpc, ctx.constant]
  55. ctx._mpq = rational.mpq
  56. ctx.default()
  57. StandardBaseContext.__init__(ctx)
  58. ctx.mpq = rational.mpq
  59. ctx.init_builtins()
  60. ctx.hyp_summators = {}
  61. ctx._init_aliases()
  62. # XXX: automate
  63. try:
  64. ctx.bernoulli.im_func.func_doc = function_docs.bernoulli
  65. ctx.primepi.im_func.func_doc = function_docs.primepi
  66. ctx.psi.im_func.func_doc = function_docs.psi
  67. ctx.atan2.im_func.func_doc = function_docs.atan2
  68. except AttributeError:
  69. # python 3
  70. ctx.bernoulli.__func__.func_doc = function_docs.bernoulli
  71. ctx.primepi.__func__.func_doc = function_docs.primepi
  72. ctx.psi.__func__.func_doc = function_docs.psi
  73. ctx.atan2.__func__.func_doc = function_docs.atan2
  74. ctx.digamma.func_doc = function_docs.digamma
  75. ctx.cospi.func_doc = function_docs.cospi
  76. ctx.sinpi.func_doc = function_docs.sinpi
  77. def init_builtins(ctx):
  78. mpf = ctx.mpf
  79. mpc = ctx.mpc
  80. # Exact constants
  81. ctx.one = ctx.make_mpf(fone)
  82. ctx.zero = ctx.make_mpf(fzero)
  83. ctx.j = ctx.make_mpc((fzero,fone))
  84. ctx.inf = ctx.make_mpf(finf)
  85. ctx.ninf = ctx.make_mpf(fninf)
  86. ctx.nan = ctx.make_mpf(fnan)
  87. eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1),
  88. "epsilon of working precision", "eps")
  89. ctx.eps = eps
  90. # Approximate constants
  91. ctx.pi = ctx.constant(mpf_pi, "pi", "pi")
  92. ctx.ln2 = ctx.constant(mpf_ln2, "ln(2)", "ln2")
  93. ctx.ln10 = ctx.constant(mpf_ln10, "ln(10)", "ln10")
  94. ctx.phi = ctx.constant(mpf_phi, "Golden ratio phi", "phi")
  95. ctx.e = ctx.constant(mpf_e, "e = exp(1)", "e")
  96. ctx.euler = ctx.constant(mpf_euler, "Euler's constant", "euler")
  97. ctx.catalan = ctx.constant(mpf_catalan, "Catalan's constant", "catalan")
  98. ctx.khinchin = ctx.constant(mpf_khinchin, "Khinchin's constant", "khinchin")
  99. ctx.glaisher = ctx.constant(mpf_glaisher, "Glaisher's constant", "glaisher")
  100. ctx.apery = ctx.constant(mpf_apery, "Apery's constant", "apery")
  101. ctx.degree = ctx.constant(mpf_degree, "1 deg = pi / 180", "degree")
  102. ctx.twinprime = ctx.constant(mpf_twinprime, "Twin prime constant", "twinprime")
  103. ctx.mertens = ctx.constant(mpf_mertens, "Mertens' constant", "mertens")
  104. # Standard functions
  105. ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt)
  106. ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt)
  107. ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log)
  108. ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
  109. ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp)
  110. ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj)
  111. ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi)
  112. ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin)
  113. ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos)
  114. ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan)
  115. ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh)
  116. ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh)
  117. ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh)
  118. ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin)
  119. ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos)
  120. ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
  121. ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh)
  122. ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh)
  123. ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh)
  124. ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi)
  125. ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi)
  126. ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor)
  127. ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil)
  128. ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint)
  129. ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac)
  130. ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci)
  131. ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma)
  132. ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma)
  133. ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma)
  134. ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial)
  135. ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0)
  136. ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic)
  137. ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei)
  138. ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1)
  139. ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci)
  140. ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si)
  141. ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk)
  142. ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe)
  143. ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1)
  144. ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None)
  145. ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None)
  146. ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta)
  147. ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta)
  148. # Faster versions
  149. ctx.sqrt = getattr(ctx, "_sage_sqrt", ctx.sqrt)
  150. ctx.exp = getattr(ctx, "_sage_exp", ctx.exp)
  151. ctx.ln = getattr(ctx, "_sage_ln", ctx.ln)
  152. ctx.cos = getattr(ctx, "_sage_cos", ctx.cos)
  153. ctx.sin = getattr(ctx, "_sage_sin", ctx.sin)
  154. def to_fixed(ctx, x, prec):
  155. return x.to_fixed(prec)
  156. def hypot(ctx, x, y):
  157. r"""
  158. Computes the Euclidean norm of the vector `(x, y)`, equal
  159. to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real."""
  160. x = ctx.convert(x)
  161. y = ctx.convert(y)
  162. return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding))
  163. def _gamma_upper_int(ctx, n, z):
  164. n = int(ctx._re(n))
  165. if n == 0:
  166. return ctx.e1(z)
  167. if not hasattr(z, '_mpf_'):
  168. raise NotImplementedError
  169. prec, rounding = ctx._prec_rounding
  170. real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True)
  171. if imag is None:
  172. return ctx.make_mpf(real)
  173. else:
  174. return ctx.make_mpc((real, imag))
  175. def _expint_int(ctx, n, z):
  176. n = int(n)
  177. if n == 1:
  178. return ctx.e1(z)
  179. if not hasattr(z, '_mpf_'):
  180. raise NotImplementedError
  181. prec, rounding = ctx._prec_rounding
  182. real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding)
  183. if imag is None:
  184. return ctx.make_mpf(real)
  185. else:
  186. return ctx.make_mpc((real, imag))
  187. def _nthroot(ctx, x, n):
  188. if hasattr(x, '_mpf_'):
  189. try:
  190. return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding))
  191. except ComplexResult:
  192. if ctx.trap_complex:
  193. raise
  194. x = (x._mpf_, libmp.fzero)
  195. else:
  196. x = x._mpc_
  197. return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding))
  198. def _besselj(ctx, n, z):
  199. prec, rounding = ctx._prec_rounding
  200. if hasattr(z, '_mpf_'):
  201. return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding))
  202. elif hasattr(z, '_mpc_'):
  203. return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding))
  204. def _agm(ctx, a, b=1):
  205. prec, rounding = ctx._prec_rounding
  206. if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'):
  207. try:
  208. v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding)
  209. return ctx.make_mpf(v)
  210. except ComplexResult:
  211. pass
  212. if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero)
  213. else: a = a._mpc_
  214. if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero)
  215. else: b = b._mpc_
  216. return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding))
  217. def bernoulli(ctx, n):
  218. return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding))
  219. def _zeta_int(ctx, n):
  220. return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding))
  221. def atan2(ctx, y, x):
  222. x = ctx.convert(x)
  223. y = ctx.convert(y)
  224. return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding))
  225. def psi(ctx, m, z):
  226. z = ctx.convert(z)
  227. m = int(m)
  228. if ctx._is_real_type(z):
  229. return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding))
  230. else:
  231. return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding))
  232. def cos_sin(ctx, x, **kwargs):
  233. if type(x) not in ctx.types:
  234. x = ctx.convert(x)
  235. prec, rounding = ctx._parse_prec(kwargs)
  236. if hasattr(x, '_mpf_'):
  237. c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding)
  238. return ctx.make_mpf(c), ctx.make_mpf(s)
  239. elif hasattr(x, '_mpc_'):
  240. c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding)
  241. return ctx.make_mpc(c), ctx.make_mpc(s)
  242. else:
  243. return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
  244. def cospi_sinpi(ctx, x, **kwargs):
  245. if type(x) not in ctx.types:
  246. x = ctx.convert(x)
  247. prec, rounding = ctx._parse_prec(kwargs)
  248. if hasattr(x, '_mpf_'):
  249. c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding)
  250. return ctx.make_mpf(c), ctx.make_mpf(s)
  251. elif hasattr(x, '_mpc_'):
  252. c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding)
  253. return ctx.make_mpc(c), ctx.make_mpc(s)
  254. else:
  255. return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
  256. def clone(ctx):
  257. """
  258. Create a copy of the context, with the same working precision.
  259. """
  260. a = ctx.__class__()
  261. a.prec = ctx.prec
  262. return a
  263. # Several helper methods
  264. # TODO: add more of these, make consistent, write docstrings, ...
  265. def _is_real_type(ctx, x):
  266. if hasattr(x, '_mpc_') or type(x) is complex:
  267. return False
  268. return True
  269. def _is_complex_type(ctx, x):
  270. if hasattr(x, '_mpc_') or type(x) is complex:
  271. return True
  272. return False
  273. def isnan(ctx, x):
  274. """
  275. Return *True* if *x* is a NaN (not-a-number), or for a complex
  276. number, whether either the real or complex part is NaN;
  277. otherwise return *False*::
  278. >>> from mpmath import *
  279. >>> isnan(3.14)
  280. False
  281. >>> isnan(nan)
  282. True
  283. >>> isnan(mpc(3.14,2.72))
  284. False
  285. >>> isnan(mpc(3.14,nan))
  286. True
  287. """
  288. if hasattr(x, "_mpf_"):
  289. return x._mpf_ == fnan
  290. if hasattr(x, "_mpc_"):
  291. return fnan in x._mpc_
  292. if isinstance(x, int_types) or isinstance(x, rational.mpq):
  293. return False
  294. x = ctx.convert(x)
  295. if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
  296. return ctx.isnan(x)
  297. raise TypeError("isnan() needs a number as input")
  298. def isfinite(ctx, x):
  299. """
  300. Return *True* if *x* is a finite number, i.e. neither
  301. an infinity or a NaN.
  302. >>> from mpmath import *
  303. >>> isfinite(inf)
  304. False
  305. >>> isfinite(-inf)
  306. False
  307. >>> isfinite(3)
  308. True
  309. >>> isfinite(nan)
  310. False
  311. >>> isfinite(3+4j)
  312. True
  313. >>> isfinite(mpc(3,inf))
  314. False
  315. >>> isfinite(mpc(nan,3))
  316. False
  317. """
  318. if ctx.isinf(x) or ctx.isnan(x):
  319. return False
  320. return True
  321. def isnpint(ctx, x):
  322. """
  323. Determine if *x* is a nonpositive integer.
  324. """
  325. if not x:
  326. return True
  327. if hasattr(x, '_mpf_'):
  328. sign, man, exp, bc = x._mpf_
  329. return sign and exp >= 0
  330. if hasattr(x, '_mpc_'):
  331. return not x.imag and ctx.isnpint(x.real)
  332. if type(x) in int_types:
  333. return x <= 0
  334. if isinstance(x, ctx.mpq):
  335. p, q = x._mpq_
  336. if not p:
  337. return True
  338. return q == 1 and p <= 0
  339. return ctx.isnpint(ctx.convert(x))
  340. def __str__(ctx):
  341. lines = ["Mpmath settings:",
  342. (" mp.prec = %s" % ctx.prec).ljust(30) + "[default: 53]",
  343. (" mp.dps = %s" % ctx.dps).ljust(30) + "[default: 15]",
  344. (" mp.trap_complex = %s" % ctx.trap_complex).ljust(30) + "[default: False]",
  345. ]
  346. return "\n".join(lines)
  347. @property
  348. def _repr_digits(ctx):
  349. return repr_dps(ctx._prec)
  350. @property
  351. def _str_digits(ctx):
  352. return ctx._dps
  353. def extraprec(ctx, n, normalize_output=False):
  354. """
  355. The block
  356. with extraprec(n):
  357. <code>
  358. increases the precision n bits, executes <code>, and then
  359. restores the precision.
  360. extraprec(n)(f) returns a decorated version of the function f
  361. that increases the working precision by n bits before execution,
  362. and restores the parent precision afterwards. With
  363. normalize_output=True, it rounds the return value to the parent
  364. precision.
  365. """
  366. return PrecisionManager(ctx, lambda p: p + n, None, normalize_output)
  367. def extradps(ctx, n, normalize_output=False):
  368. """
  369. This function is analogous to extraprec (see documentation)
  370. but changes the decimal precision instead of the number of bits.
  371. """
  372. return PrecisionManager(ctx, None, lambda d: d + n, normalize_output)
  373. def workprec(ctx, n, normalize_output=False):
  374. """
  375. The block
  376. with workprec(n):
  377. <code>
  378. sets the precision to n bits, executes <code>, and then restores
  379. the precision.
  380. workprec(n)(f) returns a decorated version of the function f
  381. that sets the precision to n bits before execution,
  382. and restores the precision afterwards. With normalize_output=True,
  383. it rounds the return value to the parent precision.
  384. """
  385. return PrecisionManager(ctx, lambda p: n, None, normalize_output)
  386. def workdps(ctx, n, normalize_output=False):
  387. """
  388. This function is analogous to workprec (see documentation)
  389. but changes the decimal precision instead of the number of bits.
  390. """
  391. return PrecisionManager(ctx, None, lambda d: n, normalize_output)
  392. def autoprec(ctx, f, maxprec=None, catch=(), verbose=False):
  393. r"""
  394. Return a wrapped copy of *f* that repeatedly evaluates *f*
  395. with increasing precision until the result converges to the
  396. full precision used at the point of the call.
  397. This heuristically protects against rounding errors, at the cost of
  398. roughly a 2x slowdown compared to manually setting the optimal
  399. precision. This method can, however, easily be fooled if the results
  400. from *f* depend "discontinuously" on the precision, for instance
  401. if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec`
  402. should be used judiciously.
  403. **Examples**
  404. Many functions are sensitive to perturbations of the input arguments.
  405. If the arguments are decimal numbers, they may have to be converted
  406. to binary at a much higher precision. If the amount of required
  407. extra precision is unknown, :func:`~mpmath.autoprec` is convenient::
  408. >>> from mpmath import *
  409. >>> mp.dps = 15
  410. >>> mp.pretty = True
  411. >>> besselj(5, 125 * 10**28) # Exact input
  412. -8.03284785591801e-17
  413. >>> besselj(5, '1.25e30') # Bad
  414. 7.12954868316652e-16
  415. >>> autoprec(besselj)(5, '1.25e30') # Good
  416. -8.03284785591801e-17
  417. The following fails to converge because `\sin(\pi) = 0` whereas all
  418. finite-precision approximations of `\pi` give nonzero values::
  419. >>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL
  420. Traceback (most recent call last):
  421. ...
  422. NoConvergence: autoprec: prec increased to 2910 without convergence
  423. As the following example shows, :func:`~mpmath.autoprec` can protect against
  424. cancellation, but is fooled by too severe cancellation::
  425. >>> x = 1e-10
  426. >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
  427. 1.00000008274037e-10
  428. 1.00000000005e-10
  429. 1.00000000005e-10
  430. >>> x = 1e-50
  431. >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
  432. 0.0
  433. 1.0e-50
  434. 0.0
  435. With *catch*, an exception or list of exceptions to intercept
  436. may be specified. The raised exception is interpreted
  437. as signaling insufficient precision. This permits, for example,
  438. evaluating a function where a too low precision results in a
  439. division by zero::
  440. >>> f = lambda x: 1/(exp(x)-1)
  441. >>> f(1e-30)
  442. Traceback (most recent call last):
  443. ...
  444. ZeroDivisionError
  445. >>> autoprec(f, catch=ZeroDivisionError)(1e-30)
  446. 1.0e+30
  447. """
  448. def f_autoprec_wrapped(*args, **kwargs):
  449. prec = ctx.prec
  450. if maxprec is None:
  451. maxprec2 = ctx._default_hyper_maxprec(prec)
  452. else:
  453. maxprec2 = maxprec
  454. try:
  455. ctx.prec = prec + 10
  456. try:
  457. v1 = f(*args, **kwargs)
  458. except catch:
  459. v1 = ctx.nan
  460. prec2 = prec + 20
  461. while 1:
  462. ctx.prec = prec2
  463. try:
  464. v2 = f(*args, **kwargs)
  465. except catch:
  466. v2 = ctx.nan
  467. if v1 == v2:
  468. break
  469. err = ctx.mag(v2-v1) - ctx.mag(v2)
  470. if err < (-prec):
  471. break
  472. if verbose:
  473. print("autoprec: target=%s, prec=%s, accuracy=%s" \
  474. % (prec, prec2, -err))
  475. v1 = v2
  476. if prec2 >= maxprec2:
  477. raise ctx.NoConvergence(\
  478. "autoprec: prec increased to %i without convergence"\
  479. % prec2)
  480. prec2 += int(prec2*2)
  481. prec2 = min(prec2, maxprec2)
  482. finally:
  483. ctx.prec = prec
  484. return +v2
  485. return f_autoprec_wrapped
  486. def nstr(ctx, x, n=6, **kwargs):
  487. """
  488. Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n*
  489. significant digits. The small default value for *n* is chosen to
  490. make this function useful for printing collections of numbers
  491. (lists, matrices, etc).
  492. If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively
  493. to each element. For unrecognized classes, :func:`~mpmath.nstr`
  494. simply returns ``str(x)``.
  495. The companion function :func:`~mpmath.nprint` prints the result
  496. instead of returning it.
  497. The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed*
  498. and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`.
  499. The number will be printed in fixed-point format if the position
  500. of the leading digit is strictly between min_fixed
  501. (default = min(-dps/3,-5)) and max_fixed (default = dps).
  502. To force fixed-point format always, set min_fixed = -inf,
  503. max_fixed = +inf. To force floating-point format, set
  504. min_fixed >= max_fixed.
  505. >>> from mpmath import *
  506. >>> nstr([+pi, ldexp(1,-500)])
  507. '[3.14159, 3.05494e-151]'
  508. >>> nprint([+pi, ldexp(1,-500)])
  509. [3.14159, 3.05494e-151]
  510. >>> nstr(mpf("5e-10"), 5)
  511. '5.0e-10'
  512. >>> nstr(mpf("5e-10"), 5, strip_zeros=False)
  513. '5.0000e-10'
  514. >>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11)
  515. '0.00000000050000'
  516. >>> nstr(mpf(0), 5, show_zero_exponent=True)
  517. '0.0e+0'
  518. """
  519. if isinstance(x, list):
  520. return "[%s]" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
  521. if isinstance(x, tuple):
  522. return "(%s)" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
  523. if hasattr(x, '_mpf_'):
  524. return to_str(x._mpf_, n, **kwargs)
  525. if hasattr(x, '_mpc_'):
  526. return "(" + mpc_to_str(x._mpc_, n, **kwargs) + ")"
  527. if isinstance(x, basestring):
  528. return repr(x)
  529. if isinstance(x, ctx.matrix):
  530. return x.__nstr__(n, **kwargs)
  531. return str(x)
  532. def _convert_fallback(ctx, x, strings):
  533. if strings and isinstance(x, basestring):
  534. if 'j' in x.lower():
  535. x = x.lower().replace(' ', '')
  536. match = get_complex.match(x)
  537. re = match.group('re')
  538. if not re:
  539. re = 0
  540. im = match.group('im').rstrip('j')
  541. return ctx.mpc(ctx.convert(re), ctx.convert(im))
  542. if hasattr(x, "_mpi_"):
  543. a, b = x._mpi_
  544. if a == b:
  545. return ctx.make_mpf(a)
  546. else:
  547. raise ValueError("can only create mpf from zero-width interval")
  548. raise TypeError("cannot create mpf from " + repr(x))
  549. def mpmathify(ctx, *args, **kwargs):
  550. return ctx.convert(*args, **kwargs)
  551. def _parse_prec(ctx, kwargs):
  552. if kwargs:
  553. if kwargs.get('exact'):
  554. return 0, 'f'
  555. prec, rounding = ctx._prec_rounding
  556. if 'rounding' in kwargs:
  557. rounding = kwargs['rounding']
  558. if 'prec' in kwargs:
  559. prec = kwargs['prec']
  560. if prec == ctx.inf:
  561. return 0, 'f'
  562. else:
  563. prec = int(prec)
  564. elif 'dps' in kwargs:
  565. dps = kwargs['dps']
  566. if dps == ctx.inf:
  567. return 0, 'f'
  568. prec = dps_to_prec(dps)
  569. return prec, rounding
  570. return ctx._prec_rounding
  571. _exact_overflow_msg = "the exact result does not fit in memory"
  572. _hypsum_msg = """hypsum() failed to converge to the requested %i bits of accuracy
  573. using a working precision of %i bits. Try with a higher maxprec,
  574. maxterms, or set zeroprec."""
  575. def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs):
  576. if hasattr(z, "_mpf_"):
  577. key = p, q, flags, 'R'
  578. v = z._mpf_
  579. elif hasattr(z, "_mpc_"):
  580. key = p, q, flags, 'C'
  581. v = z._mpc_
  582. if key not in ctx.hyp_summators:
  583. ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1]
  584. summator = ctx.hyp_summators[key]
  585. prec = ctx.prec
  586. maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec))
  587. extraprec = 50
  588. epsshift = 25
  589. # Jumps in magnitude occur when parameters are close to negative
  590. # integers. We must ensure that these terms are included in
  591. # the sum and added accurately
  592. magnitude_check = {}
  593. max_total_jump = 0
  594. for i, c in enumerate(coeffs):
  595. if flags[i] == 'Z':
  596. if i >= p and c <= 0:
  597. ok = False
  598. for ii, cc in enumerate(coeffs[:p]):
  599. # Note: c <= cc or c < cc, depending on convention
  600. if flags[ii] == 'Z' and cc <= 0 and c <= cc:
  601. ok = True
  602. if not ok:
  603. raise ZeroDivisionError("pole in hypergeometric series")
  604. continue
  605. n, d = ctx.nint_distance(c)
  606. n = -int(n)
  607. d = -d
  608. if i >= p and n >= 0 and d > 4:
  609. if n in magnitude_check:
  610. magnitude_check[n] += d
  611. else:
  612. magnitude_check[n] = d
  613. extraprec = max(extraprec, d - prec + 60)
  614. max_total_jump += abs(d)
  615. while 1:
  616. if extraprec > maxprec:
  617. raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec))
  618. wp = prec + extraprec
  619. if magnitude_check:
  620. mag_dict = dict((n,None) for n in magnitude_check)
  621. else:
  622. mag_dict = {}
  623. zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \
  624. epsshift, mag_dict, **kwargs)
  625. cancel = -magnitude
  626. jumps_resolved = True
  627. if extraprec < max_total_jump:
  628. for n in mag_dict.values():
  629. if (n is None) or (n < prec):
  630. jumps_resolved = False
  631. break
  632. accurate = (cancel < extraprec-25-5 or not accurate_small)
  633. if jumps_resolved:
  634. if accurate:
  635. break
  636. # zero?
  637. zeroprec = kwargs.get('zeroprec')
  638. if zeroprec is not None:
  639. if cancel > zeroprec:
  640. if have_complex:
  641. return ctx.mpc(0)
  642. else:
  643. return ctx.zero
  644. # Some near-singularities were not included, so increase
  645. # precision and repeat until they are
  646. extraprec *= 2
  647. # Possible workaround for bad roundoff in fixed-point arithmetic
  648. epsshift += 5
  649. extraprec += 5
  650. if type(zv) is tuple:
  651. if have_complex:
  652. return ctx.make_mpc(zv)
  653. else:
  654. return ctx.make_mpf(zv)
  655. else:
  656. return zv
  657. def ldexp(ctx, x, n):
  658. r"""
  659. Computes `x 2^n` efficiently. No rounding is performed.
  660. The argument `x` must be a real floating-point number (or
  661. possible to convert into one) and `n` must be a Python ``int``.
  662. >>> from mpmath import *
  663. >>> mp.dps = 15; mp.pretty = False
  664. >>> ldexp(1, 10)
  665. mpf('1024.0')
  666. >>> ldexp(1, -3)
  667. mpf('0.125')
  668. """
  669. x = ctx.convert(x)
  670. return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n))
  671. def frexp(ctx, x):
  672. r"""
  673. Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`,
  674. `n` a Python integer, and such that `x = y 2^n`. No rounding is
  675. performed.
  676. >>> from mpmath import *
  677. >>> mp.dps = 15; mp.pretty = False
  678. >>> frexp(7.5)
  679. (mpf('0.9375'), 3)
  680. """
  681. x = ctx.convert(x)
  682. y, n = libmp.mpf_frexp(x._mpf_)
  683. return ctx.make_mpf(y), n
  684. def fneg(ctx, x, **kwargs):
  685. """
  686. Negates the number *x*, giving a floating-point result, optionally
  687. using a custom precision and rounding mode.
  688. See the documentation of :func:`~mpmath.fadd` for a detailed description
  689. of how to specify precision and rounding.
  690. **Examples**
  691. An mpmath number is returned::
  692. >>> from mpmath import *
  693. >>> mp.dps = 15; mp.pretty = False
  694. >>> fneg(2.5)
  695. mpf('-2.5')
  696. >>> fneg(-5+2j)
  697. mpc(real='5.0', imag='-2.0')
  698. Precise control over rounding is possible::
  699. >>> x = fadd(2, 1e-100, exact=True)
  700. >>> fneg(x)
  701. mpf('-2.0')
  702. >>> fneg(x, rounding='f')
  703. mpf('-2.0000000000000004')
  704. Negating with and without roundoff::
  705. >>> n = 200000000000000000000001
  706. >>> print(int(-mpf(n)))
  707. -200000000000000016777216
  708. >>> print(int(fneg(n)))
  709. -200000000000000016777216
  710. >>> print(int(fneg(n, prec=log(n,2)+1)))
  711. -200000000000000000000001
  712. >>> print(int(fneg(n, dps=log(n,10)+1)))
  713. -200000000000000000000001
  714. >>> print(int(fneg(n, prec=inf)))
  715. -200000000000000000000001
  716. >>> print(int(fneg(n, dps=inf)))
  717. -200000000000000000000001
  718. >>> print(int(fneg(n, exact=True)))
  719. -200000000000000000000001
  720. """
  721. prec, rounding = ctx._parse_prec(kwargs)
  722. x = ctx.convert(x)
  723. if hasattr(x, '_mpf_'):
  724. return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding))
  725. if hasattr(x, '_mpc_'):
  726. return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding))
  727. raise ValueError("Arguments need to be mpf or mpc compatible numbers")
  728. def fadd(ctx, x, y, **kwargs):
  729. """
  730. Adds the numbers *x* and *y*, giving a floating-point result,
  731. optionally using a custom precision and rounding mode.
  732. The default precision is the working precision of the context.
  733. You can specify a custom precision in bits by passing the *prec* keyword
  734. argument, or by providing an equivalent decimal precision with the *dps*
  735. keyword argument. If the precision is set to ``+inf``, or if the flag
  736. *exact=True* is passed, an exact addition with no rounding is performed.
  737. When the precision is finite, the optional *rounding* keyword argument
  738. specifies the direction of rounding. Valid options are ``'n'`` for
  739. nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'``
  740. for down, ``'u'`` for up.
  741. **Examples**
  742. Using :func:`~mpmath.fadd` with precision and rounding control::
  743. >>> from mpmath import *
  744. >>> mp.dps = 15; mp.pretty = False
  745. >>> fadd(2, 1e-20)
  746. mpf('2.0')
  747. >>> fadd(2, 1e-20, rounding='u')
  748. mpf('2.0000000000000004')
  749. >>> nprint(fadd(2, 1e-20, prec=100), 25)
  750. 2.00000000000000000001
  751. >>> nprint(fadd(2, 1e-20, dps=15), 25)
  752. 2.0
  753. >>> nprint(fadd(2, 1e-20, dps=25), 25)
  754. 2.00000000000000000001
  755. >>> nprint(fadd(2, 1e-20, exact=True), 25)
  756. 2.00000000000000000001
  757. Exact addition avoids cancellation errors, enforcing familiar laws
  758. of numbers such as `x+y-x = y`, which don't hold in floating-point
  759. arithmetic with finite precision::
  760. >>> x, y = mpf(2), mpf('1e-1000')
  761. >>> print(x + y - x)
  762. 0.0
  763. >>> print(fadd(x, y, prec=inf) - x)
  764. 1.0e-1000
  765. >>> print(fadd(x, y, exact=True) - x)
  766. 1.0e-1000
  767. Exact addition can be inefficient and may be impossible to perform
  768. with large magnitude differences::
  769. >>> fadd(1, '1e-100000000000000000000', prec=inf)
  770. Traceback (most recent call last):
  771. ...
  772. OverflowError: the exact result does not fit in memory
  773. """
  774. prec, rounding = ctx._parse_prec(kwargs)
  775. x = ctx.convert(x)
  776. y = ctx.convert(y)
  777. try:
  778. if hasattr(x, '_mpf_'):
  779. if hasattr(y, '_mpf_'):
  780. return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding))
  781. if hasattr(y, '_mpc_'):
  782. return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding))
  783. if hasattr(x, '_mpc_'):
  784. if hasattr(y, '_mpf_'):
  785. return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding))
  786. if hasattr(y, '_mpc_'):
  787. return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding))
  788. except (ValueError, OverflowError):
  789. raise OverflowError(ctx._exact_overflow_msg)
  790. raise ValueError("Arguments need to be mpf or mpc compatible numbers")
  791. def fsub(ctx, x, y, **kwargs):
  792. """
  793. Subtracts the numbers *x* and *y*, giving a floating-point result,
  794. optionally using a custom precision and rounding mode.
  795. See the documentation of :func:`~mpmath.fadd` for a detailed description
  796. of how to specify precision and rounding.
  797. **Examples**
  798. Using :func:`~mpmath.fsub` with precision and rounding control::
  799. >>> from mpmath import *
  800. >>> mp.dps = 15; mp.pretty = False
  801. >>> fsub(2, 1e-20)
  802. mpf('2.0')
  803. >>> fsub(2, 1e-20, rounding='d')
  804. mpf('1.9999999999999998')
  805. >>> nprint(fsub(2, 1e-20, prec=100), 25)
  806. 1.99999999999999999999
  807. >>> nprint(fsub(2, 1e-20, dps=15), 25)
  808. 2.0
  809. >>> nprint(fsub(2, 1e-20, dps=25), 25)
  810. 1.99999999999999999999
  811. >>> nprint(fsub(2, 1e-20, exact=True), 25)
  812. 1.99999999999999999999
  813. Exact subtraction avoids cancellation errors, enforcing familiar laws
  814. of numbers such as `x-y+y = x`, which don't hold in floating-point
  815. arithmetic with finite precision::
  816. >>> x, y = mpf(2), mpf('1e1000')
  817. >>> print(x - y + y)
  818. 0.0
  819. >>> print(fsub(x, y, prec=inf) + y)
  820. 2.0
  821. >>> print(fsub(x, y, exact=True) + y)
  822. 2.0
  823. Exact addition can be inefficient and may be impossible to perform
  824. with large magnitude differences::
  825. >>> fsub(1, '1e-100000000000000000000', prec=inf)
  826. Traceback (most recent call last):
  827. ...
  828. OverflowError: the exact result does not fit in memory
  829. """
  830. prec, rounding = ctx._parse_prec(kwargs)
  831. x = ctx.convert(x)
  832. y = ctx.convert(y)
  833. try:
  834. if hasattr(x, '_mpf_'):
  835. if hasattr(y, '_mpf_'):
  836. return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding))
  837. if hasattr(y, '_mpc_'):
  838. return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding))
  839. if hasattr(x, '_mpc_'):
  840. if hasattr(y, '_mpf_'):
  841. return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding))
  842. if hasattr(y, '_mpc_'):
  843. return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding))
  844. except (ValueError, OverflowError):
  845. raise OverflowError(ctx._exact_overflow_msg)
  846. raise ValueError("Arguments need to be mpf or mpc compatible numbers")
  847. def fmul(ctx, x, y, **kwargs):
  848. """
  849. Multiplies the numbers *x* and *y*, giving a floating-point result,
  850. optionally using a custom precision and rounding mode.
  851. See the documentation of :func:`~mpmath.fadd` for a detailed description
  852. of how to specify precision and rounding.
  853. **Examples**
  854. The result is an mpmath number::
  855. >>> from mpmath import *
  856. >>> mp.dps = 15; mp.pretty = False
  857. >>> fmul(2, 5.0)
  858. mpf('10.0')
  859. >>> fmul(0.5j, 0.5)
  860. mpc(real='0.0', imag='0.25')
  861. Avoiding roundoff::
  862. >>> x, y = 10**10+1, 10**15+1
  863. >>> print(x*y)
  864. 10000000001000010000000001
  865. >>> print(mpf(x) * mpf(y))
  866. 1.0000000001e+25
  867. >>> print(int(mpf(x) * mpf(y)))
  868. 10000000001000011026399232
  869. >>> print(int(fmul(x, y)))
  870. 10000000001000011026399232
  871. >>> print(int(fmul(x, y, dps=25)))
  872. 10000000001000010000000001
  873. >>> print(int(fmul(x, y, exact=True)))
  874. 10000000001000010000000001
  875. Exact multiplication with complex numbers can be inefficient and may
  876. be impossible to perform with large magnitude differences between
  877. real and imaginary parts::
  878. >>> x = 1+2j
  879. >>> y = mpc(2, '1e-100000000000000000000')
  880. >>> fmul(x, y)
  881. mpc(real='2.0', imag='4.0')
  882. >>> fmul(x, y, rounding='u')
  883. mpc(real='2.0', imag='4.0000000000000009')
  884. >>> fmul(x, y, exact=True)
  885. Traceback (most recent call last):
  886. ...
  887. OverflowError: the exact result does not fit in memory
  888. """
  889. prec, rounding = ctx._parse_prec(kwargs)
  890. x = ctx.convert(x)
  891. y = ctx.convert(y)
  892. try:
  893. if hasattr(x, '_mpf_'):
  894. if hasattr(y, '_mpf_'):
  895. return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding))
  896. if hasattr(y, '_mpc_'):
  897. return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding))
  898. if hasattr(x, '_mpc_'):
  899. if hasattr(y, '_mpf_'):
  900. return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding))
  901. if hasattr(y, '_mpc_'):
  902. return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding))
  903. except (ValueError, OverflowError):
  904. raise OverflowError(ctx._exact_overflow_msg)
  905. raise ValueError("Arguments need to be mpf or mpc compatible numbers")
  906. def fdiv(ctx, x, y, **kwargs):
  907. """
  908. Divides the numbers *x* and *y*, giving a floating-point result,
  909. optionally using a custom precision and rounding mode.
  910. See the documentation of :func:`~mpmath.fadd` for a detailed description
  911. of how to specify precision and rounding.
  912. **Examples**
  913. The result is an mpmath number::
  914. >>> from mpmath import *
  915. >>> mp.dps = 15; mp.pretty = False
  916. >>> fdiv(3, 2)
  917. mpf('1.5')
  918. >>> fdiv(2, 3)
  919. mpf('0.66666666666666663')
  920. >>> fdiv(2+4j, 0.5)
  921. mpc(real='4.0', imag='8.0')
  922. The rounding direction and precision can be controlled::
  923. >>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits
  924. mpf('0.6666259765625')
  925. >>> fdiv(2, 3, rounding='d')
  926. mpf('0.66666666666666663')
  927. >>> fdiv(2, 3, prec=60)
  928. mpf('0.66666666666666667')
  929. >>> fdiv(2, 3, rounding='u')
  930. mpf('0.66666666666666674')
  931. Checking the error of a division by performing it at higher precision::
  932. >>> fdiv(2, 3) - fdiv(2, 3, prec=100)
  933. mpf('-3.7007434154172148e-17')
  934. Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not
  935. allowed since the quotient of two floating-point numbers generally
  936. does not have an exact floating-point representation. (In the
  937. future this might be changed to allow the case where the division
  938. is actually exact.)
  939. >>> fdiv(2, 3, exact=True)
  940. Traceback (most recent call last):
  941. ...
  942. ValueError: division is not an exact operation
  943. """
  944. prec, rounding = ctx._parse_prec(kwargs)
  945. if not prec:
  946. raise ValueError("division is not an exact operation")
  947. x = ctx.convert(x)
  948. y = ctx.convert(y)
  949. if hasattr(x, '_mpf_'):
  950. if hasattr(y, '_mpf_'):
  951. return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding))
  952. if hasattr(y, '_mpc_'):
  953. return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding))
  954. if hasattr(x, '_mpc_'):
  955. if hasattr(y, '_mpf_'):
  956. return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding))
  957. if hasattr(y, '_mpc_'):
  958. return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding))
  959. raise ValueError("Arguments need to be mpf or mpc compatible numbers")
  960. def nint_distance(ctx, x):
  961. r"""
  962. Return `(n,d)` where `n` is the nearest integer to `x` and `d` is
  963. an estimate of `\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision
  964. (measured in bits) lost to cancellation when computing `x-n`.
  965. >>> from mpmath import *
  966. >>> n, d = nint_distance(5)
  967. >>> print(n); print(d)
  968. 5
  969. -inf
  970. >>> n, d = nint_distance(mpf(5))
  971. >>> print(n); print(d)
  972. 5
  973. -inf
  974. >>> n, d = nint_distance(mpf(5.00000001))
  975. >>> print(n); print(d)
  976. 5
  977. -26
  978. >>> n, d = nint_distance(mpf(4.99999999))
  979. >>> print(n); print(d)
  980. 5
  981. -26
  982. >>> n, d = nint_distance(mpc(5,10))
  983. >>> print(n); print(d)
  984. 5
  985. 4
  986. >>> n, d = nint_distance(mpc(5,0.000001))
  987. >>> print(n); print(d)
  988. 5
  989. -19
  990. """
  991. typx = type(x)
  992. if typx in int_types:
  993. return int(x), ctx.ninf
  994. elif typx is rational.mpq:
  995. p, q = x._mpq_
  996. n, r = divmod(p, q)
  997. if 2*r >= q:
  998. n += 1
  999. elif not r:
  1000. return n, ctx.ninf
  1001. # log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q)
  1002. d = bitcount(abs(p-n*q)) - bitcount(q)
  1003. return n, d
  1004. if hasattr(x, "_mpf_"):
  1005. re = x._mpf_
  1006. im_dist = ctx.ninf
  1007. elif hasattr(x, "_mpc_"):
  1008. re, im = x._mpc_
  1009. isign, iman, iexp, ibc = im
  1010. if iman:
  1011. im_dist = iexp + ibc
  1012. elif im == fzero:
  1013. im_dist = ctx.ninf
  1014. else:
  1015. raise ValueError("requires a finite number")
  1016. else:
  1017. x = ctx.convert(x)
  1018. if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"):
  1019. return ctx.nint_distance(x)
  1020. else:
  1021. raise TypeError("requires an mpf/mpc")
  1022. sign, man, exp, bc = re
  1023. mag = exp+bc
  1024. # |x| < 0.5
  1025. if mag < 0:
  1026. n = 0
  1027. re_dist = mag
  1028. elif man:
  1029. # exact integer
  1030. if exp >= 0:
  1031. n = man << exp
  1032. re_dist = ctx.ninf
  1033. # exact half-integer
  1034. elif exp == -1:
  1035. n = (man>>1)+1
  1036. re_dist = 0
  1037. else:
  1038. d = (-exp-1)
  1039. t = man >> d
  1040. if t & 1:
  1041. t += 1
  1042. man = (t<<d) - man
  1043. else:
  1044. man -= (t<<d)
  1045. n = t>>1 # int(t)>>1
  1046. re_dist = exp+bitcount(man)
  1047. if sign:
  1048. n = -n
  1049. elif re == fzero:
  1050. re_dist = ctx.ninf
  1051. n = 0
  1052. else:
  1053. raise ValueError("requires a finite number")
  1054. return n, max(re_dist, im_dist)
  1055. def fprod(ctx, factors):
  1056. r"""
  1057. Calculates a product containing a finite number of factors (for
  1058. infinite products, see :func:`~mpmath.nprod`). The factors will be
  1059. converted to mpmath numbers.
  1060. >>> from mpmath import *
  1061. >>> mp.dps = 15; mp.pretty = False
  1062. >>> fprod([1, 2, 0.5, 7])
  1063. mpf('7.0')
  1064. """
  1065. orig = ctx.prec
  1066. try:
  1067. v = ctx.one
  1068. for p in factors:
  1069. v *= p
  1070. finally:
  1071. ctx.prec = orig
  1072. return +v
  1073. def rand(ctx):
  1074. """
  1075. Returns an ``mpf`` with value chosen randomly from `[0, 1)`.
  1076. The number of randomly generated bits in the mantissa is equal
  1077. to the working precision.
  1078. """
  1079. return ctx.make_mpf(mpf_rand(ctx._prec))
  1080. def fraction(ctx, p, q):
  1081. """
  1082. Given Python integers `(p, q)`, returns a lazy ``mpf`` representing
  1083. the fraction `p/q`. The value is updated with the precision.
  1084. >>> from mpmath import *
  1085. >>> mp.dps = 15
  1086. >>> a = fraction(1,100)
  1087. >>> b = mpf(1)/100
  1088. >>> print(a); print(b)
  1089. 0.01
  1090. 0.01
  1091. >>> mp.dps = 30
  1092. >>> print(a); print(b) # a will be accurate
  1093. 0.01
  1094. 0.0100000000000000002081668171172
  1095. >>> mp.dps = 15
  1096. """
  1097. return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd),
  1098. '%s/%s' % (p, q))
  1099. def absmin(ctx, x):
  1100. return abs(ctx.convert(x))
  1101. def absmax(ctx, x):
  1102. return abs(ctx.convert(x))
  1103. def _as_points(ctx, x):
  1104. # XXX: remove this?
  1105. if hasattr(x, '_mpi_'):
  1106. a, b = x._mpi_
  1107. return [ctx.make_mpf(a), ctx.make_mpf(b)]
  1108. return x
  1109. '''
  1110. def _zetasum(ctx, s, a, b):
  1111. """
  1112. Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small
  1113. integers.
  1114. """
  1115. a = int(a)
  1116. b = int(b)
  1117. s = ctx.convert(s)
  1118. prec, rounding = ctx._prec_rounding
  1119. if hasattr(s, '_mpf_'):
  1120. v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec))
  1121. elif hasattr(s, '_mpc_'):
  1122. v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec))
  1123. return v
  1124. '''
  1125. def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False):
  1126. if not (ctx.isint(a) and hasattr(s, "_mpc_")):
  1127. raise NotImplementedError
  1128. a = int(a)
  1129. prec = ctx._prec
  1130. xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec)
  1131. xs = [ctx.make_mpc(x) for x in xs]
  1132. ys = [ctx.make_mpc(y) for y in ys]
  1133. return xs, ys
  1134. class PrecisionManager:
  1135. def __init__(self, ctx, precfun, dpsfun, normalize_output=False):
  1136. self.ctx = ctx
  1137. self.precfun = precfun
  1138. self.dpsfun = dpsfun
  1139. self.normalize_output = normalize_output
  1140. def __call__(self, f):
  1141. @functools.wraps(f)
  1142. def g(*args, **kwargs):
  1143. orig = self.ctx.prec
  1144. try:
  1145. if self.precfun:
  1146. self.ctx.prec = self.precfun(self.ctx.prec)
  1147. else:
  1148. self.ctx.dps = self.dpsfun(self.ctx.dps)
  1149. if self.normalize_output:
  1150. v = f(*args, **kwargs)
  1151. if type(v) is tuple:
  1152. return tuple([+a for a in v])
  1153. return +v
  1154. else:
  1155. return f(*args, **kwargs)
  1156. finally:
  1157. self.ctx.prec = orig
  1158. return g
  1159. def __enter__(self):
  1160. self.origp = self.ctx.prec
  1161. if self.precfun:
  1162. self.ctx.prec = self.precfun(self.ctx.prec)
  1163. else:
  1164. self.ctx.dps = self.dpsfun(self.ctx.dps)
  1165. def __exit__(self, exc_type, exc_val, exc_tb):
  1166. self.ctx.prec = self.origp
  1167. return False
  1168. if __name__ == '__main__':
  1169. import doctest
  1170. doctest.testmod()