import numpy as np
import matplotlib.pyplot as plt
def newton(f, df, x0, tol=1e-6, max_iter=100):
puntos = [] # para guardar las aproximaciones
x = x0
for i in range(max_iter):
fx = f(x)
dfx = df(x)
if abs(dfx) < 1e-12:
print("La derivada es muy pequeña. El método falla.")
return None
x_new = x - fx/dfx
puntos.append(x_new)
print(f"Iteración {i+1}: x = {x_new}, f(x) = {f(x_new)}")
if abs(x_new - x) < tol:
return x_new, puntos
x = x_new
return x, puntos
# Definimos la función
# x*np.sin(x) ## x**3-x-2 ## (x-1)**3*(x-2)*(x-3)
def f(x):
return x**3 - x - 2
# derivada
def df(x):
return 3*x**2 - 1
# valor inicial
x0 = 1
# ejecutar el método
raiz, puntos = newton(f, df, x0)
print("\nRaíz aproximada:", raiz)
# GRAFICA
a = 0
b = 2
x = np.linspace(a, b, 400)
y = f(x)
plt.figure(figsize=(8,5))
plt.axhline(0)
plt.plot(x, y)
# puntos del método
for p in puntos:
plt.scatter(p, f(p), s=20)
plt.scatter(raiz, f(raiz), s=20, label="Raíz")
plt.title("Método de Newton-Raphson", fontsize=18)
plt.xlabel("$x$", fontsize=16)
plt.ylabel("$f(x)$", fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend()
plt.grid()
plt.show()
To embed this project on your website, copy the following code and paste it into your website's HTML: