Part 4. Metode Bisection

 


Berikut saya lampirkan code Metode Bisection dengan python

import numpy as np

import matplotlib.pyplot as plt

 

# Mendefinisikan fungsi dan variabel

def f(x): return 2*x**3 - 3

xl, xu, tol = -1, 2, 0.0001

 

# Membuat dan menyimpan plot

x = np.linspace(-3, 3, 200)

plt.plot(x, f(x), linewidth=3)

plt.grid(True)

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

plt.xlabel('x')

plt.ylabel('f(x)')

plt.savefig('Bisection_Method.pdf')  # Menyimpan plot sebagai PDF dengan nama Bisection_Method

plt.show()

 

# Cek apakah akar berada di antara xl dan xu

if f(xu) * f(xl) >= 0:

    print('Nilai tebakannya salah! Masukkan xl dan xu yang baru')

else:

    # Menampilkan heading untuk iterasi

    print('xl\t\t xu\t\t xr\t\t f(xr)')  # Menampilkan heading

    # Metode biseksi dengan tampilan proses iterasi

    for _ in range(1000):

        xr = (xu + xl) / 2

        print(f'{xl:.6f}\t {xu:.6f}\t {xr:.6f}\t {f(xr):.6f}')  # Menampilkan iterasi dengan format

       

        if f(xu) * f(xr) < 0: xl = xr

        else: xu = xr

        if np.abs(f(xr)) < tol: break

 

    print(f'Solusi akarnya adalah: {xr:.6f}')

    print(f'Nilai f(x), x = akar adalah: {f(xr):.6f}')

    #print(f(xr))  # Nilai f(x) di akar

 

Post a Comment

0 Comments