gammazeta.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166
  1. """
  2. -----------------------------------------------------------------------
  3. This module implements gamma- and zeta-related functions:
  4. * Bernoulli numbers
  5. * Factorials
  6. * The gamma function
  7. * Polygamma functions
  8. * Harmonic numbers
  9. * The Riemann zeta function
  10. * Constants related to these functions
  11. -----------------------------------------------------------------------
  12. """
  13. import math
  14. import sys
  15. from .backend import xrange
  16. from .backend import MPZ, MPZ_ZERO, MPZ_ONE, MPZ_THREE, gmpy
  17. from .libintmath import list_primes, ifac, ifac2, moebius
  18. from .libmpf import (\
  19. round_floor, round_ceiling, round_down, round_up,
  20. round_nearest, round_fast,
  21. lshift, sqrt_fixed, isqrt_fast,
  22. fzero, fone, fnone, fhalf, ftwo, finf, fninf, fnan,
  23. from_int, to_int, to_fixed, from_man_exp, from_rational,
  24. mpf_pos, mpf_neg, mpf_abs, mpf_add, mpf_sub,
  25. mpf_mul, mpf_mul_int, mpf_div, mpf_sqrt, mpf_pow_int,
  26. mpf_rdiv_int,
  27. mpf_perturb, mpf_le, mpf_lt, mpf_gt, mpf_shift,
  28. negative_rnd, reciprocal_rnd,
  29. bitcount, to_float, mpf_floor, mpf_sign, ComplexResult
  30. )
  31. from .libelefun import (\
  32. constant_memo,
  33. def_mpf_constant,
  34. mpf_pi, pi_fixed, ln2_fixed, log_int_fixed, mpf_ln2,
  35. mpf_exp, mpf_log, mpf_pow, mpf_cosh,
  36. mpf_cos_sin, mpf_cosh_sinh, mpf_cos_sin_pi, mpf_cos_pi, mpf_sin_pi,
  37. ln_sqrt2pi_fixed, mpf_ln_sqrt2pi, sqrtpi_fixed, mpf_sqrtpi,
  38. cos_sin_fixed, exp_fixed
  39. )
  40. from .libmpc import (\
  41. mpc_zero, mpc_one, mpc_half, mpc_two,
  42. mpc_abs, mpc_shift, mpc_pos, mpc_neg,
  43. mpc_add, mpc_sub, mpc_mul, mpc_div,
  44. mpc_add_mpf, mpc_mul_mpf, mpc_div_mpf, mpc_mpf_div,
  45. mpc_mul_int, mpc_pow_int,
  46. mpc_log, mpc_exp, mpc_pow,
  47. mpc_cos_pi, mpc_sin_pi,
  48. mpc_reciprocal, mpc_square,
  49. mpc_sub_mpf
  50. )
  51. # Catalan's constant is computed using Lupas's rapidly convergent series
  52. # (listed on http://mathworld.wolfram.com/CatalansConstant.html)
  53. # oo
  54. # ___ n-1 8n 2 3 2
  55. # 1 \ (-1) 2 (40n - 24n + 3) [(2n)!] (n!)
  56. # K = --- ) -----------------------------------------
  57. # 64 /___ 3 2
  58. # n (2n-1) [(4n)!]
  59. # n = 1
  60. @constant_memo
  61. def catalan_fixed(prec):
  62. prec = prec + 20
  63. a = one = MPZ_ONE << prec
  64. s, t, n = 0, 1, 1
  65. while t:
  66. a *= 32 * n**3 * (2*n-1)
  67. a //= (3-16*n+16*n**2)**2
  68. t = a * (-1)**(n-1) * (40*n**2-24*n+3) // (n**3 * (2*n-1))
  69. s += t
  70. n += 1
  71. return s >> (20 + 6)
  72. # Khinchin's constant is relatively difficult to compute. Here
  73. # we use the rational zeta series
  74. # oo 2*n-1
  75. # ___ ___
  76. # \ ` zeta(2*n)-1 \ ` (-1)^(k+1)
  77. # log(K)*log(2) = ) ------------ ) ----------
  78. # /___. n /___. k
  79. # n = 1 k = 1
  80. # which adds half a digit per term. The essential trick for achieving
  81. # reasonable efficiency is to recycle both the values of the zeta
  82. # function (essentially Bernoulli numbers) and the partial terms of
  83. # the inner sum.
  84. # An alternative might be to use K = 2*exp[1/log(2) X] where
  85. # / 1 1 [ pi*x*(1-x^2) ]
  86. # X = | ------ log [ ------------ ].
  87. # / 0 x(1+x) [ sin(pi*x) ]
  88. # and integrate numerically. In practice, this seems to be slightly
  89. # slower than the zeta series at high precision.
  90. @constant_memo
  91. def khinchin_fixed(prec):
  92. wp = int(prec + prec**0.5 + 15)
  93. s = MPZ_ZERO
  94. fac = from_int(4)
  95. t = ONE = MPZ_ONE << wp
  96. pi = mpf_pi(wp)
  97. pipow = twopi2 = mpf_shift(mpf_mul(pi, pi, wp), 2)
  98. n = 1
  99. while 1:
  100. zeta2n = mpf_abs(mpf_bernoulli(2*n, wp))
  101. zeta2n = mpf_mul(zeta2n, pipow, wp)
  102. zeta2n = mpf_div(zeta2n, fac, wp)
  103. zeta2n = to_fixed(zeta2n, wp)
  104. term = (((zeta2n - ONE) * t) // n) >> wp
  105. if term < 100:
  106. break
  107. #if not n % 10:
  108. # print n, math.log(int(abs(term)))
  109. s += term
  110. t += ONE//(2*n+1) - ONE//(2*n)
  111. n += 1
  112. fac = mpf_mul_int(fac, (2*n)*(2*n-1), wp)
  113. pipow = mpf_mul(pipow, twopi2, wp)
  114. s = (s << wp) // ln2_fixed(wp)
  115. K = mpf_exp(from_man_exp(s, -wp), wp)
  116. K = to_fixed(K, prec)
  117. return K
  118. # Glaisher's constant is defined as A = exp(1/2 - zeta'(-1)).
  119. # One way to compute it would be to perform direct numerical
  120. # differentiation, but computing arbitrary Riemann zeta function
  121. # values at high precision is expensive. We instead use the formula
  122. # A = exp((6 (-zeta'(2))/pi^2 + log 2 pi + gamma)/12)
  123. # and compute zeta'(2) from the series representation
  124. # oo
  125. # ___
  126. # \ log k
  127. # -zeta'(2) = ) -----
  128. # /___ 2
  129. # k
  130. # k = 2
  131. # This series converges exceptionally slowly, but can be accelerated
  132. # using Euler-Maclaurin formula. The important insight is that the
  133. # E-M integral can be done in closed form and that the high order
  134. # are given by
  135. # n / \
  136. # d | log x | a + b log x
  137. # --- | ----- | = -----------
  138. # n | 2 | 2 + n
  139. # dx \ x / x
  140. # where a and b are integers given by a simple recurrence. Note
  141. # that just one logarithm is needed. However, lots of integer
  142. # logarithms are required for the initial summation.
  143. # This algorithm could possibly be turned into a faster algorithm
  144. # for general evaluation of zeta(s) or zeta'(s); this should be
  145. # looked into.
  146. @constant_memo
  147. def glaisher_fixed(prec):
  148. wp = prec + 30
  149. # Number of direct terms to sum before applying the Euler-Maclaurin
  150. # formula to the tail. TODO: choose more intelligently
  151. N = int(0.33*prec + 5)
  152. ONE = MPZ_ONE << wp
  153. # Euler-Maclaurin, step 1: sum log(k)/k**2 for k from 2 to N-1
  154. s = MPZ_ZERO
  155. for k in range(2, N):
  156. #print k, N
  157. s += log_int_fixed(k, wp) // k**2
  158. logN = log_int_fixed(N, wp)
  159. #logN = to_fixed(mpf_log(from_int(N), wp+20), wp)
  160. # E-M step 2: integral of log(x)/x**2 from N to inf
  161. s += (ONE + logN) // N
  162. # E-M step 3: endpoint correction term f(N)/2
  163. s += logN // (N**2 * 2)
  164. # E-M step 4: the series of derivatives
  165. pN = N**3
  166. a = 1
  167. b = -2
  168. j = 3
  169. fac = from_int(2)
  170. k = 1
  171. while 1:
  172. # D(2*k-1) * B(2*k) / fac(2*k) [D(n) = nth derivative]
  173. D = ((a << wp) + b*logN) // pN
  174. D = from_man_exp(D, -wp)
  175. B = mpf_bernoulli(2*k, wp)
  176. term = mpf_mul(B, D, wp)
  177. term = mpf_div(term, fac, wp)
  178. term = to_fixed(term, wp)
  179. if abs(term) < 100:
  180. break
  181. #if not k % 10:
  182. # print k, math.log(int(abs(term)), 10)
  183. s -= term
  184. # Advance derivative twice
  185. a, b, pN, j = b-a*j, -j*b, pN*N, j+1
  186. a, b, pN, j = b-a*j, -j*b, pN*N, j+1
  187. k += 1
  188. fac = mpf_mul_int(fac, (2*k)*(2*k-1), wp)
  189. # A = exp((6*s/pi**2 + log(2*pi) + euler)/12)
  190. pi = pi_fixed(wp)
  191. s *= 6
  192. s = (s << wp) // (pi**2 >> wp)
  193. s += euler_fixed(wp)
  194. s += to_fixed(mpf_log(from_man_exp(2*pi, -wp), wp), wp)
  195. s //= 12
  196. A = mpf_exp(from_man_exp(s, -wp), wp)
  197. return to_fixed(A, prec)
  198. # Apery's constant can be computed using the very rapidly convergent
  199. # series
  200. # oo
  201. # ___ 2 10
  202. # \ n 205 n + 250 n + 77 (n!)
  203. # zeta(3) = ) (-1) ------------------- ----------
  204. # /___ 64 5
  205. # n = 0 ((2n+1)!)
  206. @constant_memo
  207. def apery_fixed(prec):
  208. prec += 20
  209. d = MPZ_ONE << prec
  210. term = MPZ(77) << prec
  211. n = 1
  212. s = MPZ_ZERO
  213. while term:
  214. s += term
  215. d *= (n**10)
  216. d //= (((2*n+1)**5) * (2*n)**5)
  217. term = (-1)**n * (205*(n**2) + 250*n + 77) * d
  218. n += 1
  219. return s >> (20 + 6)
  220. """
  221. Euler's constant (gamma) is computed using the Brent-McMillan formula,
  222. gamma ~= I(n)/J(n) - log(n), where
  223. I(n) = sum_{k=0,1,2,...} (n**k / k!)**2 * H(k)
  224. J(n) = sum_{k=0,1,2,...} (n**k / k!)**2
  225. H(k) = 1 + 1/2 + 1/3 + ... + 1/k
  226. The error is bounded by O(exp(-4n)). Choosing n to be a power
  227. of two, 2**p, the logarithm becomes particularly easy to calculate.[1]
  228. We use the formulation of Algorithm 3.9 in [2] to make the summation
  229. more efficient.
  230. Reference:
  231. [1] Xavier Gourdon & Pascal Sebah, The Euler constant: gamma
  232. http://numbers.computation.free.fr/Constants/Gamma/gamma.pdf
  233. [2] Jonathan Borwein & David Bailey, Mathematics by Experiment,
  234. A K Peters, 2003
  235. """
  236. @constant_memo
  237. def euler_fixed(prec):
  238. extra = 30
  239. prec += extra
  240. # choose p such that exp(-4*(2**p)) < 2**-n
  241. p = int(math.log((prec/4) * math.log(2), 2)) + 1
  242. n = 2**p
  243. A = U = -p*ln2_fixed(prec)
  244. B = V = MPZ_ONE << prec
  245. k = 1
  246. while 1:
  247. B = B*n**2//k**2
  248. A = (A*n**2//k + B)//k
  249. U += A
  250. V += B
  251. if max(abs(A), abs(B)) < 100:
  252. break
  253. k += 1
  254. return (U<<(prec-extra))//V
  255. # Use zeta accelerated formulas for the Mertens and twin
  256. # prime constants; see
  257. # http://mathworld.wolfram.com/MertensConstant.html
  258. # http://mathworld.wolfram.com/TwinPrimesConstant.html
  259. @constant_memo
  260. def mertens_fixed(prec):
  261. wp = prec + 20
  262. m = 2
  263. s = mpf_euler(wp)
  264. while 1:
  265. t = mpf_zeta_int(m, wp)
  266. if t == fone:
  267. break
  268. t = mpf_log(t, wp)
  269. t = mpf_mul_int(t, moebius(m), wp)
  270. t = mpf_div(t, from_int(m), wp)
  271. s = mpf_add(s, t)
  272. m += 1
  273. return to_fixed(s, prec)
  274. @constant_memo
  275. def twinprime_fixed(prec):
  276. def I(n):
  277. return sum(moebius(d)<<(n//d) for d in xrange(1,n+1) if not n%d)//n
  278. wp = 2*prec + 30
  279. res = fone
  280. primes = [from_rational(1,p,wp) for p in [2,3,5,7]]
  281. ppowers = [mpf_mul(p,p,wp) for p in primes]
  282. n = 2
  283. while 1:
  284. a = mpf_zeta_int(n, wp)
  285. for i in range(4):
  286. a = mpf_mul(a, mpf_sub(fone, ppowers[i]), wp)
  287. ppowers[i] = mpf_mul(ppowers[i], primes[i], wp)
  288. a = mpf_pow_int(a, -I(n), wp)
  289. if mpf_pos(a, prec+10, 'n') == fone:
  290. break
  291. #from libmpf import to_str
  292. #print n, to_str(mpf_sub(fone, a), 6)
  293. res = mpf_mul(res, a, wp)
  294. n += 1
  295. res = mpf_mul(res, from_int(3*15*35), wp)
  296. res = mpf_div(res, from_int(4*16*36), wp)
  297. return to_fixed(res, prec)
  298. mpf_euler = def_mpf_constant(euler_fixed)
  299. mpf_apery = def_mpf_constant(apery_fixed)
  300. mpf_khinchin = def_mpf_constant(khinchin_fixed)
  301. mpf_glaisher = def_mpf_constant(glaisher_fixed)
  302. mpf_catalan = def_mpf_constant(catalan_fixed)
  303. mpf_mertens = def_mpf_constant(mertens_fixed)
  304. mpf_twinprime = def_mpf_constant(twinprime_fixed)
  305. #-----------------------------------------------------------------------#
  306. # #
  307. # Bernoulli numbers #
  308. # #
  309. #-----------------------------------------------------------------------#
  310. MAX_BERNOULLI_CACHE = 3000
  311. r"""
  312. Small Bernoulli numbers and factorials are used in numerous summations,
  313. so it is critical for speed that sequential computation is fast and that
  314. values are cached up to a fairly high threshold.
  315. On the other hand, we also want to support fast computation of isolated
  316. large numbers. Currently, no such acceleration is provided for integer
  317. factorials (though it is for large floating-point factorials, which are
  318. computed via gamma if the precision is low enough).
  319. For sequential computation of Bernoulli numbers, we use Ramanujan's formula
  320. / n + 3 \
  321. B = (A(n) - S(n)) / | |
  322. n \ n /
  323. where A(n) = (n+3)/3 when n = 0 or 2 (mod 6), A(n) = -(n+3)/6
  324. when n = 4 (mod 6), and
  325. [n/6]
  326. ___
  327. \ / n + 3 \
  328. S(n) = ) | | * B
  329. /___ \ n - 6*k / n-6*k
  330. k = 1
  331. For isolated large Bernoulli numbers, we use the Riemann zeta function
  332. to calculate a numerical value for B_n. The von Staudt-Clausen theorem
  333. can then be used to optionally find the exact value of the
  334. numerator and denominator.
  335. """
  336. bernoulli_cache = {}
  337. f3 = from_int(3)
  338. f6 = from_int(6)
  339. def bernoulli_size(n):
  340. """Accurately estimate the size of B_n (even n > 2 only)"""
  341. lgn = math.log(n,2)
  342. return int(2.326 + 0.5*lgn + n*(lgn - 4.094))
  343. BERNOULLI_PREC_CUTOFF = bernoulli_size(MAX_BERNOULLI_CACHE)
  344. def mpf_bernoulli(n, prec, rnd=None):
  345. """Computation of Bernoulli numbers (numerically)"""
  346. if n < 2:
  347. if n < 0:
  348. raise ValueError("Bernoulli numbers only defined for n >= 0")
  349. if n == 0:
  350. return fone
  351. if n == 1:
  352. return mpf_neg(fhalf)
  353. # For odd n > 1, the Bernoulli numbers are zero
  354. if n & 1:
  355. return fzero
  356. # If precision is extremely high, we can save time by computing
  357. # the Bernoulli number at a lower precision that is sufficient to
  358. # obtain the exact fraction, round to the exact fraction, and
  359. # convert the fraction back to an mpf value at the original precision
  360. if prec > BERNOULLI_PREC_CUTOFF and prec > bernoulli_size(n)*1.1 + 1000:
  361. p, q = bernfrac(n)
  362. return from_rational(p, q, prec, rnd or round_floor)
  363. if n > MAX_BERNOULLI_CACHE:
  364. return mpf_bernoulli_huge(n, prec, rnd)
  365. wp = prec + 30
  366. # Reuse nearby precisions
  367. wp += 32 - (prec & 31)
  368. cached = bernoulli_cache.get(wp)
  369. if cached:
  370. numbers, state = cached
  371. if n in numbers:
  372. if not rnd:
  373. return numbers[n]
  374. return mpf_pos(numbers[n], prec, rnd)
  375. m, bin, bin1 = state
  376. if n - m > 10:
  377. return mpf_bernoulli_huge(n, prec, rnd)
  378. else:
  379. if n > 10:
  380. return mpf_bernoulli_huge(n, prec, rnd)
  381. numbers = {0:fone}
  382. m, bin, bin1 = state = [2, MPZ(10), MPZ_ONE]
  383. bernoulli_cache[wp] = (numbers, state)
  384. while m <= n:
  385. #print m
  386. case = m % 6
  387. # Accurately estimate size of B_m so we can use
  388. # fixed point math without using too much precision
  389. szbm = bernoulli_size(m)
  390. s = 0
  391. sexp = max(0, szbm) - wp
  392. if m < 6:
  393. a = MPZ_ZERO
  394. else:
  395. a = bin1
  396. for j in xrange(1, m//6+1):
  397. usign, uman, uexp, ubc = u = numbers[m-6*j]
  398. if usign:
  399. uman = -uman
  400. s += lshift(a*uman, uexp-sexp)
  401. # Update inner binomial coefficient
  402. j6 = 6*j
  403. a *= ((m-5-j6)*(m-4-j6)*(m-3-j6)*(m-2-j6)*(m-1-j6)*(m-j6))
  404. a //= ((4+j6)*(5+j6)*(6+j6)*(7+j6)*(8+j6)*(9+j6))
  405. if case == 0: b = mpf_rdiv_int(m+3, f3, wp)
  406. if case == 2: b = mpf_rdiv_int(m+3, f3, wp)
  407. if case == 4: b = mpf_rdiv_int(-m-3, f6, wp)
  408. s = from_man_exp(s, sexp, wp)
  409. b = mpf_div(mpf_sub(b, s, wp), from_int(bin), wp)
  410. numbers[m] = b
  411. m += 2
  412. # Update outer binomial coefficient
  413. bin = bin * ((m+2)*(m+3)) // (m*(m-1))
  414. if m > 6:
  415. bin1 = bin1 * ((2+m)*(3+m)) // ((m-7)*(m-6))
  416. state[:] = [m, bin, bin1]
  417. return numbers[n]
  418. def mpf_bernoulli_huge(n, prec, rnd=None):
  419. wp = prec + 10
  420. piprec = wp + int(math.log(n,2))
  421. v = mpf_gamma_int(n+1, wp)
  422. v = mpf_mul(v, mpf_zeta_int(n, wp), wp)
  423. v = mpf_mul(v, mpf_pow_int(mpf_pi(piprec), -n, wp))
  424. v = mpf_shift(v, 1-n)
  425. if not n & 3:
  426. v = mpf_neg(v)
  427. return mpf_pos(v, prec, rnd or round_fast)
  428. def bernfrac(n):
  429. r"""
  430. Returns a tuple of integers `(p, q)` such that `p/q = B_n` exactly,
  431. where `B_n` denotes the `n`-th Bernoulli number. The fraction is
  432. always reduced to lowest terms. Note that for `n > 1` and `n` odd,
  433. `B_n = 0`, and `(0, 1)` is returned.
  434. **Examples**
  435. The first few Bernoulli numbers are exactly::
  436. >>> from mpmath import *
  437. >>> for n in range(15):
  438. ... p, q = bernfrac(n)
  439. ... print("%s %s/%s" % (n, p, q))
  440. ...
  441. 0 1/1
  442. 1 -1/2
  443. 2 1/6
  444. 3 0/1
  445. 4 -1/30
  446. 5 0/1
  447. 6 1/42
  448. 7 0/1
  449. 8 -1/30
  450. 9 0/1
  451. 10 5/66
  452. 11 0/1
  453. 12 -691/2730
  454. 13 0/1
  455. 14 7/6
  456. This function works for arbitrarily large `n`::
  457. >>> p, q = bernfrac(10**4)
  458. >>> print(q)
  459. 2338224387510
  460. >>> print(len(str(p)))
  461. 27692
  462. >>> mp.dps = 15
  463. >>> print(mpf(p) / q)
  464. -9.04942396360948e+27677
  465. >>> print(bernoulli(10**4))
  466. -9.04942396360948e+27677
  467. .. note ::
  468. :func:`~mpmath.bernoulli` computes a floating-point approximation
  469. directly, without computing the exact fraction first.
  470. This is much faster for large `n`.
  471. **Algorithm**
  472. :func:`~mpmath.bernfrac` works by computing the value of `B_n` numerically
  473. and then using the von Staudt-Clausen theorem [1] to reconstruct
  474. the exact fraction. For large `n`, this is significantly faster than
  475. computing `B_1, B_2, \ldots, B_2` recursively with exact arithmetic.
  476. The implementation has been tested for `n = 10^m` up to `m = 6`.
  477. In practice, :func:`~mpmath.bernfrac` appears to be about three times
  478. slower than the specialized program calcbn.exe [2]
  479. **References**
  480. 1. MathWorld, von Staudt-Clausen Theorem:
  481. http://mathworld.wolfram.com/vonStaudt-ClausenTheorem.html
  482. 2. The Bernoulli Number Page:
  483. http://www.bernoulli.org/
  484. """
  485. n = int(n)
  486. if n < 3:
  487. return [(1, 1), (-1, 2), (1, 6)][n]
  488. if n & 1:
  489. return (0, 1)
  490. q = 1
  491. for k in list_primes(n+1):
  492. if not (n % (k-1)):
  493. q *= k
  494. prec = bernoulli_size(n) + int(math.log(q,2)) + 20
  495. b = mpf_bernoulli(n, prec)
  496. p = mpf_mul(b, from_int(q))
  497. pint = to_int(p, round_nearest)
  498. return (pint, q)
  499. #-----------------------------------------------------------------------#
  500. # #
  501. # Polygamma functions #
  502. # #
  503. #-----------------------------------------------------------------------#
  504. r"""
  505. For all polygamma (psi) functions, we use the Euler-Maclaurin summation
  506. formula. It looks slightly different in the m = 0 and m > 0 cases.
  507. For m = 0, we have
  508. oo
  509. ___ B
  510. (0) 1 \ 2 k -2 k
  511. psi (z) ~ log z + --- - ) ------ z
  512. 2 z /___ (2 k)!
  513. k = 1
  514. Experiment shows that the minimum term of the asymptotic series
  515. reaches 2^(-p) when Re(z) > 0.11*p. So we simply use the recurrence
  516. for psi (equivalent, in fact, to summing to the first few terms
  517. directly before applying E-M) to obtain z large enough.
  518. Since, very crudely, log z ~= 1 for Re(z) > 1, we can use
  519. fixed-point arithmetic (if z is extremely large, log(z) itself
  520. is a sufficient approximation, so we can stop there already).
  521. For Re(z) << 0, we could use recurrence, but this is of course
  522. inefficient for large negative z, so there we use the
  523. reflection formula instead.
  524. For m > 0, we have
  525. N - 1
  526. ___
  527. ~~~(m) [ \ 1 ] 1 1
  528. psi (z) ~ [ ) -------- ] + ---------- + -------- +
  529. [ /___ m+1 ] m+1 m
  530. k = 1 (z+k) ] 2 (z+N) m (z+N)
  531. oo
  532. ___ B
  533. \ 2 k (m+1) (m+2) ... (m+2k-1)
  534. + ) ------ ------------------------
  535. /___ (2 k)! m + 2 k
  536. k = 1 (z+N)
  537. where ~~~ denotes the function rescaled by 1/((-1)^(m+1) m!).
  538. Here again N is chosen to make z+N large enough for the minimum
  539. term in the last series to become smaller than eps.
  540. TODO: the current estimation of N for m > 0 is *very suboptimal*.
  541. TODO: implement the reflection formula for m > 0, Re(z) << 0.
  542. It is generally a combination of multiple cotangents. Need to
  543. figure out a reasonably simple way to generate these formulas
  544. on the fly.
  545. TODO: maybe use exact algorithms to compute psi for integral
  546. and certain rational arguments, as this can be much more
  547. efficient. (On the other hand, the availability of these
  548. special values provides a convenient way to test the general
  549. algorithm.)
  550. """
  551. # Harmonic numbers are just shifted digamma functions
  552. # We should calculate these exactly when x is an integer
  553. # and when doing so is faster.
  554. def mpf_harmonic(x, prec, rnd):
  555. if x in (fzero, fnan, finf):
  556. return x
  557. a = mpf_psi0(mpf_add(fone, x, prec+5), prec)
  558. return mpf_add(a, mpf_euler(prec+5, rnd), prec, rnd)
  559. def mpc_harmonic(z, prec, rnd):
  560. if z[1] == fzero:
  561. return (mpf_harmonic(z[0], prec, rnd), fzero)
  562. a = mpc_psi0(mpc_add_mpf(z, fone, prec+5), prec)
  563. return mpc_add_mpf(a, mpf_euler(prec+5, rnd), prec, rnd)
  564. def mpf_psi0(x, prec, rnd=round_fast):
  565. """
  566. Computation of the digamma function (psi function of order 0)
  567. of a real argument.
  568. """
  569. sign, man, exp, bc = x
  570. wp = prec + 10
  571. if not man:
  572. if x == finf: return x
  573. if x == fninf or x == fnan: return fnan
  574. if x == fzero or (exp >= 0 and sign):
  575. raise ValueError("polygamma pole")
  576. # Near 0 -- fixed-point arithmetic becomes bad
  577. if exp+bc < -5:
  578. v = mpf_psi0(mpf_add(x, fone, prec, rnd), prec, rnd)
  579. return mpf_sub(v, mpf_div(fone, x, wp, rnd), prec, rnd)
  580. # Reflection formula
  581. if sign and exp+bc > 3:
  582. c, s = mpf_cos_sin_pi(x, wp)
  583. q = mpf_mul(mpf_div(c, s, wp), mpf_pi(wp), wp)
  584. p = mpf_psi0(mpf_sub(fone, x, wp), wp)
  585. return mpf_sub(p, q, prec, rnd)
  586. # The logarithmic term is accurate enough
  587. if (not sign) and bc + exp > wp:
  588. return mpf_log(mpf_sub(x, fone, wp), prec, rnd)
  589. # Initial recurrence to obtain a large enough x
  590. m = to_int(x)
  591. n = int(0.11*wp) + 2
  592. s = MPZ_ZERO
  593. x = to_fixed(x, wp)
  594. one = MPZ_ONE << wp
  595. if m < n:
  596. for k in xrange(m, n):
  597. s -= (one << wp) // x
  598. x += one
  599. x -= one
  600. # Logarithmic term
  601. s += to_fixed(mpf_log(from_man_exp(x, -wp, wp), wp), wp)
  602. # Endpoint term in Euler-Maclaurin expansion
  603. s += (one << wp) // (2*x)
  604. # Euler-Maclaurin remainder sum
  605. x2 = (x*x) >> wp
  606. t = one
  607. prev = 0
  608. k = 1
  609. while 1:
  610. t = (t*x2) >> wp
  611. bsign, bman, bexp, bbc = mpf_bernoulli(2*k, wp)
  612. offset = (bexp + 2*wp)
  613. if offset >= 0: term = (bman << offset) // (t*(2*k))
  614. else: term = (bman >> (-offset)) // (t*(2*k))
  615. if k & 1: s -= term
  616. else: s += term
  617. if k > 2 and term >= prev:
  618. break
  619. prev = term
  620. k += 1
  621. return from_man_exp(s, -wp, wp, rnd)
  622. def mpc_psi0(z, prec, rnd=round_fast):
  623. """
  624. Computation of the digamma function (psi function of order 0)
  625. of a complex argument.
  626. """
  627. re, im = z
  628. # Fall back to the real case
  629. if im == fzero:
  630. return (mpf_psi0(re, prec, rnd), fzero)
  631. wp = prec + 20
  632. sign, man, exp, bc = re
  633. # Reflection formula
  634. if sign and exp+bc > 3:
  635. c = mpc_cos_pi(z, wp)
  636. s = mpc_sin_pi(z, wp)
  637. q = mpc_mul_mpf(mpc_div(c, s, wp), mpf_pi(wp), wp)
  638. p = mpc_psi0(mpc_sub(mpc_one, z, wp), wp)
  639. return mpc_sub(p, q, prec, rnd)
  640. # Just the logarithmic term
  641. if (not sign) and bc + exp > wp:
  642. return mpc_log(mpc_sub(z, mpc_one, wp), prec, rnd)
  643. # Initial recurrence to obtain a large enough z
  644. w = to_int(re)
  645. n = int(0.11*wp) + 2
  646. s = mpc_zero
  647. if w < n:
  648. for k in xrange(w, n):
  649. s = mpc_sub(s, mpc_reciprocal(z, wp), wp)
  650. z = mpc_add_mpf(z, fone, wp)
  651. z = mpc_sub(z, mpc_one, wp)
  652. # Logarithmic and endpoint term
  653. s = mpc_add(s, mpc_log(z, wp), wp)
  654. s = mpc_add(s, mpc_div(mpc_half, z, wp), wp)
  655. # Euler-Maclaurin remainder sum
  656. z2 = mpc_square(z, wp)
  657. t = mpc_one
  658. prev = mpc_zero
  659. k = 1
  660. eps = mpf_shift(fone, -wp+2)
  661. while 1:
  662. t = mpc_mul(t, z2, wp)
  663. bern = mpf_bernoulli(2*k, wp)
  664. term = mpc_mpf_div(bern, mpc_mul_int(t, 2*k, wp), wp)
  665. s = mpc_sub(s, term, wp)
  666. szterm = mpc_abs(term, 10)
  667. if k > 2 and mpf_le(szterm, eps):
  668. break
  669. prev = term
  670. k += 1
  671. return s
  672. # Currently unoptimized
  673. def mpf_psi(m, x, prec, rnd=round_fast):
  674. """
  675. Computation of the polygamma function of arbitrary integer order
  676. m >= 0, for a real argument x.
  677. """
  678. if m == 0:
  679. return mpf_psi0(x, prec, rnd=round_fast)
  680. return mpc_psi(m, (x, fzero), prec, rnd)[0]
  681. def mpc_psi(m, z, prec, rnd=round_fast):
  682. """
  683. Computation of the polygamma function of arbitrary integer order
  684. m >= 0, for a complex argument z.
  685. """
  686. if m == 0:
  687. return mpc_psi0(z, prec, rnd)
  688. re, im = z
  689. wp = prec + 20
  690. sign, man, exp, bc = re
  691. if not im[1]:
  692. if im in (finf, fninf, fnan):
  693. return (fnan, fnan)
  694. if not man:
  695. if re == finf and im == fzero:
  696. return (fzero, fzero)
  697. if re == fnan:
  698. return (fnan, fnan)
  699. # Recurrence
  700. w = to_int(re)
  701. n = int(0.4*wp + 4*m)
  702. s = mpc_zero
  703. if w < n:
  704. for k in xrange(w, n):
  705. t = mpc_pow_int(z, -m-1, wp)
  706. s = mpc_add(s, t, wp)
  707. z = mpc_add_mpf(z, fone, wp)
  708. zm = mpc_pow_int(z, -m, wp)
  709. z2 = mpc_pow_int(z, -2, wp)
  710. # 1/m*(z+N)^m
  711. integral_term = mpc_div_mpf(zm, from_int(m), wp)
  712. s = mpc_add(s, integral_term, wp)
  713. # 1/2*(z+N)^(-(m+1))
  714. s = mpc_add(s, mpc_mul_mpf(mpc_div(zm, z, wp), fhalf, wp), wp)
  715. a = m + 1
  716. b = 2
  717. k = 1
  718. # Important: we want to sum up to the *relative* error,
  719. # not the absolute error, because psi^(m)(z) might be tiny
  720. magn = mpc_abs(s, 10)
  721. magn = magn[2]+magn[3]
  722. eps = mpf_shift(fone, magn-wp+2)
  723. while 1:
  724. zm = mpc_mul(zm, z2, wp)
  725. bern = mpf_bernoulli(2*k, wp)
  726. scal = mpf_mul_int(bern, a, wp)
  727. scal = mpf_div(scal, from_int(b), wp)
  728. term = mpc_mul_mpf(zm, scal, wp)
  729. s = mpc_add(s, term, wp)
  730. szterm = mpc_abs(term, 10)
  731. if k > 2 and mpf_le(szterm, eps):
  732. break
  733. #print k, to_str(szterm, 10), to_str(eps, 10)
  734. a *= (m+2*k)*(m+2*k+1)
  735. b *= (2*k+1)*(2*k+2)
  736. k += 1
  737. # Scale and sign factor
  738. v = mpc_mul_mpf(s, mpf_gamma(from_int(m+1), wp), prec, rnd)
  739. if not (m & 1):
  740. v = mpf_neg(v[0]), mpf_neg(v[1])
  741. return v
  742. #-----------------------------------------------------------------------#
  743. # #
  744. # Riemann zeta function #
  745. # #
  746. #-----------------------------------------------------------------------#
  747. r"""
  748. We use zeta(s) = eta(s) / (1 - 2**(1-s)) and Borwein's approximation
  749. n-1
  750. ___ k
  751. -1 \ (-1) (d_k - d_n)
  752. eta(s) ~= ---- ) ------------------
  753. d_n /___ s
  754. k = 0 (k + 1)
  755. where
  756. k
  757. ___ i
  758. \ (n + i - 1)! 4
  759. d_k = n ) ---------------.
  760. /___ (n - i)! (2i)!
  761. i = 0
  762. If s = a + b*I, the absolute error for eta(s) is bounded by
  763. 3 (1 + 2|b|)
  764. ------------ * exp(|b| pi/2)
  765. n
  766. (3+sqrt(8))
  767. Disregarding the linear term, we have approximately,
  768. log(err) ~= log(exp(1.58*|b|)) - log(5.8**n)
  769. log(err) ~= 1.58*|b| - log(5.8)*n
  770. log(err) ~= 1.58*|b| - 1.76*n
  771. log2(err) ~= 2.28*|b| - 2.54*n
  772. So for p bits, we should choose n > (p + 2.28*|b|) / 2.54.
  773. References:
  774. -----------
  775. Peter Borwein, "An Efficient Algorithm for the Riemann Zeta Function"
  776. http://www.cecm.sfu.ca/personal/pborwein/PAPERS/P117.ps
  777. http://en.wikipedia.org/wiki/Dirichlet_eta_function
  778. """
  779. borwein_cache = {}
  780. def borwein_coefficients(n):
  781. if n in borwein_cache:
  782. return borwein_cache[n]
  783. ds = [MPZ_ZERO] * (n+1)
  784. d = MPZ_ONE
  785. s = ds[0] = MPZ_ONE
  786. for i in range(1, n+1):
  787. d = d * 4 * (n+i-1) * (n-i+1)
  788. d //= ((2*i) * ((2*i)-1))
  789. s += d
  790. ds[i] = s
  791. borwein_cache[n] = ds
  792. return ds
  793. ZETA_INT_CACHE_MAX_PREC = 1000
  794. zeta_int_cache = {}
  795. def mpf_zeta_int(s, prec, rnd=round_fast):
  796. """
  797. Optimized computation of zeta(s) for an integer s.
  798. """
  799. wp = prec + 20
  800. s = int(s)
  801. if s in zeta_int_cache and zeta_int_cache[s][0] >= wp:
  802. return mpf_pos(zeta_int_cache[s][1], prec, rnd)
  803. if s < 2:
  804. if s == 1:
  805. raise ValueError("zeta(1) pole")
  806. if not s:
  807. return mpf_neg(fhalf)
  808. return mpf_div(mpf_bernoulli(-s+1, wp), from_int(s-1), prec, rnd)
  809. # 2^-s term vanishes?
  810. if s >= wp:
  811. return mpf_perturb(fone, 0, prec, rnd)
  812. # 5^-s term vanishes?
  813. elif s >= wp*0.431:
  814. t = one = 1 << wp
  815. t += 1 << (wp - s)
  816. t += one // (MPZ_THREE ** s)
  817. t += 1 << max(0, wp - s*2)
  818. return from_man_exp(t, -wp, prec, rnd)
  819. else:
  820. # Fast enough to sum directly?
  821. # Even better, we use the Euler product (idea stolen from pari)
  822. m = (float(wp)/(s-1) + 1)
  823. if m < 30:
  824. needed_terms = int(2.0**m + 1)
  825. if needed_terms < int(wp/2.54 + 5) / 10:
  826. t = fone
  827. for k in list_primes(needed_terms):
  828. #print k, needed_terms
  829. powprec = int(wp - s*math.log(k,2))
  830. if powprec < 2:
  831. break
  832. a = mpf_sub(fone, mpf_pow_int(from_int(k), -s, powprec), wp)
  833. t = mpf_mul(t, a, wp)
  834. return mpf_div(fone, t, wp)
  835. # Use Borwein's algorithm
  836. n = int(wp/2.54 + 5)
  837. d = borwein_coefficients(n)
  838. t = MPZ_ZERO
  839. s = MPZ(s)
  840. for k in xrange(n):
  841. t += (((-1)**k * (d[k] - d[n])) << wp) // (k+1)**s
  842. t = (t << wp) // (-d[n])
  843. t = (t << wp) // ((1 << wp) - (1 << (wp+1-s)))
  844. if (s in zeta_int_cache and zeta_int_cache[s][0] < wp) or (s not in zeta_int_cache):
  845. zeta_int_cache[s] = (wp, from_man_exp(t, -wp-wp))
  846. return from_man_exp(t, -wp-wp, prec, rnd)
  847. def mpf_zeta(s, prec, rnd=round_fast, alt=0):
  848. sign, man, exp, bc = s
  849. if not man:
  850. if s == fzero:
  851. if alt:
  852. return fhalf
  853. else:
  854. return mpf_neg(fhalf)
  855. if s == finf:
  856. return fone
  857. return fnan
  858. wp = prec + 20
  859. # First term vanishes?
  860. if (not sign) and (exp + bc > (math.log(wp,2) + 2)):
  861. return mpf_perturb(fone, alt, prec, rnd)
  862. # Optimize for integer arguments
  863. elif exp >= 0:
  864. if alt:
  865. if s == fone:
  866. return mpf_ln2(prec, rnd)
  867. z = mpf_zeta_int(to_int(s), wp, negative_rnd[rnd])
  868. q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)
  869. return mpf_mul(z, q, prec, rnd)
  870. else:
  871. return mpf_zeta_int(to_int(s), prec, rnd)
  872. # Negative: use the reflection formula
  873. # Borwein only proves the accuracy bound for x >= 1/2. However, based on
  874. # tests, the accuracy without reflection is quite good even some distance
  875. # to the left of 1/2. XXX: verify this.
  876. if sign:
  877. # XXX: could use the separate refl. formula for Dirichlet eta
  878. if alt:
  879. q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)
  880. return mpf_mul(mpf_zeta(s, wp), q, prec, rnd)
  881. # XXX: -1 should be done exactly
  882. y = mpf_sub(fone, s, 10*wp)
  883. a = mpf_gamma(y, wp)
  884. b = mpf_zeta(y, wp)
  885. c = mpf_sin_pi(mpf_shift(s, -1), wp)
  886. wp2 = wp + max(0,exp+bc)
  887. pi = mpf_pi(wp+wp2)
  888. d = mpf_div(mpf_pow(mpf_shift(pi, 1), s, wp2), pi, wp2)
  889. return mpf_mul(a,mpf_mul(b,mpf_mul(c,d,wp),wp),prec,rnd)
  890. # Near pole
  891. r = mpf_sub(fone, s, wp)
  892. asign, aman, aexp, abc = mpf_abs(r)
  893. pole_dist = -2*(aexp+abc)
  894. if pole_dist > wp:
  895. if alt:
  896. return mpf_ln2(prec, rnd)
  897. else:
  898. q = mpf_neg(mpf_div(fone, r, wp))
  899. return mpf_add(q, mpf_euler(wp), prec, rnd)
  900. else:
  901. wp += max(0, pole_dist)
  902. t = MPZ_ZERO
  903. #wp += 16 - (prec & 15)
  904. # Use Borwein's algorithm
  905. n = int(wp/2.54 + 5)
  906. d = borwein_coefficients(n)
  907. t = MPZ_ZERO
  908. sf = to_fixed(s, wp)
  909. ln2 = ln2_fixed(wp)
  910. for k in xrange(n):
  911. u = (-sf*log_int_fixed(k+1, wp, ln2)) >> wp
  912. #esign, eman, eexp, ebc = mpf_exp(u, wp)
  913. #offset = eexp + wp
  914. #if offset >= 0:
  915. # w = ((d[k] - d[n]) * eman) << offset
  916. #else:
  917. # w = ((d[k] - d[n]) * eman) >> (-offset)
  918. eman = exp_fixed(u, wp, ln2)
  919. w = (d[k] - d[n]) * eman
  920. if k & 1:
  921. t -= w
  922. else:
  923. t += w
  924. t = t // (-d[n])
  925. t = from_man_exp(t, -wp, wp)
  926. if alt:
  927. return mpf_pos(t, prec, rnd)
  928. else:
  929. q = mpf_sub(fone, mpf_pow(ftwo, mpf_sub(fone, s, wp), wp), wp)
  930. return mpf_div(t, q, prec, rnd)
  931. def mpc_zeta(s, prec, rnd=round_fast, alt=0, force=False):
  932. re, im = s
  933. if im == fzero:
  934. return mpf_zeta(re, prec, rnd, alt), fzero
  935. # slow for large s
  936. if (not force) and mpf_gt(mpc_abs(s, 10), from_int(prec)):
  937. raise NotImplementedError
  938. wp = prec + 20
  939. # Near pole
  940. r = mpc_sub(mpc_one, s, wp)
  941. asign, aman, aexp, abc = mpc_abs(r, 10)
  942. pole_dist = -2*(aexp+abc)
  943. if pole_dist > wp:
  944. if alt:
  945. q = mpf_ln2(wp)
  946. y = mpf_mul(q, mpf_euler(wp), wp)
  947. g = mpf_shift(mpf_mul(q, q, wp), -1)
  948. g = mpf_sub(y, g)
  949. z = mpc_mul_mpf(r, mpf_neg(g), wp)
  950. z = mpc_add_mpf(z, q, wp)
  951. return mpc_pos(z, prec, rnd)
  952. else:
  953. q = mpc_neg(mpc_div(mpc_one, r, wp))
  954. q = mpc_add_mpf(q, mpf_euler(wp), wp)
  955. return mpc_pos(q, prec, rnd)
  956. else:
  957. wp += max(0, pole_dist)
  958. # Reflection formula. To be rigorous, we should reflect to the left of
  959. # re = 1/2 (see comments for mpf_zeta), but this leads to unnecessary
  960. # slowdown for interesting values of s
  961. if mpf_lt(re, fzero):
  962. # XXX: could use the separate refl. formula for Dirichlet eta
  963. if alt:
  964. q = mpc_sub(mpc_one, mpc_pow(mpc_two, mpc_sub(mpc_one, s, wp),
  965. wp), wp)
  966. return mpc_mul(mpc_zeta(s, wp), q, prec, rnd)
  967. # XXX: -1 should be done exactly
  968. y = mpc_sub(mpc_one, s, 10*wp)
  969. a = mpc_gamma(y, wp)
  970. b = mpc_zeta(y, wp)
  971. c = mpc_sin_pi(mpc_shift(s, -1), wp)
  972. rsign, rman, rexp, rbc = re
  973. isign, iman, iexp, ibc = im
  974. mag = max(rexp+rbc, iexp+ibc)
  975. wp2 = wp + max(0, mag)
  976. pi = mpf_pi(wp+wp2)
  977. pi2 = (mpf_shift(pi, 1), fzero)
  978. d = mpc_div_mpf(mpc_pow(pi2, s, wp2), pi, wp2)
  979. return mpc_mul(a,mpc_mul(b,mpc_mul(c,d,wp),wp),prec,rnd)
  980. n = int(wp/2.54 + 5)
  981. n += int(0.9*abs(to_int(im)))
  982. d = borwein_coefficients(n)
  983. ref = to_fixed(re, wp)
  984. imf = to_fixed(im, wp)
  985. tre = MPZ_ZERO
  986. tim = MPZ_ZERO
  987. one = MPZ_ONE << wp
  988. one_2wp = MPZ_ONE << (2*wp)
  989. critical_line = re == fhalf
  990. ln2 = ln2_fixed(wp)
  991. pi2 = pi_fixed(wp-1)
  992. wp2 = wp+wp
  993. for k in xrange(n):
  994. log = log_int_fixed(k+1, wp, ln2)
  995. # A square root is much cheaper than an exp
  996. if critical_line:
  997. w = one_2wp // isqrt_fast((k+1) << wp2)
  998. else:
  999. w = exp_fixed((-ref*log) >> wp, wp)
  1000. if k & 1:
  1001. w *= (d[n] - d[k])
  1002. else:
  1003. w *= (d[k] - d[n])
  1004. wre, wim = cos_sin_fixed((-imf*log)>>wp, wp, pi2)
  1005. tre += (w * wre) >> wp
  1006. tim += (w * wim) >> wp
  1007. tre //= (-d[n])
  1008. tim //= (-d[n])
  1009. tre = from_man_exp(tre, -wp, wp)
  1010. tim = from_man_exp(tim, -wp, wp)
  1011. if alt:
  1012. return mpc_pos((tre, tim), prec, rnd)
  1013. else:
  1014. q = mpc_sub(mpc_one, mpc_pow(mpc_two, r, wp), wp)
  1015. return mpc_div((tre, tim), q, prec, rnd)
  1016. def mpf_altzeta(s, prec, rnd=round_fast):
  1017. return mpf_zeta(s, prec, rnd, 1)
  1018. def mpc_altzeta(s, prec, rnd=round_fast):
  1019. return mpc_zeta(s, prec, rnd, 1)
  1020. # Not optimized currently
  1021. mpf_zetasum = None
  1022. def pow_fixed(x, n, wp):
  1023. if n == 1:
  1024. return x
  1025. y = MPZ_ONE << wp
  1026. while n:
  1027. if n & 1:
  1028. y = (y*x) >> wp
  1029. n -= 1
  1030. x = (x*x) >> wp
  1031. n //= 2
  1032. return y
  1033. # TODO: optimize / cleanup interface / unify with list_primes
  1034. sieve_cache = []
  1035. primes_cache = []
  1036. mult_cache = []
  1037. def primesieve(n):
  1038. global sieve_cache, primes_cache, mult_cache
  1039. if n < len(sieve_cache):
  1040. sieve = sieve_cache#[:n+1]
  1041. primes = primes_cache[:primes_cache.index(max(sieve))+1]
  1042. mult = mult_cache#[:n+1]
  1043. return sieve, primes, mult
  1044. sieve = [0] * (n+1)
  1045. mult = [0] * (n+1)
  1046. primes = list_primes(n)
  1047. for p in primes:
  1048. #sieve[p::p] = p
  1049. for k in xrange(p,n+1,p):
  1050. sieve[k] = p
  1051. for i, p in enumerate(sieve):
  1052. if i >= 2:
  1053. m = 1
  1054. n = i // p
  1055. while not n % p:
  1056. n //= p
  1057. m += 1
  1058. mult[i] = m
  1059. sieve_cache = sieve
  1060. primes_cache = primes
  1061. mult_cache = mult
  1062. return sieve, primes, mult
  1063. def zetasum_sieved(critical_line, sre, sim, a, n, wp):
  1064. if a < 1:
  1065. raise ValueError("a cannot be less than 1")
  1066. sieve, primes, mult = primesieve(a+n)
  1067. basic_powers = {}
  1068. one = MPZ_ONE << wp
  1069. one_2wp = MPZ_ONE << (2*wp)
  1070. wp2 = wp+wp
  1071. ln2 = ln2_fixed(wp)
  1072. pi2 = pi_fixed(wp-1)
  1073. for p in primes:
  1074. if p*2 > a+n:
  1075. break
  1076. log = log_int_fixed(p, wp, ln2)
  1077. cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)
  1078. if critical_line:
  1079. u = one_2wp // isqrt_fast(p<<wp2)
  1080. else:
  1081. u = exp_fixed((-sre*log)>>wp, wp)
  1082. pre = (u*cos) >> wp
  1083. pim = (u*sin) >> wp
  1084. basic_powers[p] = [(pre, pim)]
  1085. tre, tim = pre, pim
  1086. for m in range(1,int(math.log(a+n,p)+0.01)+1):
  1087. tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp)
  1088. basic_powers[p].append((tre,tim))
  1089. xre = MPZ_ZERO
  1090. xim = MPZ_ZERO
  1091. if a == 1:
  1092. xre += one
  1093. aa = max(a,2)
  1094. for k in xrange(aa, a+n+1):
  1095. p = sieve[k]
  1096. if p in basic_powers:
  1097. m = mult[k]
  1098. tre, tim = basic_powers[p][m-1]
  1099. while 1:
  1100. k //= p**m
  1101. if k == 1:
  1102. break
  1103. p = sieve[k]
  1104. m = mult[k]
  1105. pre, pim = basic_powers[p][m-1]
  1106. tre, tim = ((pre*tre-pim*tim)>>wp), ((pim*tre+pre*tim)>>wp)
  1107. else:
  1108. log = log_int_fixed(k, wp, ln2)
  1109. cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)
  1110. if critical_line:
  1111. u = one_2wp // isqrt_fast(k<<wp2)
  1112. else:
  1113. u = exp_fixed((-sre*log)>>wp, wp)
  1114. tre = (u*cos) >> wp
  1115. tim = (u*sin) >> wp
  1116. xre += tre
  1117. xim += tim
  1118. return xre, xim
  1119. # Set to something large to disable
  1120. ZETASUM_SIEVE_CUTOFF = 10
  1121. def mpc_zetasum(s, a, n, derivatives, reflect, prec):
  1122. """
  1123. Fast version of mp._zetasum, assuming s = complex, a = integer.
  1124. """
  1125. wp = prec + 10
  1126. derivatives = list(derivatives)
  1127. have_derivatives = derivatives != [0]
  1128. have_one_derivative = len(derivatives) == 1
  1129. # parse s
  1130. sre, sim = s
  1131. critical_line = (sre == fhalf)
  1132. sre = to_fixed(sre, wp)
  1133. sim = to_fixed(sim, wp)
  1134. if a > 0 and n > ZETASUM_SIEVE_CUTOFF and not have_derivatives \
  1135. and not reflect and (n < 4e7 or sys.maxsize > 2**32):
  1136. re, im = zetasum_sieved(critical_line, sre, sim, a, n, wp)
  1137. xs = [(from_man_exp(re, -wp, prec, 'n'), from_man_exp(im, -wp, prec, 'n'))]
  1138. return xs, []
  1139. maxd = max(derivatives)
  1140. if not have_one_derivative:
  1141. derivatives = range(maxd+1)
  1142. # x_d = 0, y_d = 0
  1143. xre = [MPZ_ZERO for d in derivatives]
  1144. xim = [MPZ_ZERO for d in derivatives]
  1145. if reflect:
  1146. yre = [MPZ_ZERO for d in derivatives]
  1147. yim = [MPZ_ZERO for d in derivatives]
  1148. else:
  1149. yre = yim = []
  1150. one = MPZ_ONE << wp
  1151. one_2wp = MPZ_ONE << (2*wp)
  1152. ln2 = ln2_fixed(wp)
  1153. pi2 = pi_fixed(wp-1)
  1154. wp2 = wp+wp
  1155. for w in xrange(a, a+n+1):
  1156. log = log_int_fixed(w, wp, ln2)
  1157. cos, sin = cos_sin_fixed((-sim*log)>>wp, wp, pi2)
  1158. if critical_line:
  1159. u = one_2wp // isqrt_fast(w<<wp2)
  1160. else:
  1161. u = exp_fixed((-sre*log)>>wp, wp)
  1162. xterm_re = (u * cos) >> wp
  1163. xterm_im = (u * sin) >> wp
  1164. if reflect:
  1165. reciprocal = (one_2wp // (u*w))
  1166. yterm_re = (reciprocal * cos) >> wp
  1167. yterm_im = (reciprocal * sin) >> wp
  1168. if have_derivatives:
  1169. if have_one_derivative:
  1170. log = pow_fixed(log, maxd, wp)
  1171. xre[0] += (xterm_re * log) >> wp
  1172. xim[0] += (xterm_im * log) >> wp
  1173. if reflect:
  1174. yre[0] += (yterm_re * log) >> wp
  1175. yim[0] += (yterm_im * log) >> wp
  1176. else:
  1177. t = MPZ_ONE << wp
  1178. for d in derivatives:
  1179. xre[d] += (xterm_re * t) >> wp
  1180. xim[d] += (xterm_im * t) >> wp
  1181. if reflect:
  1182. yre[d] += (yterm_re * t) >> wp
  1183. yim[d] += (yterm_im * t) >> wp
  1184. t = (t * log) >> wp
  1185. else:
  1186. xre[0] += xterm_re
  1187. xim[0] += xterm_im
  1188. if reflect:
  1189. yre[0] += yterm_re
  1190. yim[0] += yterm_im
  1191. if have_derivatives:
  1192. if have_one_derivative:
  1193. if maxd % 2:
  1194. xre[0] = -xre[0]
  1195. xim[0] = -xim[0]
  1196. if reflect:
  1197. yre[0] = -yre[0]
  1198. yim[0] = -yim[0]
  1199. else:
  1200. xre = [(-1)**d * xre[d] for d in derivatives]
  1201. xim = [(-1)**d * xim[d] for d in derivatives]
  1202. if reflect:
  1203. yre = [(-1)**d * yre[d] for d in derivatives]
  1204. yim = [(-1)**d * yim[d] for d in derivatives]
  1205. xs = [(from_man_exp(xa, -wp, prec, 'n'), from_man_exp(xb, -wp, prec, 'n'))
  1206. for (xa, xb) in zip(xre, xim)]
  1207. ys = [(from_man_exp(ya, -wp, prec, 'n'), from_man_exp(yb, -wp, prec, 'n'))
  1208. for (ya, yb) in zip(yre, yim)]
  1209. return xs, ys
  1210. #-----------------------------------------------------------------------#
  1211. # #
  1212. # The gamma function (NEW IMPLEMENTATION) #
  1213. # #
  1214. #-----------------------------------------------------------------------#
  1215. # Higher means faster, but more precomputation time
  1216. MAX_GAMMA_TAYLOR_PREC = 5000
  1217. # Need to derive higher bounds for Taylor series to go higher
  1218. assert MAX_GAMMA_TAYLOR_PREC < 15000
  1219. # Use Stirling's series if abs(x) > beta*prec
  1220. # Important: must be large enough for convergence!
  1221. GAMMA_STIRLING_BETA = 0.2
  1222. SMALL_FACTORIAL_CACHE_SIZE = 150
  1223. gamma_taylor_cache = {}
  1224. gamma_stirling_cache = {}
  1225. small_factorial_cache = [from_int(ifac(n)) for \
  1226. n in range(SMALL_FACTORIAL_CACHE_SIZE+1)]
  1227. def zeta_array(N, prec):
  1228. """
  1229. zeta(n) = A * pi**n / n! + B
  1230. where A is a rational number (A = Bernoulli number
  1231. for n even) and B is an infinite sum over powers of exp(2*pi).
  1232. (B = 0 for n even).
  1233. TODO: this is currently only used for gamma, but could
  1234. be very useful elsewhere.
  1235. """
  1236. extra = 30
  1237. wp = prec+extra
  1238. zeta_values = [MPZ_ZERO] * (N+2)
  1239. pi = pi_fixed(wp)
  1240. # STEP 1:
  1241. one = MPZ_ONE << wp
  1242. zeta_values[0] = -one//2
  1243. f_2pi = mpf_shift(mpf_pi(wp),1)
  1244. exp_2pi_k = exp_2pi = mpf_exp(f_2pi, wp)
  1245. # Compute exponential series
  1246. # Store values of 1/(exp(2*pi*k)-1),
  1247. # exp(2*pi*k)/(exp(2*pi*k)-1)**2, 1/(exp(2*pi*k)-1)**2
  1248. # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2
  1249. exps3 = []
  1250. k = 1
  1251. while 1:
  1252. tp = wp - 9*k
  1253. if tp < 1:
  1254. break
  1255. # 1/(exp(2*pi*k-1)
  1256. q1 = mpf_div(fone, mpf_sub(exp_2pi_k, fone, tp), tp)
  1257. # pi*k*exp(2*pi*k)/(exp(2*pi*k)-1)**2
  1258. q2 = mpf_mul(exp_2pi_k, mpf_mul(q1,q1,tp), tp)
  1259. q1 = to_fixed(q1, wp)
  1260. q2 = to_fixed(q2, wp)
  1261. q2 = (k * q2 * pi) >> wp
  1262. exps3.append((q1, q2))
  1263. # Multiply for next round
  1264. exp_2pi_k = mpf_mul(exp_2pi_k, exp_2pi, wp)
  1265. k += 1
  1266. # Exponential sum
  1267. for n in xrange(3, N+1, 2):
  1268. s = MPZ_ZERO
  1269. k = 1
  1270. for e1, e2 in exps3:
  1271. if n%4 == 3:
  1272. t = e1 // k**n
  1273. else:
  1274. U = (n-1)//4
  1275. t = (e1 + e2//U) // k**n
  1276. if not t:
  1277. break
  1278. s += t
  1279. k += 1
  1280. zeta_values[n] = -2*s
  1281. # Even zeta values
  1282. B = [mpf_abs(mpf_bernoulli(k,wp)) for k in xrange(N+2)]
  1283. pi_pow = fpi = mpf_pow_int(mpf_shift(mpf_pi(wp), 1), 2, wp)
  1284. pi_pow = mpf_div(pi_pow, from_int(4), wp)
  1285. for n in xrange(2,N+2,2):
  1286. z = mpf_mul(B[n], pi_pow, wp)
  1287. zeta_values[n] = to_fixed(z, wp)
  1288. pi_pow = mpf_mul(pi_pow, fpi, wp)
  1289. pi_pow = mpf_div(pi_pow, from_int((n+1)*(n+2)), wp)
  1290. # Zeta sum
  1291. reciprocal_pi = (one << wp) // pi
  1292. for n in xrange(3, N+1, 4):
  1293. U = (n-3)//4
  1294. s = zeta_values[4*U+4]*(4*U+7)//4
  1295. for k in xrange(1, U+1):
  1296. s -= (zeta_values[4*k] * zeta_values[4*U+4-4*k]) >> wp
  1297. zeta_values[n] += (2*s*reciprocal_pi) >> wp
  1298. for n in xrange(5, N+1, 4):
  1299. U = (n-1)//4
  1300. s = zeta_values[4*U+2]*(2*U+1)
  1301. for k in xrange(1, 2*U+1):
  1302. s += ((-1)**k*2*k* zeta_values[2*k] * zeta_values[4*U+2-2*k])>>wp
  1303. zeta_values[n] += ((s*reciprocal_pi)>>wp)//(2*U)
  1304. return [x>>extra for x in zeta_values]
  1305. def gamma_taylor_coefficients(inprec):
  1306. """
  1307. Gives the Taylor coefficients of 1/gamma(1+x) as
  1308. a list of fixed-point numbers. Enough coefficients are returned
  1309. to ensure that the series converges to the given precision
  1310. when x is in [0.5, 1.5].
  1311. """
  1312. # Reuse nearby cache values (small case)
  1313. if inprec < 400:
  1314. prec = inprec + (10-(inprec%10))
  1315. elif inprec < 1000:
  1316. prec = inprec + (30-(inprec%30))
  1317. else:
  1318. prec = inprec
  1319. if prec in gamma_taylor_cache:
  1320. return gamma_taylor_cache[prec], prec
  1321. # Experimentally determined bounds
  1322. if prec < 1000:
  1323. N = int(prec**0.76 + 2)
  1324. else:
  1325. # Valid to at least 15000 bits
  1326. N = int(prec**0.787 + 2)
  1327. # Reuse higher precision values
  1328. for cprec in gamma_taylor_cache:
  1329. if cprec > prec:
  1330. coeffs = [x>>(cprec-prec) for x in gamma_taylor_cache[cprec][-N:]]
  1331. if inprec < 1000:
  1332. gamma_taylor_cache[prec] = coeffs
  1333. return coeffs, prec
  1334. # Cache at a higher precision (large case)
  1335. if prec > 1000:
  1336. prec = int(prec * 1.2)
  1337. wp = prec + 20
  1338. A = [0] * N
  1339. A[0] = MPZ_ZERO
  1340. A[1] = MPZ_ONE << wp
  1341. A[2] = euler_fixed(wp)
  1342. # SLOW, reference implementation
  1343. #zeta_values = [0,0]+[to_fixed(mpf_zeta_int(k,wp),wp) for k in xrange(2,N)]
  1344. zeta_values = zeta_array(N, wp)
  1345. for k in xrange(3, N):
  1346. a = (-A[2]*A[k-1])>>wp
  1347. for j in xrange(2,k):
  1348. a += ((-1)**j * zeta_values[j] * A[k-j]) >> wp
  1349. a //= (1-k)
  1350. A[k] = a
  1351. A = [a>>20 for a in A]
  1352. A = A[::-1]
  1353. A = A[:-1]
  1354. gamma_taylor_cache[prec] = A
  1355. #return A, prec
  1356. return gamma_taylor_coefficients(inprec)
  1357. def gamma_fixed_taylor(xmpf, x, wp, prec, rnd, type):
  1358. # Determine nearest multiple of N/2
  1359. #n = int(x >> (wp-1))
  1360. #steps = (n-1)>>1
  1361. nearest_int = ((x >> (wp-1)) + MPZ_ONE) >> 1
  1362. one = MPZ_ONE << wp
  1363. coeffs, cwp = gamma_taylor_coefficients(wp)
  1364. if nearest_int > 0:
  1365. r = one
  1366. for i in xrange(nearest_int-1):
  1367. x -= one
  1368. r = (r*x) >> wp
  1369. x -= one
  1370. p = MPZ_ZERO
  1371. for c in coeffs:
  1372. p = c + ((x*p)>>wp)
  1373. p >>= (cwp-wp)
  1374. if type == 0:
  1375. return from_man_exp((r<<wp)//p, -wp, prec, rnd)
  1376. if type == 2:
  1377. return mpf_shift(from_rational(p, (r<<wp), prec, rnd), wp)
  1378. if type == 3:
  1379. return mpf_log(mpf_abs(from_man_exp((r<<wp)//p, -wp)), prec, rnd)
  1380. else:
  1381. r = one
  1382. for i in xrange(-nearest_int):
  1383. r = (r*x) >> wp
  1384. x += one
  1385. p = MPZ_ZERO
  1386. for c in coeffs:
  1387. p = c + ((x*p)>>wp)
  1388. p >>= (cwp-wp)
  1389. if wp - bitcount(abs(x)) > 10:
  1390. # pass very close to 0, so do floating-point multiply
  1391. g = mpf_add(xmpf, from_int(-nearest_int)) # exact
  1392. r = from_man_exp(p*r,-wp-wp)
  1393. r = mpf_mul(r, g, wp)
  1394. if type == 0:
  1395. return mpf_div(fone, r, prec, rnd)
  1396. if type == 2:
  1397. return mpf_pos(r, prec, rnd)
  1398. if type == 3:
  1399. return mpf_log(mpf_abs(mpf_div(fone, r, wp)), prec, rnd)
  1400. else:
  1401. r = from_man_exp(x*p*r,-3*wp)
  1402. if type == 0: return mpf_div(fone, r, prec, rnd)
  1403. if type == 2: return mpf_pos(r, prec, rnd)
  1404. if type == 3: return mpf_neg(mpf_log(mpf_abs(r), prec, rnd))
  1405. def stirling_coefficient(n):
  1406. if n in gamma_stirling_cache:
  1407. return gamma_stirling_cache[n]
  1408. p, q = bernfrac(n)
  1409. q *= MPZ(n*(n-1))
  1410. gamma_stirling_cache[n] = p, q, bitcount(abs(p)), bitcount(q)
  1411. return gamma_stirling_cache[n]
  1412. def real_stirling_series(x, prec):
  1413. """
  1414. Sums the rational part of Stirling's expansion,
  1415. log(sqrt(2*pi)) - z + 1/(12*z) - 1/(360*z^3) + ...
  1416. """
  1417. t = (MPZ_ONE<<(prec+prec)) // x # t = 1/x
  1418. u = (t*t)>>prec # u = 1/x**2
  1419. s = ln_sqrt2pi_fixed(prec) - x
  1420. # Add initial terms of Stirling's series
  1421. s += t//12; t = (t*u)>>prec
  1422. s -= t//360; t = (t*u)>>prec
  1423. s += t//1260; t = (t*u)>>prec
  1424. s -= t//1680; t = (t*u)>>prec
  1425. if not t: return s
  1426. s += t//1188; t = (t*u)>>prec
  1427. s -= 691*t//360360; t = (t*u)>>prec
  1428. s += t//156; t = (t*u)>>prec
  1429. if not t: return s
  1430. s -= 3617*t//122400; t = (t*u)>>prec
  1431. s += 43867*t//244188; t = (t*u)>>prec
  1432. s -= 174611*t//125400; t = (t*u)>>prec
  1433. if not t: return s
  1434. k = 22
  1435. # From here on, the coefficients are growing, so we
  1436. # have to keep t at a roughly constant size
  1437. usize = bitcount(abs(u))
  1438. tsize = bitcount(abs(t))
  1439. texp = 0
  1440. while 1:
  1441. p, q, pb, qb = stirling_coefficient(k)
  1442. term_mag = tsize + pb + texp
  1443. shift = -texp
  1444. m = pb - term_mag
  1445. if m > 0 and shift < m:
  1446. p >>= m
  1447. shift -= m
  1448. m = tsize - term_mag
  1449. if m > 0 and shift < m:
  1450. w = t >> m
  1451. shift -= m
  1452. else:
  1453. w = t
  1454. term = (t*p//q) >> shift
  1455. if not term:
  1456. break
  1457. s += term
  1458. t = (t*u) >> usize
  1459. texp -= (prec - usize)
  1460. k += 2
  1461. return s
  1462. def complex_stirling_series(x, y, prec):
  1463. # t = 1/z
  1464. _m = (x*x + y*y) >> prec
  1465. tre = (x << prec) // _m
  1466. tim = (-y << prec) // _m
  1467. # u = 1/z**2
  1468. ure = (tre*tre - tim*tim) >> prec
  1469. uim = tim*tre >> (prec-1)
  1470. # s = log(sqrt(2*pi)) - z
  1471. sre = ln_sqrt2pi_fixed(prec) - x
  1472. sim = -y
  1473. # Add initial terms of Stirling's series
  1474. sre += tre//12; sim += tim//12;
  1475. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1476. sre -= tre//360; sim -= tim//360;
  1477. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1478. sre += tre//1260; sim += tim//1260;
  1479. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1480. sre -= tre//1680; sim -= tim//1680;
  1481. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1482. if abs(tre) + abs(tim) < 5: return sre, sim
  1483. sre += tre//1188; sim += tim//1188;
  1484. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1485. sre -= 691*tre//360360; sim -= 691*tim//360360;
  1486. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1487. sre += tre//156; sim += tim//156;
  1488. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1489. if abs(tre) + abs(tim) < 5: return sre, sim
  1490. sre -= 3617*tre//122400; sim -= 3617*tim//122400;
  1491. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1492. sre += 43867*tre//244188; sim += 43867*tim//244188;
  1493. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1494. sre -= 174611*tre//125400; sim -= 174611*tim//125400;
  1495. tre, tim = ((tre*ure-tim*uim)>>prec), ((tre*uim+tim*ure)>>prec)
  1496. if abs(tre) + abs(tim) < 5: return sre, sim
  1497. k = 22
  1498. # From here on, the coefficients are growing, so we
  1499. # have to keep t at a roughly constant size
  1500. usize = bitcount(max(abs(ure), abs(uim)))
  1501. tsize = bitcount(max(abs(tre), abs(tim)))
  1502. texp = 0
  1503. while 1:
  1504. p, q, pb, qb = stirling_coefficient(k)
  1505. term_mag = tsize + pb + texp
  1506. shift = -texp
  1507. m = pb - term_mag
  1508. if m > 0 and shift < m:
  1509. p >>= m
  1510. shift -= m
  1511. m = tsize - term_mag
  1512. if m > 0 and shift < m:
  1513. wre = tre >> m
  1514. wim = tim >> m
  1515. shift -= m
  1516. else:
  1517. wre = tre
  1518. wim = tim
  1519. termre = (tre*p//q) >> shift
  1520. termim = (tim*p//q) >> shift
  1521. if abs(termre) + abs(termim) < 5:
  1522. break
  1523. sre += termre
  1524. sim += termim
  1525. tre, tim = ((tre*ure - tim*uim)>>usize), \
  1526. ((tre*uim + tim*ure)>>usize)
  1527. texp -= (prec - usize)
  1528. k += 2
  1529. return sre, sim
  1530. def mpf_gamma(x, prec, rnd='d', type=0):
  1531. """
  1532. This function implements multipurpose evaluation of the gamma
  1533. function, G(x), as well as the following versions of the same:
  1534. type = 0 -- G(x) [standard gamma function]
  1535. type = 1 -- G(x+1) = x*G(x+1) = x! [factorial]
  1536. type = 2 -- 1/G(x) [reciprocal gamma function]
  1537. type = 3 -- log(|G(x)|) [log-gamma function, real part]
  1538. """
  1539. # Specal values
  1540. sign, man, exp, bc = x
  1541. if not man:
  1542. if x == fzero:
  1543. if type == 1: return fone
  1544. if type == 2: return fzero
  1545. raise ValueError("gamma function pole")
  1546. if x == finf:
  1547. if type == 2: return fzero
  1548. return finf
  1549. return fnan
  1550. # First of all, for log gamma, numbers can be well beyond the fixed-point
  1551. # range, so we must take care of huge numbers before e.g. trying
  1552. # to convert x to the nearest integer
  1553. if type == 3:
  1554. wp = prec+20
  1555. if exp+bc > wp and not sign:
  1556. return mpf_sub(mpf_mul(x, mpf_log(x, wp), wp), x, prec, rnd)
  1557. # We strongly want to special-case small integers
  1558. is_integer = exp >= 0
  1559. if is_integer:
  1560. # Poles
  1561. if sign:
  1562. if type == 2:
  1563. return fzero
  1564. raise ValueError("gamma function pole")
  1565. # n = x
  1566. n = man << exp
  1567. if n < SMALL_FACTORIAL_CACHE_SIZE:
  1568. if type == 0:
  1569. return mpf_pos(small_factorial_cache[n-1], prec, rnd)
  1570. if type == 1:
  1571. return mpf_pos(small_factorial_cache[n], prec, rnd)
  1572. if type == 2:
  1573. return mpf_div(fone, small_factorial_cache[n-1], prec, rnd)
  1574. if type == 3:
  1575. return mpf_log(small_factorial_cache[n-1], prec, rnd)
  1576. else:
  1577. # floor(abs(x))
  1578. n = int(man >> (-exp))
  1579. # Estimate size and precision
  1580. # Estimate log(gamma(|x|),2) as x*log(x,2)
  1581. mag = exp + bc
  1582. gamma_size = n*mag
  1583. if type == 3:
  1584. wp = prec + 20
  1585. else:
  1586. wp = prec + bitcount(gamma_size) + 20
  1587. # Very close to 0, pole
  1588. if mag < -wp:
  1589. if type == 0:
  1590. return mpf_sub(mpf_div(fone,x, wp),mpf_shift(fone,-wp),prec,rnd)
  1591. if type == 1: return mpf_sub(fone, x, prec, rnd)
  1592. if type == 2: return mpf_add(x, mpf_shift(fone,mag-wp), prec, rnd)
  1593. if type == 3: return mpf_neg(mpf_log(mpf_abs(x), prec, rnd))
  1594. # From now on, we assume having a gamma function
  1595. if type == 1:
  1596. return mpf_gamma(mpf_add(x, fone), prec, rnd, 0)
  1597. # Special case integers (those not small enough to be caught above,
  1598. # but still small enough for an exact factorial to be faster
  1599. # than an approximate algorithm), and half-integers
  1600. if exp >= -1:
  1601. if is_integer:
  1602. if gamma_size < 10*wp:
  1603. if type == 0:
  1604. return from_int(ifac(n-1), prec, rnd)
  1605. if type == 2:
  1606. return from_rational(MPZ_ONE, ifac(n-1), prec, rnd)
  1607. if type == 3:
  1608. return mpf_log(from_int(ifac(n-1)), prec, rnd)
  1609. # half-integer
  1610. if n < 100 or gamma_size < 10*wp:
  1611. if sign:
  1612. w = sqrtpi_fixed(wp)
  1613. if n % 2: f = ifac2(2*n+1)
  1614. else: f = -ifac2(2*n+1)
  1615. if type == 0:
  1616. return mpf_shift(from_rational(w, f, prec, rnd), -wp+n+1)
  1617. if type == 2:
  1618. return mpf_shift(from_rational(f, w, prec, rnd), wp-n-1)
  1619. if type == 3:
  1620. return mpf_log(mpf_shift(from_rational(w, abs(f),
  1621. prec, rnd), -wp+n+1), prec, rnd)
  1622. elif n == 0:
  1623. if type == 0: return mpf_sqrtpi(prec, rnd)
  1624. if type == 2: return mpf_div(fone, mpf_sqrtpi(wp), prec, rnd)
  1625. if type == 3: return mpf_log(mpf_sqrtpi(wp), prec, rnd)
  1626. else:
  1627. w = sqrtpi_fixed(wp)
  1628. w = from_man_exp(w * ifac2(2*n-1), -wp-n)
  1629. if type == 0: return mpf_pos(w, prec, rnd)
  1630. if type == 2: return mpf_div(fone, w, prec, rnd)
  1631. if type == 3: return mpf_log(mpf_abs(w), prec, rnd)
  1632. # Convert to fixed point
  1633. offset = exp + wp
  1634. if offset >= 0: absxman = man << offset
  1635. else: absxman = man >> (-offset)
  1636. # For log gamma, provide accurate evaluation for x = 1+eps and 2+eps
  1637. if type == 3 and not sign:
  1638. one = MPZ_ONE << wp
  1639. one_dist = abs(absxman-one)
  1640. two_dist = abs(absxman-2*one)
  1641. cancellation = (wp - bitcount(min(one_dist, two_dist)))
  1642. if cancellation > 10:
  1643. xsub1 = mpf_sub(fone, x)
  1644. xsub2 = mpf_sub(ftwo, x)
  1645. xsub1mag = xsub1[2]+xsub1[3]
  1646. xsub2mag = xsub2[2]+xsub2[3]
  1647. if xsub1mag < -wp:
  1648. return mpf_mul(mpf_euler(wp), mpf_sub(fone, x), prec, rnd)
  1649. if xsub2mag < -wp:
  1650. return mpf_mul(mpf_sub(fone, mpf_euler(wp)),
  1651. mpf_sub(x, ftwo), prec, rnd)
  1652. # Proceed but increase precision
  1653. wp += max(-xsub1mag, -xsub2mag)
  1654. offset = exp + wp
  1655. if offset >= 0: absxman = man << offset
  1656. else: absxman = man >> (-offset)
  1657. # Use Taylor series if appropriate
  1658. n_for_stirling = int(GAMMA_STIRLING_BETA*wp)
  1659. if n < max(100, n_for_stirling) and wp < MAX_GAMMA_TAYLOR_PREC:
  1660. if sign:
  1661. absxman = -absxman
  1662. return gamma_fixed_taylor(x, absxman, wp, prec, rnd, type)
  1663. # Use Stirling's series
  1664. # First ensure that |x| is large enough for rapid convergence
  1665. xorig = x
  1666. # Argument reduction
  1667. r = 0
  1668. if n < n_for_stirling:
  1669. r = one = MPZ_ONE << wp
  1670. d = n_for_stirling - n
  1671. for k in xrange(d):
  1672. r = (r * absxman) >> wp
  1673. absxman += one
  1674. x = xabs = from_man_exp(absxman, -wp)
  1675. if sign:
  1676. x = mpf_neg(x)
  1677. else:
  1678. xabs = mpf_abs(x)
  1679. # Asymptotic series
  1680. y = real_stirling_series(absxman, wp)
  1681. u = to_fixed(mpf_log(xabs, wp), wp)
  1682. u = ((absxman - (MPZ_ONE<<(wp-1))) * u) >> wp
  1683. y += u
  1684. w = from_man_exp(y, -wp)
  1685. # Compute final value
  1686. if sign:
  1687. # Reflection formula
  1688. A = mpf_mul(mpf_sin_pi(xorig, wp), xorig, wp)
  1689. B = mpf_neg(mpf_pi(wp))
  1690. if type == 0 or type == 2:
  1691. A = mpf_mul(A, mpf_exp(w, wp))
  1692. if r:
  1693. B = mpf_mul(B, from_man_exp(r, -wp), wp)
  1694. if type == 0:
  1695. return mpf_div(B, A, prec, rnd)
  1696. if type == 2:
  1697. return mpf_div(A, B, prec, rnd)
  1698. if type == 3:
  1699. if r:
  1700. B = mpf_mul(B, from_man_exp(r, -wp), wp)
  1701. A = mpf_add(mpf_log(mpf_abs(A), wp), w, wp)
  1702. return mpf_sub(mpf_log(mpf_abs(B), wp), A, prec, rnd)
  1703. else:
  1704. if type == 0:
  1705. if r:
  1706. return mpf_div(mpf_exp(w, wp),
  1707. from_man_exp(r, -wp), prec, rnd)
  1708. return mpf_exp(w, prec, rnd)
  1709. if type == 2:
  1710. if r:
  1711. return mpf_div(from_man_exp(r, -wp),
  1712. mpf_exp(w, wp), prec, rnd)
  1713. return mpf_exp(mpf_neg(w), prec, rnd)
  1714. if type == 3:
  1715. if r:
  1716. return mpf_sub(w, mpf_log(from_man_exp(r,-wp), wp), prec, rnd)
  1717. return mpf_pos(w, prec, rnd)
  1718. def mpc_gamma(z, prec, rnd='d', type=0):
  1719. a, b = z
  1720. asign, aman, aexp, abc = a
  1721. bsign, bman, bexp, bbc = b
  1722. if b == fzero:
  1723. # Imaginary part on negative half-axis for log-gamma function
  1724. if type == 3 and asign:
  1725. re = mpf_gamma(a, prec, rnd, 3)
  1726. n = (-aman) >> (-aexp)
  1727. im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd)
  1728. return re, im
  1729. return mpf_gamma(a, prec, rnd, type), fzero
  1730. # Some kind of complex inf/nan
  1731. if (not aman and aexp) or (not bman and bexp):
  1732. return (fnan, fnan)
  1733. # Initial working precision
  1734. wp = prec + 20
  1735. amag = aexp+abc
  1736. bmag = bexp+bbc
  1737. if aman:
  1738. mag = max(amag, bmag)
  1739. else:
  1740. mag = bmag
  1741. # Close to 0
  1742. if mag < -8:
  1743. if mag < -wp:
  1744. # 1/gamma(z) = z + euler*z^2 + O(z^3)
  1745. v = mpc_add(z, mpc_mul_mpf(mpc_mul(z,z,wp),mpf_euler(wp),wp), wp)
  1746. if type == 0: return mpc_reciprocal(v, prec, rnd)
  1747. if type == 1: return mpc_div(z, v, prec, rnd)
  1748. if type == 2: return mpc_pos(v, prec, rnd)
  1749. if type == 3: return mpc_log(mpc_reciprocal(v, prec), prec, rnd)
  1750. elif type != 1:
  1751. wp += (-mag)
  1752. # Handle huge log-gamma values; must do this before converting to
  1753. # a fixed-point value. TODO: determine a precise cutoff of validity
  1754. # depending on amag and bmag
  1755. if type == 3 and mag > wp and ((not asign) or (bmag >= amag)):
  1756. return mpc_sub(mpc_mul(z, mpc_log(z, wp), wp), z, prec, rnd)
  1757. # From now on, we assume having a gamma function
  1758. if type == 1:
  1759. return mpc_gamma((mpf_add(a, fone), b), prec, rnd, 0)
  1760. an = abs(to_int(a))
  1761. bn = abs(to_int(b))
  1762. absn = max(an, bn)
  1763. gamma_size = absn*mag
  1764. if type == 3:
  1765. pass
  1766. else:
  1767. wp += bitcount(gamma_size)
  1768. # Reflect to the right half-plane. Note that Stirling's expansion
  1769. # is valid in the left half-plane too, as long as we're not too close
  1770. # to the real axis, but in order to use this argument reduction
  1771. # in the negative direction must be implemented.
  1772. #need_reflection = asign and ((bmag < 0) or (amag-bmag > 4))
  1773. need_reflection = asign
  1774. zorig = z
  1775. if need_reflection:
  1776. z = mpc_neg(z)
  1777. asign, aman, aexp, abc = a = z[0]
  1778. bsign, bman, bexp, bbc = b = z[1]
  1779. # Imaginary part very small compared to real one?
  1780. yfinal = 0
  1781. balance_prec = 0
  1782. if bmag < -10:
  1783. # Check z ~= 1 and z ~= 2 for loggamma
  1784. if type == 3:
  1785. zsub1 = mpc_sub_mpf(z, fone)
  1786. if zsub1[0] == fzero:
  1787. cancel1 = -bmag
  1788. else:
  1789. cancel1 = -max(zsub1[0][2]+zsub1[0][3], bmag)
  1790. if cancel1 > wp:
  1791. pi = mpf_pi(wp)
  1792. x = mpc_mul_mpf(zsub1, pi, wp)
  1793. x = mpc_mul(x, x, wp)
  1794. x = mpc_div_mpf(x, from_int(12), wp)
  1795. y = mpc_mul_mpf(zsub1, mpf_neg(mpf_euler(wp)), wp)
  1796. yfinal = mpc_add(x, y, wp)
  1797. if not need_reflection:
  1798. return mpc_pos(yfinal, prec, rnd)
  1799. elif cancel1 > 0:
  1800. wp += cancel1
  1801. zsub2 = mpc_sub_mpf(z, ftwo)
  1802. if zsub2[0] == fzero:
  1803. cancel2 = -bmag
  1804. else:
  1805. cancel2 = -max(zsub2[0][2]+zsub2[0][3], bmag)
  1806. if cancel2 > wp:
  1807. pi = mpf_pi(wp)
  1808. t = mpf_sub(mpf_mul(pi, pi), from_int(6))
  1809. x = mpc_mul_mpf(mpc_mul(zsub2, zsub2, wp), t, wp)
  1810. x = mpc_div_mpf(x, from_int(12), wp)
  1811. y = mpc_mul_mpf(zsub2, mpf_sub(fone, mpf_euler(wp)), wp)
  1812. yfinal = mpc_add(x, y, wp)
  1813. if not need_reflection:
  1814. return mpc_pos(yfinal, prec, rnd)
  1815. elif cancel2 > 0:
  1816. wp += cancel2
  1817. if bmag < -wp:
  1818. # Compute directly from the real gamma function.
  1819. pp = 2*(wp+10)
  1820. aabs = mpf_abs(a)
  1821. eps = mpf_shift(fone, amag-wp)
  1822. x1 = mpf_gamma(aabs, pp, type=type)
  1823. x2 = mpf_gamma(mpf_add(aabs, eps), pp, type=type)
  1824. xprime = mpf_div(mpf_sub(x2, x1, pp), eps, pp)
  1825. y = mpf_mul(b, xprime, prec, rnd)
  1826. yfinal = (x1, y)
  1827. # Note: we still need to use the reflection formula for
  1828. # near-poles, and the correct branch of the log-gamma function
  1829. if not need_reflection:
  1830. return mpc_pos(yfinal, prec, rnd)
  1831. else:
  1832. balance_prec += (-bmag)
  1833. wp += balance_prec
  1834. n_for_stirling = int(GAMMA_STIRLING_BETA*wp)
  1835. need_reduction = absn < n_for_stirling
  1836. afix = to_fixed(a, wp)
  1837. bfix = to_fixed(b, wp)
  1838. r = 0
  1839. if not yfinal:
  1840. zprered = z
  1841. # Argument reduction
  1842. if absn < n_for_stirling:
  1843. absn = complex(an, bn)
  1844. d = int((1 + n_for_stirling**2 - bn**2)**0.5 - an)
  1845. rre = one = MPZ_ONE << wp
  1846. rim = MPZ_ZERO
  1847. for k in xrange(d):
  1848. rre, rim = ((afix*rre-bfix*rim)>>wp), ((afix*rim + bfix*rre)>>wp)
  1849. afix += one
  1850. r = from_man_exp(rre, -wp), from_man_exp(rim, -wp)
  1851. a = from_man_exp(afix, -wp)
  1852. z = a, b
  1853. yre, yim = complex_stirling_series(afix, bfix, wp)
  1854. # (z-1/2)*log(z) + S
  1855. lre, lim = mpc_log(z, wp)
  1856. lre = to_fixed(lre, wp)
  1857. lim = to_fixed(lim, wp)
  1858. yre = ((lre*afix - lim*bfix)>>wp) - (lre>>1) + yre
  1859. yim = ((lre*bfix + lim*afix)>>wp) - (lim>>1) + yim
  1860. y = from_man_exp(yre, -wp), from_man_exp(yim, -wp)
  1861. if r and type == 3:
  1862. # If re(z) > 0 and abs(z) <= 4, the branches of loggamma(z)
  1863. # and log(gamma(z)) coincide. Otherwise, use the zeroth order
  1864. # Stirling expansion to compute the correct imaginary part.
  1865. y = mpc_sub(y, mpc_log(r, wp), wp)
  1866. zfa = to_float(zprered[0])
  1867. zfb = to_float(zprered[1])
  1868. zfabs = math.hypot(zfa,zfb)
  1869. #if not (zfa > 0.0 and zfabs <= 4):
  1870. yfb = to_float(y[1])
  1871. u = math.atan2(zfb, zfa)
  1872. if zfabs <= 0.5:
  1873. gi = 0.577216*zfb - u
  1874. else:
  1875. gi = -zfb - 0.5*u + zfa*u + zfb*math.log(zfabs)
  1876. n = int(math.floor((gi-yfb)/(2*math.pi)+0.5))
  1877. y = (y[0], mpf_add(y[1], mpf_mul_int(mpf_pi(wp), 2*n, wp), wp))
  1878. if need_reflection:
  1879. if type == 0 or type == 2:
  1880. A = mpc_mul(mpc_sin_pi(zorig, wp), zorig, wp)
  1881. B = (mpf_neg(mpf_pi(wp)), fzero)
  1882. if yfinal:
  1883. if type == 2:
  1884. A = mpc_div(A, yfinal, wp)
  1885. else:
  1886. A = mpc_mul(A, yfinal, wp)
  1887. else:
  1888. A = mpc_mul(A, mpc_exp(y, wp), wp)
  1889. if r:
  1890. B = mpc_mul(B, r, wp)
  1891. if type == 0: return mpc_div(B, A, prec, rnd)
  1892. if type == 2: return mpc_div(A, B, prec, rnd)
  1893. # Reflection formula for the log-gamma function with correct branch
  1894. # http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0006/
  1895. # LogGamma[z] == -LogGamma[-z] - Log[-z] +
  1896. # Sign[Im[z]] Floor[Re[z]] Pi I + Log[Pi] -
  1897. # Log[Sin[Pi (z - Floor[Re[z]])]] -
  1898. # Pi I (1 - Abs[Sign[Im[z]]]) Abs[Floor[Re[z]]]
  1899. if type == 3:
  1900. if yfinal:
  1901. s1 = mpc_neg(yfinal)
  1902. else:
  1903. s1 = mpc_neg(y)
  1904. # s -= log(-z)
  1905. s1 = mpc_sub(s1, mpc_log(mpc_neg(zorig), wp), wp)
  1906. # floor(re(z))
  1907. rezfloor = mpf_floor(zorig[0])
  1908. imzsign = mpf_sign(zorig[1])
  1909. pi = mpf_pi(wp)
  1910. t = mpf_mul(pi, rezfloor)
  1911. t = mpf_mul_int(t, imzsign, wp)
  1912. s1 = (s1[0], mpf_add(s1[1], t, wp))
  1913. s1 = mpc_add_mpf(s1, mpf_log(pi, wp), wp)
  1914. t = mpc_sin_pi(mpc_sub_mpf(zorig, rezfloor), wp)
  1915. t = mpc_log(t, wp)
  1916. s1 = mpc_sub(s1, t, wp)
  1917. # Note: may actually be unused, because we fall back
  1918. # to the mpf_ function for real arguments
  1919. if not imzsign:
  1920. t = mpf_mul(pi, mpf_floor(rezfloor), wp)
  1921. s1 = (s1[0], mpf_sub(s1[1], t, wp))
  1922. return mpc_pos(s1, prec, rnd)
  1923. else:
  1924. if type == 0:
  1925. if r:
  1926. return mpc_div(mpc_exp(y, wp), r, prec, rnd)
  1927. return mpc_exp(y, prec, rnd)
  1928. if type == 2:
  1929. if r:
  1930. return mpc_div(r, mpc_exp(y, wp), prec, rnd)
  1931. return mpc_exp(mpc_neg(y), prec, rnd)
  1932. if type == 3:
  1933. return mpc_pos(y, prec, rnd)
  1934. def mpf_factorial(x, prec, rnd='d'):
  1935. return mpf_gamma(x, prec, rnd, 1)
  1936. def mpc_factorial(x, prec, rnd='d'):
  1937. return mpc_gamma(x, prec, rnd, 1)
  1938. def mpf_rgamma(x, prec, rnd='d'):
  1939. return mpf_gamma(x, prec, rnd, 2)
  1940. def mpc_rgamma(x, prec, rnd='d'):
  1941. return mpc_gamma(x, prec, rnd, 2)
  1942. def mpf_loggamma(x, prec, rnd='d'):
  1943. sign, man, exp, bc = x
  1944. if sign:
  1945. raise ComplexResult
  1946. return mpf_gamma(x, prec, rnd, 3)
  1947. def mpc_loggamma(z, prec, rnd='d'):
  1948. a, b = z
  1949. asign, aman, aexp, abc = a
  1950. bsign, bman, bexp, bbc = b
  1951. if b == fzero and asign:
  1952. re = mpf_gamma(a, prec, rnd, 3)
  1953. n = (-aman) >> (-aexp)
  1954. im = mpf_mul_int(mpf_pi(prec+10), n, prec, rnd)
  1955. return re, im
  1956. return mpc_gamma(z, prec, rnd, 3)
  1957. def mpf_gamma_int(n, prec, rnd=round_fast):
  1958. if n < SMALL_FACTORIAL_CACHE_SIZE:
  1959. return mpf_pos(small_factorial_cache[n-1], prec, rnd)
  1960. return mpf_gamma(from_int(n), prec, rnd)