So I just started learning Python 3 in school, and we had to make a function that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of a computed with the first function; the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.
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))
                PrettyTable class inside the prettytable library is used to create relational tables in Python. It can be installed using the below command.
If you're allowed to use libraries
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"]))
Outputs
  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
Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With