diff --git a/rf_methods.py b/rf_methods.py index 3fdf34e258168d1d86cec149399fea66ea46b4ee..a6e5385c8c12ba5f48ecd857a9bb53b5e4d92057 100644 --- a/rf_methods.py +++ b/rf_methods.py @@ -2,8 +2,8 @@ import numpy as np from typing import Callable -def f(x: float) -> float: - return x ** 4 + x ** 3 + x ** 2 - 1 +# def f(x: float) -> float: +# return x ** 4 + x ** 3 + x ** 2 - 1 def g(x: float) -> float: @@ -91,7 +91,7 @@ def iter_bisection(init_start: float, init_stop: float, func: iter = 0 - while np.abs(stop - start) > 1e-9: + while np.abs(stop - start) > 1e-8: if debug: print(f"Iter = {iter}\tx = {cN}\tf(x) = {func(cN)}") @@ -107,12 +107,38 @@ def iter_bisection(init_start: float, init_stop: float, func: return cN +def iter_newton_raphson(init_guess: float, f: Callable[[float], float], + dfdx: Callable[[float], float], debug: bool) -> float: + + prev = init_guess + curr = init_guess + + iter = 0 + + while np.abs(f(curr)) > 1e-9: + if debug: + print(f"Iter = {iter}\tx = {curr}\tf(x) = {f(curr)}") + curr = prev - f(prev) / dfdx(prev) + prev = curr + iter += 1 + + return curr + + if __name__ == "__main__": # print(f"Bissection = {bissect_method(0.5, 2, g)}") # print(f"Regula falsi = {regula_falsi(-3, 7, h)}") # print(f"Bissection = {bissect_method(-3, 7, h)}") # print(f"Regula falsi = {rec_regula_falsi(0, 3, z)}") - print(f"Iter bisection= {iter_bisection(0.5, 2, g, False)}") - print(f"Rec bisection= {rec_bisection(0.5, 2, g, False)}") - print(f"Iter regula falsi= {iter_regula_falsi(0.5, 2, g, False)}") - print(f"Rec regula falsi = {rec_regula_falsi(0.5, 2, g, False)}") + # print(f"Iter bisection= {iter_bisection(0.5, 2, g, False)}") + # print(f"Rec bisection= {rec_bisection(0.5, 2, g, False)}") + # print(f"Iter regula falsi= {iter_regula_falsi(0.5, 2, g, False)}") + # print(f"Rec regula falsi = {rec_regula_falsi(0.5, 2, g, False)}") + + def f(x): + return x ** 3 - 2 * x ** 2 + 1 + + def fprime(x): + return 3 * x ** 2 - 4 * x + 1 + + print(f"Newton = {iter_newton_raphson(0, f, fprime, True)}")