import numpy as np import matplotlib.pyplot as plt def Newton(f, x, dfdx, epsilon=1.0E-7, max_n=100, store = False): f_value = f(x) n = 0 if store: info = [(x, f_value)] while abs(f_value) > epsilon and n <= max_n: x = x - f_value / dfdx(x) n += 1 f_value = f(x) if store: info.append((x, f_value)) if store: return x, info else: return x, n, f_value def f(x): return np.sin(x) * np.exp(-0.1 * x) def dfdx(x): df1 = np.cos(x) * np.exp(-0.1 * x) df2 = np.sin(x) * (-0.1) * np.exp(-0.1 * x) return df1 + df2 x_val, iter, f_val = Newton(f, 4.0, dfdx) print(f'Found approximate root x = {x_val:g} with f(x) = {f_val:g}, in {iter} iterations') """ Terminal> python newton.py Found approximate root x = 3.14159 with f(x) = 1.11874e-11, in 4 iterations """