在 Python 3 中制作表格(初学者)

Fru*_*uif 7 python python-3.x

所以我刚开始在学校学习 Python 3,我们必须制作一个函数,将a作为参数,选择一个合理的 x 值,并返回a平方根的估计值。

我们还必须创建一个函数来测试它。我们必须编写一个名为 test_square_root 的函数来打印一个表,其中第一列是一个数字a;第二列是用第一个函数计算的a 的平方根;第三列是 math.sqrt 计算的平方根;第四列是两个估计值之间差异的绝对值。

我写了第一个求平方根的函数,但我不知道如何制作这样的表格。我在这里阅读了有关 Python3 中表格的其他问题,但我仍然不知道如何将它们应用到我的函数中。

def mysqrt(a):
    for x in range(1,int(1./2*a)):
        while True:
            y = (x + a/x) / 2
            if y == x:
                break
            x = y
    print(x)
print(mysqrt(16))
Run Code Online (Sandbox Code Playgroud)

Jac*_*ans 9

如果您被允许使用库

from tabulate import tabulate
from math import sqrt


def mysqrt(a):
    for x in range(1, int(1 / 2 * a)):
        while True:
            y = (x + a / x) / 2
            ifjl y == x:
                break
            x = y
    return x


results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))
Run Code Online (Sandbox Code Playgroud)

输出

  num    mysqrt     sqrt
-----  --------  -------
   10   3.16228  3.16228
   11   3.31662  3.31662
   12   3.4641   3.4641
   13   3.60555  3.60555
   14   3.74166  3.74166
   15   3.87298  3.87298
   16   4        4
   17   4.12311  4.12311
   18   4.24264  4.24264
   19   4.3589   4.3589
Run Code Online (Sandbox Code Playgroud)

如果没有关于如何在此处打印表格数据(带和不带库)的大量示例:将列表打印为表格数据