K i,dZdZddlZddlZddlmZddlmZmZddl m Z ddl m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^mZdd l m_Z_dd l m`Z`eajZcejd Zeed k(rdd lfmgZhddlfmicmjcmkZln ddlmmnZhddl mmZlddlmmoZompZpmqZqGddeheZrGddZsetdk(rddluZueujyy)z[ This module defines the mpf, mpc classes, and standard functions for operating with them. plaintextN)StandardBaseContext) basestringBACKEND)libmp)UMPZMPZ_ZEROMPZ_ONE int_typesrepr_dps round_floor round_ceiling dps_to_prec round_nearest prec_to_dps ComplexResult to_pickable from_pickable normalizefrom_int from_floatfrom_strto_intto_floatto_str from_rational from_man_expfonefzerofinffninffnanmpf_absmpf_posmpf_negmpf_addmpf_submpf_mul mpf_mul_intmpf_div mpf_rdiv_int mpf_pow_intmpf_modmpf_eqmpf_cmpmpf_ltmpf_gtmpf_lempf_gempf_hashmpf_randmpf_sumbitcountto_fixed mpc_to_strmpc_to_complexmpc_hashmpc_posmpc_is_nonzerompc_neg mpc_conjugatempc_absmpc_add mpc_add_mpfmpc_sub mpc_sub_mpfmpc_mul mpc_mul_mpf mpc_mul_intmpc_div mpc_div_mpfmpc_pow mpc_pow_mpf mpc_pow_int mpc_mpf_divmpf_powmpf_pi mpf_degreempf_empf_phimpf_ln2mpf_ln10 mpf_euler mpf_catalan mpf_apery mpf_khinchin mpf_glaisher mpf_twinprime mpf_mertensr ) function_docs)rationalz\^\(?(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?)??(?P[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?j)?\)?$sage)Context)PythonMPContext) ctx_mp_python)_mpf_mpc mpnumericcleZdZdZdZdZdZdZdZdZ dZ d Z d8d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZedZedZd9dZd9dZd9dZd9dZ d:d Z!d;d!Z"d"Z#d#Z$d$Z%d%Z&d&Z'd-:-D-DCMM ! ! *+8+@+@CKK   ('4'8'8CGGOO $)6)<).;.E.ECMM " " +,9,A,ACKK )(5(9(9CGG   %*7*=*=CII   '  >sB$GB-I65I6c|j}|j}|jt|_|jt |_|jt tf|_|jt|_ |jt|_ |jt|_|jddd}||_|jt"dd|_|jt&dd|_|jt*dd|_|jt.d d |_|jt2d d |_|jt6d d|_|jt:dd|_|jt>dd|_ |jtBdd|_"|jtFdd|_$|jtJdd|_&|jtNdd|_(|jtRdd|_*|jWtXjZtXj\|_/|jWtXj`tXjb|_2|jWtXjftXjh|_5|jWtXjltXjn|_8|jWtXjrtXjt|_;|jWtXjxtXjz|_>|jWtXj~tXj|_A|jWtXjtXj|_D|jWtXjtXj|_G|jWtXjtXj|_J|jWtXjtXj|_M|jWtXjtXj|_P|jWtXjtXj|_S|jWtXjtXj|_V|jWtXjtXj|_Y|jWtXjltXjn|_8|jWtXjtXj|_\|jWtXjtXj|__|jWtXjtXj|_b|jWtXjtXj|_e|jWtXjtXj|_h|jWtXjtXj|_k|jWtXjtXj|_n|jWtXjtXj|_q|jWtXjtXj|_t|jWtXjtXjx|_w|_x|jWtXjtXj|_{|jWtXjtXj|_~|jWtXjtXj|_|jWtXjtXjx|_|_|jWtXj tXj|_|jWtXjtXj|_|jWtXjtXj|_|jWtXjtXj |_|jWtXj$tXj&|_|jWtXj*tXj,|_|jWtXj0tXj2|_|jWtXj6tXj8|_|jWtXj<tXj>|_|jWtXjBd|_|jWtXjFd|_|jWtXjJtXjL|_|jWtXjPtXjR|_tW|d|j^|_/tW|d|jv|_;tW|d|jj|_5tW|d |j|_GtW|d!|j|_Dy)"Ncdtd|z dfS)Nrr)r )precrnds rz)MPContext.init_builtins..msa!D&!-Dzepsilon of working precisionepspizln(2)ln2zln(10)ln10zGolden ratio phiphiz e = exp(1)ezEuler's constanteulerzCatalan's constantcatalanzKhinchin's constantkhinchinzGlaisher's constantglaisherzApery's constantaperyz1 deg = pi / 180degreezTwin prime constant twinprimezMertens' constantmertens _sage_sqrt _sage_exp_sage_ln _sage_cos _sage_sin)rnromake_mpfroner zeromake_mpcjr!infr"ninfr#nanrprrPrrTrrUrrSrrRrrVrrWrrYrrZrrXrrQrr[rr\r_wrap_libmp_functionrmpf_sqrtmpc_sqrtsqrtmpf_cbrtmpc_cbrtcbrtmpf_logmpc_loglnmpf_atanmpc_atanatanmpf_expmpc_expexpmpf_expjmpc_expjexpj mpf_expjpi mpc_expjpiexpjpimpf_sinmpc_sinsinmpf_cosmpc_coscosmpf_tanmpc_tantanmpf_sinhmpc_sinhsinhmpf_coshmpc_coshcoshmpf_tanhmpc_tanhtanhmpf_asinmpc_asinasinmpf_acosmpc_acosacos mpf_asinh mpc_asinhasinh mpf_acosh mpc_acoshacosh mpf_atanh mpc_atanhatanh mpf_sin_pi mpc_sin_pir mpf_cos_pi mpc_cos_pir mpf_floor mpc_floorfloormpf_ceilmpc_ceilceilmpf_nintmpc_nintnintmpf_fracmpc_fracfrac mpf_fibonacci mpc_fibonaccifib fibonacci mpf_gamma mpc_gammagamma mpf_rgamma mpc_rgammargamma mpf_loggamma mpc_loggammaloggamma mpf_factorial mpc_factorialfac factorialmpf_psi0mpc_psi0r mpf_harmonic mpc_harmonicharmonicmpf_eimpc_eieimpf_e1mpc_e1e1mpf_cimpc_ci_cimpf_simpc_si_si mpf_ellipk mpc_ellipkellipk mpf_ellipe mpc_ellipe_ellipempf_agm1mpc_agm1agm1mpf_erf_erfmpf_erfc_erfcmpf_zetampc_zeta_zeta mpf_altzeta mpc_altzeta_altzetagetattr)rrnrors rruzMPContext.init_builtins`sgggg,,t$<<& eD\*,,t$<<&,,t$llD *E3fdD1,,w7<<(F;,,w(:EB UL#6LL,>H ll;0DiP ||L2GT ||L2GT LL,>H \\*.@(K  ]4I;W ll;0CYO ++ENNENNK++ENNENNK))%--G++ENNENNK**5==%--H++ENNENNK--e.>.>@P@PQ **5==%--H**5==%--H**5==%--H++ENNENNK++ENNENNK++ENNENNK++ENNENNK++ENNENNK++ENNENNK,,U__eooN ,,U__eooN ,,U__eooN ,,U-=-=u?O?OP ,,U-=-=u?O?OP ,,U__eooN ++ENNENNK++ENNENNK++ENNENNK"%":":5;N;NPUPcPc"dd#-,,U__eooN --e.>.>@P@PQ //0B0BEDVDVW "%":":5;N;NPUPcPc"dd#-..u~~u~~N //0B0BEDVDVW ))%,, E))%,, E**5<<F**5<<F--e.>.>@P@PQ ..u/?/?AQAQR ++ENNENNK++EMM4@,,U^^TB ,,U^^U^^L //0A0A5CTCTU 3 chh7#{CGG4j#&&1#{CGG4#{CGG4rc$|j|SN)r9)rxrs rr9zMPContext.to_fixedszz$rc|j|}|j|}|jtj|j|jg|j S)z Computes the Euclidean norm of the vector `(x, y)`, equal to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real.)convertrr mpf_hypot_mpf__prec_rounding)rr&ys rhypotzMPContext.hypotsK KKN KKN||EOOAGGQWWRs?Q?QRSSrc>t|j|}|dk(r|j|St|dst|j \}}t j||j||d\}}||j|S|j||fS)Nrr*T)r) int_rer hasattrNotImplementedErrorr+r mpf_expintr*rrrnzrroundingrealimags r_gamma_upper_intzMPContext._gamma_upper_ints  O 666!9 q'"% %++h%%a$M d <<<% %<<t - -rct|}|dk(r|j|St|dst|j\}}t j ||j||\}}||j|S|j||fS)Nrr*) r/r r1r2r+rr3r*rrr4s r _expint_intzMPContext._expint_ints F 666!9 q'"% %++h%%a$A d <<<% %<<t - -rcxt|dr; |jtj|j|g|j S|j}|jtj||g|j S#t $r,|jr|jtjf}YdwxYwNr*) r1rr mpf_nthrootr*r+rrlr _mpc_r mpc_nthrootrr&r5s r_nthrootzMPContext._nthroots 1g  +||E$5$5aggq$V3CUCU$VWW A||E--aHS5G5GHII ! +##WWekk* +s9B2B98B9c|j\}}t|dr1|jtj||j ||St|dr1|j tj||j||SyNr*r@) r+r1rr mpf_besseljnr*r mpc_besseljnr@)rr5r6rr7s r_besseljzMPContext._besseljsr++h 1g << 2 21aggtX NO O Q << 2 21aggtX NO O!rc |j\}}t|drJt|dr> tj|j|j||}|j |St|dr|jtjf}n |j}t|dr|jtjf}n |j}|jtj||||S#t $rYwxYwr>) r+r1rmpf_agmr*rrr r@rmpc_agm)rabrr7vs r_agmzMPContext._agms++h 1g 71g#6 MM!''177D(C||A& 1g QWWekk$:''a 1g QWWekk$:''a||EMM!Qh?@@ !  s>> from mpmath import * >>> isnan(3.14) False >>> isnan(nan) True >>> isnan(mpc(3.14,2.72)) False >>> isnan(mpc(3.14,nan)) True r*r@Fzisnan() needs a number as input) r1r*r#r@ isinstancer r^rrr(isnan TypeErrorrqs rrvzMPContext.isnan>s" 1g 77d? " 1g 177? " a #z!X\\'B KKN 1g '!W"599Q< 9::rcJ|j|s|j|ryy)a Return *True* if *x* is a finite number, i.e. neither an infinity or a NaN. >>> from mpmath import * >>> isfinite(inf) False >>> isfinite(-inf) False >>> isfinite(3) True >>> isfinite(nan) False >>> isfinite(3+4j) True >>> isfinite(mpc(3,inf)) False >>> isfinite(mpc(nan,3)) False FT)isinfrvrqs risfinitezMPContext.isfiniteZs, 99Q<399Q<rc|syt|dr|j\}}}}|xr|dk\St|dr*|j xr|j|jSt |t vr|dkSt||jr|j\}}|sy|dk(xr|dkS|j|j|S)z< Determine if *x* is a nonpositive integer. Tr*rr@r) r1r*r9isnpintr8r^r rurr_mpq_r()rr&signmanrbcpqs rr|zMPContext.isnpintts 1g !" D#sB$C1H $ 1g vv:5#++aff"5 5 7i 6M a !77DAq6$a1f ${{3;;q>**rcdd|jzjddzd|jzjddzd|jzjddzg}d j |S) NzMpmath settings:z mp.prec = %sz [default: 53]z mp.dps = %sz [default: 15]z mp.trap_complex = %sz[default: False] )rljustdpsrljoin)rliness r__str__zMPContext.__str__st#  ( / / 3o E sww & - -b 1O C %(8(8 8 ? ? CFX X  yyrc,t|jSr%)r _precrs r _repr_digitszMPContext._repr_digitss ""rc|jSr%)_dpsrs r _str_digitszMPContext._str_digitss xxrFc&t|fdd|S)a The block with extraprec(n): increases the precision n bits, executes , and then restores the precision. extraprec(n)(f) returns a decorated version of the function f that increases the working precision by n bits before execution, and restores the parent precision afterwards. With normalize_output=True, it rounds the return value to the parent precision. c|zSr%rr5s rrz%MPContext.extraprec..s q1urNPrecisionManagerrr5normalize_outputs ` r extrapreczMPContext.extraprecs  _d.s QUrrrs ` rextradpszMPContext.extradpss  T? sets the precision to n bits, executes , and then restores the precision. workprec(n)(f) returns a decorated version of the function f that sets the precision to n bits before execution, and restores the precision afterwards. With normalize_output=True, it rounds the return value to the parent precision. cSr%rrs rrz$MPContext.workprec..sqrNrrs ` rworkpreczMPContext.workprecs [$8HIIrc&t|dfd|S)z This function is analogous to workprec (see documentation) but changes the decimal precision instead of the number of bits. NcSr%rrs rrz#MPContext.workdps..sQrrrs ` rworkdpszMPContext.workdpss  T;8HIIrNc"fd}|S)a Return a wrapped copy of *f* that repeatedly evaluates *f* with increasing precision until the result converges to the full precision used at the point of the call. This heuristically protects against rounding errors, at the cost of roughly a 2x slowdown compared to manually setting the optimal precision. This method can, however, easily be fooled if the results from *f* depend "discontinuously" on the precision, for instance if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec` should be used judiciously. **Examples** Many functions are sensitive to perturbations of the input arguments. If the arguments are decimal numbers, they may have to be converted to binary at a much higher precision. If the amount of required extra precision is unknown, :func:`~mpmath.autoprec` is convenient:: >>> from mpmath import * >>> mp.dps = 15 >>> mp.pretty = True >>> besselj(5, 125 * 10**28) # Exact input -8.03284785591801e-17 >>> besselj(5, '1.25e30') # Bad 7.12954868316652e-16 >>> autoprec(besselj)(5, '1.25e30') # Good -8.03284785591801e-17 The following fails to converge because `\sin(\pi) = 0` whereas all finite-precision approximations of `\pi` give nonzero values:: >>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NoConvergence: autoprec: prec increased to 2910 without convergence As the following example shows, :func:`~mpmath.autoprec` can protect against cancellation, but is fooled by too severe cancellation:: >>> x = 1e-10 >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) 1.00000008274037e-10 1.00000000005e-10 1.00000000005e-10 >>> x = 1e-50 >>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x) 0.0 1.0e-50 0.0 With *catch*, an exception or list of exceptions to intercept may be specified. The raised exception is interpreted as signaling insufficient precision. This permits, for example, evaluating a function where a too low precision results in a division by zero:: >>> f = lambda x: 1/(exp(x)-1) >>> f(1e-30) Traceback (most recent call last): ... ZeroDivisionError >>> autoprec(f, catch=ZeroDivisionError)(1e-30) 1.0e+30 c* j}  j|}n } |dz _  |i|}|dz} | _  |i|}||k(rn} j||z  j|z }|| krnP rt d|d|d| |}||k\r j d|z|t |dzz }t||}| _|S#$r j}YwxYw#$r j}YwxYw#| _wxYw)N zautoprec: target=z, prec=z , accuracy=z2autoprec: prec increased to %i without convergence)r_default_hyper_maxprecrmagprint NoConvergencer/min) argsrcrmaxprec2v1prec2v2errcatchrfmaxprecverboses rf_autoprec_wrappedz.MPContext.autoprec..f_autoprec_wrapped s_88D55d;" "9!D+F+Br $CH%//Rx''"R%.3772;6Cte}#USD23B(!//L !!Sq\)Ex0E), 3J5!B!!% WW%$ sR D C D C2BD C/,D .C//D 2DD DD Dr)rrrrrrs````` rautopreczMPContext.autoprecsH$ $ J"!rc t|trddjfd|DzSt|trddjfd|DzSt |drt |j fiSt |drdt|jfizd zSt|tr t|St|jr|jfiSt|S) a3 Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n* significant digits. The small default value for *n* is chosen to make this function useful for printing collections of numbers (lists, matrices, etc). If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively to each element. For unrecognized classes, :func:`~mpmath.nstr` simply returns ``str(x)``. The companion function :func:`~mpmath.nprint` prints the result instead of returning it. The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed* and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`. The number will be printed in fixed-point format if the position of the leading digit is strictly between min_fixed (default = min(-dps/3,-5)) and max_fixed (default = dps). To force fixed-point format always, set min_fixed = -inf, max_fixed = +inf. To force floating-point format, set min_fixed >= max_fixed. >>> from mpmath import * >>> nstr([+pi, ldexp(1,-500)]) '[3.14159, 3.05494e-151]' >>> nprint([+pi, ldexp(1,-500)]) [3.14159, 3.05494e-151] >>> nstr(mpf("5e-10"), 5) '5.0e-10' >>> nstr(mpf("5e-10"), 5, strip_zeros=False) '5.0000e-10' >>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11) '0.00000000050000' >>> nstr(mpf(0), 5, show_zero_exponent=True) '0.0e+0' z[%s]z, c3FK|]}j|fiywr%nstr.0rdrrcr5s r z!MPContext.nstr..]#&KAxsxx1'?'?&K!z(%s)c3FK|]}j|fiywr%rrs rrz!MPContext.nstr.._rrr*r@())rulistrtupler1rr*r:r@rreprmatrix__nstr__str)rr&r5rcs` ``rrzMPContext.nstr4sP a TYY&K&KKL L a TYY&K&KKL L 1g !''1// / 1g AGGQ9&99S@ @ a $7N a $1::a*6* *1v rc$|rt|trd|jvr|jjdd}tj |}|j d}|sd}|j djd}|j|j||j|St|dr0|j\}}||k(r|j|Stdtd t|z) Nr rerim_mpi_z,can only create mpf from zero-width intervalzcannot create mpf from )rurlowerreplace get_complexmatchgrouprstripror(r1rr ValueErrorrwr)rr&stringsrrrrLrMs r_convert_fallbackzMPContext._convert_fallbackjs z!Z0aggiGGI%%c2.#))!,[[&B[[&--c2wws{{2 B@@ 1g 77DAqAv||A& !OPP1DG;< ! &Um#''>!"3'> !!!!rz'the exact result does not fit in memoryzhypsum() failed to converge to the requested %i bits of accuracy using a working precision of %i bits. Try with a higher maxprec, maxterms, or set zeroprec.c t|dr|||df}|j} nt|dr|||df}|j} |jvr%t j |d|j|<|j|} |j } |jd|j| } d} d}i}d }t|D]\}}||d k(rG||k\rA|d kr.sBQ4Bszeroprecr)r1r*r@rvrmake_hyp_summatorrrr enumerateZeroDivisionError nint_distancer/maxabsr _hypsum_msgdictvaluesrorr^rrr)!rrrflagscoeffsr6accurate_smallrckeyrNsummatorrrrepsshiftmagnitude_checkmax_total_jumpirdokiiccr5rwpmag_dictzv have_complex magnitudecanceljumps_resolvedaccuraters! rhypsumzMPContext.hypsums 1g Qs"CA Q Qs"CA c'' '%*%<%)!*A q4x).2a/E~3EH!::j1'('#&771:-#&88O NI MH NIGJ 8u ||B''||B''Irc|j|}|jtj|j|S)a Computes `x 2^n` efficiently. No rounding is performed. The argument `x` must be a real floating-point number (or possible to convert into one) and `n` must be a Python ``int``. >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> ldexp(1, 10) mpf('1024.0') >>> ldexp(1, -3) mpf('0.125') )r(rr mpf_shiftr*rBs rldexpzMPContext.ldexps/ KKN||EOOAGGQ788rc|j|}tj|j\}}|j ||fS)a= Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`, `n` a Python integer, and such that `x = y 2^n`. No rounding is performed. >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> frexp(7.5) (mpf('0.9375'), 3) )r(r mpf_frexpr*r)rr&r,r5s rfrexpzMPContext.frexps: KKNqww'1||A!!rc *|j|\}}|j|}t|dr&|jt |j ||St|dr&|j t|j||Std)a Negates the number *x*, giving a floating-point result, optionally using a custom precision and rounding mode. See the documentation of :func:`~mpmath.fadd` for a detailed description of how to specify precision and rounding. **Examples** An mpmath number is returned:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fneg(2.5) mpf('-2.5') >>> fneg(-5+2j) mpc(real='5.0', imag='-2.0') Precise control over rounding is possible:: >>> x = fadd(2, 1e-100, exact=True) >>> fneg(x) mpf('-2.0') >>> fneg(x, rounding='f') mpf('-2.0000000000000004') Negating with and without roundoff:: >>> n = 200000000000000000000001 >>> print(int(-mpf(n))) -200000000000000016777216 >>> print(int(fneg(n))) -200000000000000016777216 >>> print(int(fneg(n, prec=log(n,2)+1))) -200000000000000000000001 >>> print(int(fneg(n, dps=log(n,10)+1))) -200000000000000000000001 >>> print(int(fneg(n, prec=inf))) -200000000000000000000001 >>> print(int(fneg(n, dps=inf))) -200000000000000000000001 >>> print(int(fneg(n, exact=True))) -200000000000000000000001 r*r@2Arguments need to be mpf or mpc compatible numbers) r_r(r1rr&r*rr?r@r)rr&rcrr7s rfnegzMPContext.fnegs|\0h KKN 1g <<x @A A 1g <<x @A AMNNrc |j|\}}|j|}|j|} t|drzt|dr1|jt |j |j ||St|dr1|j t|j|j ||St|drzt|dr1|j t|j|j ||St|dr1|j t|j|j||Std#ttf$rt|jwxYw)a Adds the numbers *x* and *y*, giving a floating-point result, optionally using a custom precision and rounding mode. The default precision is the working precision of the context. You can specify a custom precision in bits by passing the *prec* keyword argument, or by providing an equivalent decimal precision with the *dps* keyword argument. If the precision is set to ``+inf``, or if the flag *exact=True* is passed, an exact addition with no rounding is performed. When the precision is finite, the optional *rounding* keyword argument specifies the direction of rounding. Valid options are ``'n'`` for nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'`` for down, ``'u'`` for up. **Examples** Using :func:`~mpmath.fadd` with precision and rounding control:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fadd(2, 1e-20) mpf('2.0') >>> fadd(2, 1e-20, rounding='u') mpf('2.0000000000000004') >>> nprint(fadd(2, 1e-20, prec=100), 25) 2.00000000000000000001 >>> nprint(fadd(2, 1e-20, dps=15), 25) 2.0 >>> nprint(fadd(2, 1e-20, dps=25), 25) 2.00000000000000000001 >>> nprint(fadd(2, 1e-20, exact=True), 25) 2.00000000000000000001 Exact addition avoids cancellation errors, enforcing familiar laws of numbers such as `x+y-x = y`, which don't hold in floating-point arithmetic with finite precision:: >>> x, y = mpf(2), mpf('1e-1000') >>> print(x + y - x) 0.0 >>> print(fadd(x, y, prec=inf) - x) 1.0e-1000 >>> print(fadd(x, y, exact=True) - x) 1.0e-1000 Exact addition can be inefficient and may be impossible to perform with large magnitude differences:: >>> fadd(1, '1e-100000000000000000000', prec=inf) Traceback (most recent call last): ... OverflowError: the exact result does not fit in memory r*r@r) r_r(r1rr'r*rrCr@rBr OverflowError_exact_overflow_msgrr&r,rcrr7s rfaddzMPContext.faddFs/p0h KKN KKN 9q'"1g&<<$(QRR1g&<< AGGQWWdH(UVVq'"1g&<< AGGQWWdH(UVV1g&<<$(QRRMNNM* 9 7 78 8 9AEAE>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fsub(2, 1e-20) mpf('2.0') >>> fsub(2, 1e-20, rounding='d') mpf('1.9999999999999998') >>> nprint(fsub(2, 1e-20, prec=100), 25) 1.99999999999999999999 >>> nprint(fsub(2, 1e-20, dps=15), 25) 2.0 >>> nprint(fsub(2, 1e-20, dps=25), 25) 1.99999999999999999999 >>> nprint(fsub(2, 1e-20, exact=True), 25) 1.99999999999999999999 Exact subtraction avoids cancellation errors, enforcing familiar laws of numbers such as `x-y+y = x`, which don't hold in floating-point arithmetic with finite precision:: >>> x, y = mpf(2), mpf('1e1000') >>> print(x - y + y) 0.0 >>> print(fsub(x, y, prec=inf) + y) 2.0 >>> print(fsub(x, y, exact=True) + y) 2.0 Exact addition can be inefficient and may be impossible to perform with large magnitude differences:: >>> fsub(1, '1e-100000000000000000000', prec=inf) Traceback (most recent call last): ... OverflowError: the exact result does not fit in memory r*r@r)r_r(r1rr(r*rrDr r@rErrrrs rfsubzMPContext.fsubs5`0h KKN KKN 9q'"1g&<<$(QRR1g&<<%0@!''4QY(Z[[q'"1g&<< AGGQWWdH(UVV1g&<<$(QRRMNNM* 9 7 78 8 9s AEAEAE >> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fmul(2, 5.0) mpf('10.0') >>> fmul(0.5j, 0.5) mpc(real='0.0', imag='0.25') Avoiding roundoff:: >>> x, y = 10**10+1, 10**15+1 >>> print(x*y) 10000000001000010000000001 >>> print(mpf(x) * mpf(y)) 1.0000000001e+25 >>> print(int(mpf(x) * mpf(y))) 10000000001000011026399232 >>> print(int(fmul(x, y))) 10000000001000011026399232 >>> print(int(fmul(x, y, dps=25))) 10000000001000010000000001 >>> print(int(fmul(x, y, exact=True))) 10000000001000010000000001 Exact multiplication with complex numbers can be inefficient and may be impossible to perform with large magnitude differences between real and imaginary parts:: >>> x = 1+2j >>> y = mpc(2, '1e-100000000000000000000') >>> fmul(x, y) mpc(real='2.0', imag='4.0') >>> fmul(x, y, rounding='u') mpc(real='2.0', imag='4.0000000000000009') >>> fmul(x, y, exact=True) Traceback (most recent call last): ... OverflowError: the exact result does not fit in memory r*r@r) r_r(r1rr)r*rrGr@rFrrrrs rfmulzMPContext.fmuls/f0h KKN KKN 9q'"1g&<<$(QRR1g&<< AGGQWWdH(UVVq'"1g&<< AGGQWWdH(UVV1g&<<$(QRRMNNM* 9 7 78 8 9rc |j|\}}|s td|j|}|j|}t|drt|dr1|j t |j |j ||St|dr7|jt|j tf|j||St|drzt|dr1|jt|j|j ||St|dr1|jt|j|j||Std)a Divides the numbers *x* and *y*, giving a floating-point result, optionally using a custom precision and rounding mode. See the documentation of :func:`~mpmath.fadd` for a detailed description of how to specify precision and rounding. **Examples** The result is an mpmath number:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fdiv(3, 2) mpf('1.5') >>> fdiv(2, 3) mpf('0.66666666666666663') >>> fdiv(2+4j, 0.5) mpc(real='4.0', imag='8.0') The rounding direction and precision can be controlled:: >>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits mpf('0.6666259765625') >>> fdiv(2, 3, rounding='d') mpf('0.66666666666666663') >>> fdiv(2, 3, prec=60) mpf('0.66666666666666667') >>> fdiv(2, 3, rounding='u') mpf('0.66666666666666674') Checking the error of a division by performing it at higher precision:: >>> fdiv(2, 3) - fdiv(2, 3, prec=100) mpf('-3.7007434154172148e-17') Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not allowed since the quotient of two floating-point numbers generally does not have an exact floating-point representation. (In the future this might be changed to allow the case where the division is actually exact.) >>> fdiv(2, 3, exact=True) Traceback (most recent call last): ... ValueError: division is not an exact operation z"division is not an exact operationr*r@r) r_rr(r1rr+r*rrIr r@rJrs rfdivzMPContext.fdivsb0hAB B KKN KKN 1g q'"||GAGGQWWdH$MNNq'"||GQWWe,>> from mpmath import * >>> n, d = nint_distance(5) >>> print(n); print(d) 5 -inf >>> n, d = nint_distance(mpf(5)) >>> print(n); print(d) 5 -inf >>> n, d = nint_distance(mpf(5.00000001)) >>> print(n); print(d) 5 -26 >>> n, d = nint_distance(mpf(4.99999999)) >>> print(n); print(d) 5 -26 >>> n, d = nint_distance(mpc(5,10)) >>> print(n); print(d) 5 4 >>> n, d = nint_distance(mpc(5,0.000001)) >>> print(n); print(d) 5 -19 rrr*r@zrequires a finite numberzrequires an mpf/mpcr)r^r r/rr^rrr}divmodr8rr1r*r@r rr(rrwr)rr&typxrrr5rrrim_distrisignimaniexpibcr~rrrrre_distts rrzMPContext.nint_distanceYs3BAw 9 q6388# # X\\ !77DAq!Q>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> fprod([1, 2, 0.5, 7]) mpf('7.0') )rr)rfactorsorigrNrs rfprodzMPContext.fprodsNxx A Q CHr CHs1 :cJ|jt|jS)z Returns an ``mpf`` with value chosen randomly from `[0, 1)`. The number of randomly generated bits in the mantissa is equal to the working precision. )rr6rrs rrandzMPContext.rands ||HSYY/00rc<|jfddS)a Given Python integers `(p, q)`, returns a lazy ``mpf`` representing the fraction `p/q`. The value is updated with the precision. >>> from mpmath import * >>> mp.dps = 15 >>> a = fraction(1,100) >>> b = mpf(1)/100 >>> print(a); print(b) 0.01 0.01 >>> mp.dps = 30 >>> print(a); print(b) # a will be accurate 0.01 0.0100000000000000002081668171172 >>> mp.dps = 15 c t||Sr%)r)rrrrs rrz$MPContext.fraction..smAq$.Lr/)rp)rrrs ``rfractionzMPContext.fractions!$||L!  rc6t|j|Sr%rr(rqs rabsminzMPContext.absmin3;;q>""rc6t|j|Sr%r6rqs rabsmaxzMPContext.absmaxr8rct|dr1|j\}}|j||j|gS|S)Nr)r1rr)rr&rLrMs r _as_pointszMPContext._as_pointss9 1g 77DAqLLOS\\!_5 5rrcX|j|r t|dstt|}|j}t j |j|||||\}}|D cgc]} |j| }} |D cgc]} |j| }} ||fScc} wcc} w)Nr@) isintr1r2r/rr mpc_zetasumr@r) rrerLr5 derivativesreflectrxsysr&r,s r _zetasum_fastzMPContext._zetasum_fast s ! G!4% % Fyy""177Aq+wMB') *!cll1o * *') *!cll1o * *2v + *s &B"B')rF)NrF))T)8__name__ __module__ __qualname____doc__rkrur9r-r:r<rCrHrOrxrUr}r|rfrjrmrYrsrvrzr|rpropertyrrrrrrrrrrr_rrr r rrrrrrrr.r0r4r7r:r<rDrrrrgrg:s\1BT5l T . . JP ANMT P > >  ;84+( ##N$NJ"Ji"V4l=$,"*DKSj9"" 4OlHOT@ODCOJ@OD`(D*1*##"23Urrgc&eZdZddZdZdZdZy)rc<||_||_||_||_yr%)rprecfundpsfunr)selfrrNrOrs rrkzPrecisionManager.__init__s  0rcFtjfd}|S)NcLjj} jr5jjjj_n4jjjj_j rX|i|}t |tur+t|Dcgc]}|c}|j_S||j_S|i||j_Scc}w#|j_wxYwr%)rrrNrOrrr^r)rrcr-rNrLrrPs rgz$PrecisionManager.__call__..gs88==D %<<$(LL$?DHHM#';;txx||#r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrUrVrWrXrYrZr[r\r]r^object__new__newcompilersage.libs.mpmath.ext_mainr`rjlibsmpmathext_main _mpf_modulerbrarcrdrergrrGdoctesttestmodrrrrns  ).. nnbjjKL  fB33?.00Y 2Yv&!!H zGOOr