import math def f(x): return x**3 - 3 def df(x): return 3 * x**2 def g(x): return 5*x + math.log(x, math.e) - 10000 def dg(x): return 5 + 1/x def h(x): return 2 - x**2 - math.sin(x) def dh(x): return -2*x - math.cos(x) def j(x): return x**2 - 10 def dj(x): return 2*x def k(x): return math.log((x**2 + 1), math.e) - math.e**(0.4*x)*math.cos(math.pi * x) def dk(x): return math.pi * math.e**((2 * x) / 5) * math.sin(math.pi * x) - (((2 * math.e**((2 * x) / 5)) * math.cos(math.pi * x)) / 5) + ((2 * x) / (x**2 + 1)) def calc_relative_error(current_error, last_error): return abs((current_error - last_error) / current_error) def newton_rhapson_f(x, n, tol): for i in range(n): if f(x) == 0: return x if df(x) == 0: break last_estimate = x x = x - (f(x) / df(x)) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 def newton_rhapson_g(x, n, tol): for i in range(n): if g(x) == 0: return x if dg(x) == 0: break last_estimate = x x = x - (g(x) / dg(x)) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 def newton_rhapson_h(x, n, tol): for i in range(n): if h(x) == 0: return x if dh(x) == 0: break last_estimate = x x = x - (h(x) / dh(x)) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 def newton_rhapson_j(x, n, tol): for i in range(n): if j(x) == 0: return x if dj(x) == 0: break last_estimate = x x = (x - (j(x) / dj(x))) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 def newton_rhapson_k(x, n, tol): for i in range(n): if k(x) == 0: return x if dk(x) == 0: break last_estimate = x x = (x - (k(x) / dk(x))) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 # Shared variables max_iter = 100 # Function specific variables f_x_start = 2.5 g_x_start = 3 h_x_start = -2 h_x2_start = 3 j_x_start = 3 k_x_start = -2 root_f = newton_rhapson_f(f_x_start, 100, 1.E-9) root_g = newton_rhapson_g(g_x_start, 100, 1.E-9) root_h = newton_rhapson_h(h_x_start, 100, 1.E-9) root_h2 = newton_rhapson_h(h_x2_start, 100, 1.E-9) root_j = newton_rhapson_j(j_x_start, 100, 1.E-9) root_k = newton_rhapson_k(k_x_start, 100, 1.E-9) print(root_f) print(root_g) print(root_h) print(root_h2) print(root_j) print(root_k)
Comments