Repository: mpmath/mpmath

Issue:
Polylog inaccurate for `s` very close to an integer and `z` outside of the unit circle
Some examples:

```python
import mpmath as mp
def check(s, z):
    pl1 = mp.polylog(s, z)
    print(pl1.real)
    with mp.workdps(32):
        pl2 = mp.polylog(s, z)
        print(pl2.real)
check(1+1e-15, -2) # bad
check(1, -2 + 1e-8j) # ok (s exactly an integer)
check(1+1e-15, -0.5 + 1e-8j) # ok (|z| < 1)
```

```
-1.0986328125
-1.0986122886681101262610921881491
-1.09861228866811
-1.0986122886681096969508007924781
-0.405465108108164
-0.40546510810816446598993214576279
```

Older polylog issues: #473, #505

mpmath version: 1.2.1

Discussion:

Solution patch:
diff --git a/mpmath/functions/zeta.py b/mpmath/functions/zeta.py
index 40db1d2..ce69870 100644
--- a/mpmath/functions/zeta.py
+++ b/mpmath/functions/zeta.py
@@ -458,6 +458,10 @@ def polylog_general(ctx, s, z):
         return ctx.gamma(v)*(j**v*ctx.zeta(v,0.5+y) + j**-v*ctx.zeta(v,0.5-y))/(2*ctx.pi)**v
     t = 1
     k = 0
+    prec = ctx.prec
+    if ctx.isfinite(s):
+        ctx.prec += max(0, -ctx.nint_distance(s)[1])
+
     while 1:
         term = ctx.zeta(s-k) * t
         if not abs(term) >= ctx.eps:
@@ -466,7 +470,10 @@ def polylog_general(ctx, s, z):
         k += 1
         t *= u
         t /= k
-    return ctx.gamma(1-s)*(-u)**(s-1) + v
+
+    r = ctx.gamma(1-s)*(-u)**(s-1) + v
+    ctx.prec = prec
+    return r
 
 @defun_wrapped
 def polylog(ctx, s, z):


Test patch:
diff --git a/mpmath/tests/test_functions2.py b/mpmath/tests/test_functions2.py
index 6d860f8..0a39a56 100644
--- a/mpmath/tests/test_functions2.py
+++ b/mpmath/tests/test_functions2.py
@@ -2427,3 +2427,6 @@ def test_issue_473():
     assert mp.polylog(3, -mp.inf) == -mp.inf
     assert mp.polylog(4, -mp.inf) == -mp.inf
     assert mp.polylog(5, -mp.inf) == -mp.inf
+
+def test_issue_634():
+    assert mp.polylog(1+1e-15, -2).ae(mp.mpf('-1.09861228866811'))