python求pi的方法
2023-09-27 14:28:20 时间
#_*_ coding=utf-8 *_* ## {{{ http://code.activestate.com/recipes/578130/ (r5) def pi(places=10): """Computes pi to given number of decimal places 参数places表示要返回的pi的小数点后位数 方法:先整体扩大10**8(10的八次方)倍,然后计算完成后再缩小10的八次方倍 """ # 3 + 3*(1/24) + 3*(1/24)*(9/80) + 3*(1/24)*(9/80)*(25/168) # The numerators 1, 9, 25, ... are given by (2x + 1) ^ 2 # The denominators 24, 80, 168 are given by (16x^2 -24x + 8) extra = 8 one = 10 ** (places+extra) t, c, n, na, d, da = 3*one, 3*one, 1, 0, 0, 24 #这里的n 和d 分别为每一项的分子与分母 ,na 和 da 分别为分子和分分母后一项比前一项增加的数值 #这里的//可不是C++中的注释,而是除的意思 while t > 1: n, na, d, da = n+na, na+8, d+da, da+32 t = t * n // d c += t return c // (10 ** extra) def picirc(radius, aspect_ratio=5): """Display the digit of pi in a circle of given radius radius:显示的半径 aspect_ratio:调节显示的比率参数 """ #display_width为各行的显示长度 display_width = int(radius * aspect_ratio + 10) pi_str = repr(pi(int(2 * radius ** 2 * aspect_ratio))) pos = 0 #cols为每一行中要显示的数字个数 for i in range(2 * radius): cols = int(0.5 + aspect_ratio * (radius**2 - (radius-(i+0.5))**2) ** 0.5) print(pi_str[pos:pos+cols].center(display_width)) #将产生的pi数值生成的文本列表中相应的位数取出来显示在当前行 pos += cols if __name__ == '__main__': picirc(16) ## end of http://code.activestate.com/recipes/578130/ }}}
相关文章
- python解压压缩包的几种方法
- Python之smtpd及smtplib(邮件服务器及客户端)
- Python__repr__()方法:显示属性
- web自动化测试:Selenium+Python基础方法封装
- 45 python - "魔法"方法
- python requests【2】高阶
- 职场经验:学习Python到什么地步才可以做自动化测试?
- 运维前线:一线运维专家的运维方法、技巧与实践2.4 如何利用Python获取Facts
- Python 类的方法和静态方法
- python 判断bytes是否相等的几种方法
- python中的数字取整(ceil,floor,round)概念和用法
- python数字图像处理(11):图像自动阈值分割
- 《像计算机科学家一样思考Python》—— 3.10 栈图
- python学习之报错:ModuleNotFoundError: No module named ‘pandas‘解决方法
- 基于Python的垃圾短信分类【100010111】
- Python 类的私有属性和私有方法
- python迭代器协议支持的两种方法
- python字符串方法format()如何使用
- 抛弃 JavaScript 只使用 HTML 和 Python 制作网站
- Python Manim教程大全之 05 动画运行时间 动画方法 (教程含源码)
- python多进程(三种方法)
- 查看自己某个conda环境的Python版本的方法
- 【机器学习算法-python实现】协同过滤(cf)的三种方法实现
- python-关于类、方法、对象(实例):通过一个例子看一下self都做了哪些事情
- [Python] Python标准库os常用操作代码汇总