Part 6. Metode Newton-Raphson



Berikut adalah code python untuk Metode Newton-Raphson 

import numpy as np

import matplotlib.pyplot as plt

from sympy import symbols, diff, lambdify

 

# Define symbolic variables and functions

x = symbols('x')

f_sym = x**3 + 2*x - 2

f_prime_sym = diff(f_sym, x)

 

# Convert to numerical functions

f = lambdify(x, f_sym, 'numpy')

f_prime = lambdify(x, f_prime_sym, 'numpy')

 

# Plot

plt.plot(np.linspace(-4, 9, 400), f(np.linspace(-4, 9, 400)), 'r-', linewidth=2)

plt.grid(True)

plt.title('Root of $x^3 + 2x - 2$')

plt.xlabel('$x$')

plt.ylabel('$f(x)$')

plt.axhline(0, color='black', lw=0.5)

plt.axvline(0, color='black', lw=0.5)

plt.savefig('plot_N-R_OK.png')

plt.savefig('plot_N-R_OK.pdf')  # Menyimpan plot sebagai PDF

plt.show()

 

# Print heading for iterations output

print("Iteration | Approximation of Root | Function Value at Root")

 

# Newton-Raphson Method with iteration output

x0 = 1

for i in range(7):

    x_next = x0 - f(x0) / f_prime(x0)

    print(f"{i:9} | {x_next:24} | {f(x_next)}")

    if abs(f(x_next)) < 0.00001:

        break

    x0 = x_next

 

print(f"\nFinal approximation: x = {x0}, f(x) = {f(x0)}")

 

Post a Comment

0 Comments