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 functions(function_name, x): if function_name == "f": return f(x) if function_name == "df": return df(x) if function_name == "g": return g(x) if function_name == "dg": return dg(x) if function_name == "h": return h(x) if function_name == "dh": return dh(x) if function_name == "j": return j(x) if function_name == "dj": return dj(x) if function_name == "k": return k(x) if function_name == "dk": return dk(x) def newton_rhapson(x, n, tol, function_name, derivative): for i in range(n): if functions(function_name, x) == 0: return x if functions(derivative, x) == 0: break last_estimate = x x = x - (functions(function_name, x) / functions(derivative, x)) current_estimate = x relative_error = calc_relative_error(current_estimate, last_estimate) if relative_error <= tol: return current_estimate return -1 # Function specific variables f_start = 2.5 g_start = 3 h_start = -2 h2_start = 3 j_start = 3 k_start = -2 root_f = newton_rhapson(f_start, 10, 1.E-1, "f", "df") root_g = newton_rhapson(g_start, 100, 1.E-9, "g", "dg") root_h = newton_rhapson(h_start, 100, 1.E-9, "h", "dh") root_h2 = newton_rhapson(h2_start, 100, 1.E-9, "h", "dh") root_j = newton_rhapson(j_start, 100, 1.E-9, "j", "dj") root_k = newton_rhapson(k_start, 100, 1.E-9, "k", "dk") print(root_f) print(root_g) print(root_h) print(root_h2) print(root_j) print(root_k)
Comments