""" Implementation of Newton's method, from lecture 29/9. """ 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 #solve the equation e**(-0.1* x**2) * sin(pi * x / 2) = 0: def g(x): return np.exp(-0.1 * x**2) * np.sin(np.pi * 0.5 * x) def dg(x): dg1 = -2*0.1*x*np.exp(-0.1*x**2)*np.sin(np.pi/2*x) dg2 = np.pi/2*np.exp(-0.1*x**2)*np.cos(np.pi/2*x) return dg1 + dg2 x = np.linspace(0,20,201) y = g(x) #plt.plot(x, y) #plt.show() #print(g(1.5)) #print(dg(1.5)) x_val, iter, f_val = Newton(g, 1.5, dg) print(f'Found approximate root x = {x_val:g} with f(x) = {f_val:g}, in {iter} iterations')