同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
from decimal import Decimal, getcontextfrom math import ceil, factorialdef pi(precision: int) -> str:"""The Chudnovsky algorithm is a fast method for calculating the digits of PI,based on Ramanujan’s PI formulae.https://en.wikipedia.org/wiki/Chudnovsky_algorithmPI = constant_term / ((multinomial_term * linear_term) / exponential_term)where constant_term = 426880 * sqrt(10005)The linear_term and the exponential_term can be defined iteratively as follows:L_k+1 = L_k + 545140134 where L_0 = 13591409X_k+1 = X_k * -262537412640768000 where X_0 = 1The multinomial_term is defined as follows:6k! / ((3k)! * (k!) ^ 3)where k is the k_th iteration.This algorithm correctly calculates around 14 digits of PI per iteration>>> pi(10)'3.14159265'>>> pi(100)'3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706'>>> pi('hello')Traceback (most recent call last):...TypeError: Undefined for non-integers>>> pi(-1)Traceback (most recent call last):...ValueError: Undefined for non-natural numbers"""if not isinstance(precision, int):raise TypeError("Undefined for non-integers")elif precision < 1:raise ValueError("Undefined for non-natural numbers")getcontext().prec = precisionnum_iterations = ceil(precision / 14)constant_term = 426880 * Decimal(10005).sqrt()exponential_term = 1linear_term = 13591409partial_sum = Decimal(linear_term)for k in range(1, num_iterations):multinomial_term = factorial(6 * k) // (factorial(3 * k) * factorial(k) ** 3)linear_term += 545140134exponential_term *= -262537412640768000partial_sum += Decimal(multinomial_term * linear_term) / exponential_termreturn str(constant_term / partial_sum)[:-1]if __name__ == "__main__":n = 50print(f"The first {n} digits of pi is: {pi(n)}")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。