这篇文章上次修改于 384 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
import decimal


def pi(prec: int) -> decimal.Decimal:
    if prec <= 0:
        return decimal.Decimal(prec)

    with decimal.localcontext() as ctx:
        ctx.prec = prec + 2
        three = decimal.Decimal(3)
        lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
        while s != lasts:
            lasts = s
            n, na = n + na, na + 8
            d, da = d + da, da + 32
            t = (t * n) / d
            s += t
        ctx.prec -= 2
        return +s


if __name__ == "__main__":
    pi(-1)