Python估算π值的思路

img


用函数近似计算π
编写一个函数,给定i返回值m(i)编写一个测试程序显示表格

参考

你题目的解答代码如下:

import math
def m(i):
    s = 0
    fh = 1  #符号
    fm = 1  #分母
    for x in range(i):
        s += fh * (1 / fm)
        fh = fh * -1
        fm = fm + 2
    s = s * 4
    return s

i = int(input("请输入一个整数:"))
print("π的值:{:.4f}".format(m(i)))

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

import prettytable as pt
from prettytable import ALL

tb = pt.PrettyTable()
tb.field_names = ["i","m(i)"]

# 数据加上间隔
tb.hrules =ALL

def m(i):
    s = 0
    for n in range(0,i):
        s += (-1) ** n / (2 * n + 1)
        result = s * 4
        if (1 + n) % 100 == 1:
            import os
            # 清空打印
            if os.name == 'nt':
                os.system('cls')
            else:
                os.system('clear')
            tb.add_row([n + 1,format(result,'.4f')])
            print(tb)


i=int(input("请输入整数i:"))
m(i)

img


有帮助请点击采纳,谢谢