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

 割圆法求圆面积,当半径为1000时,可以看到圆周率

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)
    input("输入回车关闭。")

 

提供另一种巴塞尔问题的解法:

import math
import time


def mathPi(n):
    num_in_circle = 0
    sum = 0
    start = time.perf_counter()
    for i in range(1, n):
        sum += 1 / i ** 2

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

    pi = math.sqrt(sum * 6)
    print()  # 打印进度条2
    return pi


if __name__ == '__main__':
    print(mathPi(10 ** 6))
    print(math.pi)

 

加入VIP


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

立马 了解一下