#!/usr/bin/env python3 '''This file contains a trivial implementation of Netwon Method written in python3 for educational purposes. The related video can be found at the following URL: Author: Leonardo Tamiano. Date: 2021-09-13 ''' import math # ------------------------- # Global variables PRECISION = 0.000001 # ------------------------- # General math functions def my_abs(x): if x >= 0: return x else: # x < 0 return -x def square(x): return x**2 def average(x, y): return (x + y) / 2 # ------------------------- # Functions for square root def good_enough(approx, x): global PRECISION if my_abs(square(approx) - x) >= PRECISION: return False else: return True def improve_approximation(approx, x): return average(approx, x / approx) def square_root(x): approx = 1.0 while not good_enough(approx, x): approx = improve_approximation(approx, x) return approx # ------------------------- def test(): numbers_to_test = list(range(1, 101)) for number in numbers_to_test: our_square_root = square_root(number) python_square_root = math.sqrt(number) abs_difference = my_abs(our_square_root - python_square_root) message = f"number={number}, our_square_root={our_square_root}, python_square_root={python_square_root}, difference={abs_difference}" if abs_difference > PRECISION: print("[ERROR]: " + message) else: print("[INFO]: " + message) # ------------------------- if __name__ == "__main__": test()