python计算圆周率近似值_使用MicroPython计算任意位数圆周率

计算任意精度的圆周率是个有趣的主题,得益于python的强大计算能力,我们在MicroPython中也可以轻松的计算pi的数值。

先输入下面的代码:

"""

文件:pi.py

说明:用MicroPython计算任意精度圆周率计算

作者:未知

版本:

时间:

修改:邵子扬

2016.5

v1.1

http://bbs.micro-python.com/forum.php

"""

import time

def pi(places=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

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 pi_t(n=10):

t1=time.ticks_us()

t=pi(n)

t2=time.ticks_us()

print('elapsed: ', time.ticks_diff(t1,t2)/1000000, 's')

return t

def pi2(n=10):

r=6*(10**n)*1000

p=0

k=0

c=r//2

d=c//(2*k+1)

while d>0:

p=p+d

k=k+1

k2=2*k

c=c*(k2-1)//(4*k2)

d=c//(k2+1)

return p//1000

def pi2_t(n=10):

t1=time.ticks_us()

t=pi2(n)

t2=time.ticks_us()

print('elapsed: ', time.ticks_diff(t1,t2)/1000000, 's')

return t

我们将它复制到STM32F7DISC中(STM32F7DISC已经下载了MicroPython固件),然后测试一下计算速度。(在其它MicroPython开发板上也可以进行这个测试)

MicroPython v1.8 on 2016-05-15; F7DISC with STM32F746

Type “help()” for more information.

>>> import pi

>>> npi=pi.pi_t(1000)

elapsed: 0.221486 s

>>> npi=pi.pi_t(2000)

elapsed: 0.793141 s

>>> npi=pi.pi_t(5000)

elapsed: 4.981964 s

>>> npi=pi.pi_t(10000)

elapsed: 21.02012 s

>>>

从运行结果可以看出,虽然不是很快,但是考虑到STM32的资源和性能,结果已经出乎预料了,毕竟计算函数还不到10行代码,没有做深度优化。最后打印出1000位的圆周率,大家可以和标准结果比较看看。

>>> pi.pi(1000)

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989

>>>

作者:shaoziyang

原文地址:https://my.oschina.net/shaoziyang/blog/781247

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值