7

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))
Fruitdruif
  • 173
  • 1
  • 1
  • 4
  • when i add print inside the loop it prints all values of x it takes, I only want one value of x, in this case 4.0. – Fruitdruif May 10 '17 at 10:02

2 Answers2

9

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

Community
  • 1
  • 1
Jack Evans
  • 1,697
  • 3
  • 17
  • 33
0
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"]
Shantanu Kher
  • 1,014
  • 1
  • 8
  • 14
  • Please add a description of the changes you are recommending and use a Markdown code block and line returns to format your code. – Ed Lucas Jul 18 '20 at 21:10