Skip to content
Snippets Groups Projects
Commit 842e0985 authored by iliya's avatar iliya
Browse files

feat: added newton's method

parent 21dca3cb
No related branches found
No related tags found
No related merge requests found
......@@ -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)}")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment