Skip to content

Instantly share code, notes, and snippets.

@sayyidyofa
Created September 24, 2019 13:16
Show Gist options
  • Save sayyidyofa/429f5446caf3e22d648c328c1f918cad to your computer and use it in GitHub Desktop.
Save sayyidyofa/429f5446caf3e22d648c328c1f918cad to your computer and use it in GitHub Desktop.
Snippet Kode Octave untuk mencari akar persamaan dengan menggunakan metode fixed point
pkg load symbolic
# x = sym("x");
# f = inline("sqrt(2*x + 3)");
function akar = iterasi(fungsi_param, start_point, toleransi=0, verbose=true, show_plot=false)
x_coords = []; # Juga untuk Xr
y_coords = [];
intervals = []; # |Xr+1 - Xr|
fungsi = inline(fungsi_param)
iter_awal = fungsi(start_point); # Iterasi ke-0
ret_iter = 0;
iterasi_ke = 1;
selisih = 0;
while (abs(iter_awal - ret_iter) > toleransi) # Iterasi ke-1 s.d selesai
if(verbose==true)
disp("\n");
disp(["Iterasi ke-", num2str(iterasi_ke)]);
disp(["Xr:\t", num2str(iter_awal)]);
disp(["|Xr+1 - Xr|:", num2str(abs(iter_awal - ret_iter))]);
endif
selisih = abs(iter_awal - ret_iter);
intervals = vertcat(intervals, abs(iter_awal - ret_iter));
x_coords = vertcat(x_coords, iter_awal);
ret_iter = iter_awal;
iter_awal = fungsi(iter_awal);
y_coords = horzcat(y_coords, selisih);
iterasi_ke++;
#Kalau selisihnya malah membesar...
#if(y_coords(1,2) > y_coords(1,1))
# ret_iter = 0
# iter_awal = 0
#endif
if(iterasi_ke > 1000)
ret_iter = 0;
iter_awal = 0;
endif
endwhile
if(verbose==true)
disp("\n");
disp(["Selisih(", num2str(selisih), ") lebih kecil atau sama dengan Toleransi(", num2str(toleransi), ")"]);
endif
#if(ret_iter==0)
# akar = "Tidak ditemukan!"
#elseif(ret_iter = Inf)
# akar = "Tidak ditemukan!"
#else
# akar = ret_iter
#endif
akar = ret_iter
if(show_plot==true)
plot(x_coords, y_coords, "xb")
x_coords
y_coords
endif
endfunction
# iterasi("sqrt(2*x + 3)", 4, 0.000001, false, false)
iterasi("sqrt(6*x - 8)", 5, 0.001, show_plot=true);
iterasi("(x^2 + 8)/6", 3, 0.001);
# plot([1, 2, 3], [1, 3, 9])
# ezplot(f, [4,9])
# print -deps graph.eps
# [a, ierror, nfneval] = quad(f, -4, 9);
# display('Area: '), disp(double(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment