割圆法求圆周率和圆面积(附带进度条)

import math
import time

r = 1000
ls_height = []


def circle_area(r, side_number):
    area = 0
    start = time.perf_counter()
    for i in range(side_number):
        bottom = r / side_number
        height = math.sqrt(r ** 2 - (bottom * (i + 1)) ** 2)
        height = round(height, 2)  # 保留小数点后两位
        ls_height.append(height)
        area += bottom * height

        # 打印进度条1
        number = 30
        past = i // (side_number//number)
        left = 30 - past
        a = "*" * past
        b = "." * left
        c = (i / side_number) * 100
        dur = time.perf_counter() - start
        print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c, a, b, dur), end="")
        # time.sleep(0.1)
    print() # 打印进度条2
    return area * 4


if __name__ == "__main__":
    print(math.pi * r ** 2)
    # print(circle_area(r, 8))
    # print(circle_area(r, 12))
    print(circle_area(r, 10**6))
    # print(ls_height)

加入VIP


如果你想系统学习编程涉及到的知识点,或者希望有人解答你在深度学习编程时遇到问题,加入VIP是个很不错的选择

立马 了解一下