• python计算π及进度条显示


          今天老师布置了一个课后作业,去尽可能的准确计算π的值,还要显示时间和进度条,对于python小白的我,当然是综合书上和网上的知识,自己做了一个小程序,代码如下:

    一、写代码的准备工作:用pip下载第三方库tqdm

    步骤1:打开cmd

    步骤2:输入pip install   你要安装的库(如 pip install tqdm)   #pip一般是在安装python的时候就有了,还有tqdm我之前已经下载好了

    二、写程序

    1.这个代码的启发是由上学期c语言的一道例题改编的

    from math import *
    from tqdm import tqdm
    from time import *
    total,s,n,t=0.0,1,1.0,1.0
    clock()
    while(fabs(t)>=1e-6):
        total+=t
        n+=2 
        s=-s
        t=s/n
    k=total*4
    print("π值是{:.10f}  运行时间为{:.4f}秒".format(k,clock()))
    for i in tqdm(range(101)):
        print("
    {:3}%".format(i),end="")
        sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间

     由于执行时太快了,我录了一个gif,如下图:

    静态图:

    2.第二个程序是根据python书上的

    from random import random
    from math import sqrt
    from time import *
    from tqdm import tqdm
    DARTS=10000000
    hits=0.0
    clock()
    for i in range(1,DARTS+1):
        x,y=random(),random()
        dist=sqrt(x**2+y**2)
        if dist <=1.0:
            hits=hits+1
    pi=4*(hits/DARTS)
    for i in tqdm(range(10)):
        print("
    {:3}%".format(i/10*100),end="") #这里的i/10*100指每10%显示一次
    sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间
    print("pi的值{}.".format(pi))
    print("运行时间:{:.5f}s".format(clock()))

    执行后:静态图和动态图如下

  • 相关阅读:
    JAVA自学之-----FileInputStream类
    RandomAccessFile类的使用(随机读取java中的文件)
    JAVA File常用的API介绍
    Java中的编码
    java的装箱与拆箱
    java基础知识整理:
    java程序编写需注意的问题
    iPhone开机键坏了如何开机
    WKInterfaceTable实例化出现的一系列
    Office for Mac
  • 原文地址:https://www.cnblogs.com/panqiaoyan/p/10534920.html
Copyright © 2020-2023  润新知