I have the following code for the Babylonian method:
number = abs(float(125348))
guess = abs(float(600))
epsilon = 0.001
while True:
difference = guess**2 - number
print('{} : {}'.format(round(guess, 4), round(difference, 4)))
if abs(difference) <= epsilon:
break
guess = (guess + number / guess) / 2.0
which gives the output
600.0 : 234652.0
404.4567 : 38237.1952
357.1868 : 2234.4368
354.059 : 9.7833
354.0452 : 0.0002
and I'd like to tabulate the results in the terminal, using PrettyTable, as such:
from prettytable import PrettyTable
t = PrettyTable(['Square Root', 'Difference'])
t.add_row(['600', 234652.0])
t.add_row(['404.4567', 38237.1952])
t.add_row(['357.1868', 2234.4368])
t.add_row(['354.059', 9.7833])
t.add_row(['354.0452', 0.0002])
print(t)
+-------------+------------+
| Square Root | Difference |
+-------------+------------+
| 600 | 234652.0 |
| 404.4567 | 38237.1952 |
| 357.1868 | 2234.4368 |
| 354.059 | 9.7833 |
| 354.0452 | 0.0002 |
+-------------+------------+
What would be the best way at going about combining both blocks of code, so it simultaneously tabulates the results for the square root? I'm open to feedback on my code as well, and I'm looking for ways to improve it.
from Tabulating the results in the terminal using PrettyTable
No comments:
Post a Comment