python - Python 3 制作表格(初级)

标签 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))

最佳答案

如果你被允许使用图书馆

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"]))

输出

  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

如果这里有很多关于如何打印表格数据(有和没有库)的例子:Printing Lists as Tabular Data

关于python - Python 3 制作表格(初级),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889141/

相关文章:

python-3.x - 图像处理以去除图像中的噪声

python - 找出所有可能的变化排列

python - 在skimage中绘制渐变椭圆

python - 在Python中获取__future__函数的参数名称

python - 如何根据 ID 镜像新列中的列中的值

python - Pymunk body 对象有问题

python - Django_beanstalkd 中的连接被拒绝

python - 在 Python 和 matplotlib 中连接 3D 散点图中的两个点

python - Python的报纸包返回哪些文章?

python - 不理解 undefined reference