Algoritma ini digunakan untuk menghitung nilai cos(x) hingga suku ke-4.
Algoritma Level Tinggi Read(x) //baca input x Read(N) //baca input N cosx = 0; //harga awal cos(x) sign = 1; for k = 1, N do { 2k = 2 * k; x2k = 1; //harga awal x 2k
fact = 1; //harga awal (2k)! for i = 1, 2k do { x2k = x2k * x; //hitung harga x 2k utk k=/=0 fact = fact * i; //hitung harga (2k)! } end for; temp = x2k / fact; //hitung suku x 2k /(2k)! for j = 1, k do { sign = sign * -1; //menghitung tanda untuk setiap suku } end for; temp = sign * temp; cosx = cosx + temp; } end for; cosx = cosx + 1; //tambahkan suku ke k=0, tampilkan output
Algoritma Level Implementasi FUNC COSX {input x[16],N[16] type fraction, start type boolean; output cosx type fraction, done type boolean; local_objects i,j,k,sign type integer, 2k,x2k,fact type fraction;}
WAIT : done 1 || WAIT if start; COUNT : done 0 || cosx 0 || sign 1 || k 1; loop1 : 2k MUL(2, k) || x2k 1 || fact 1 || i 1 || j 1; loop2 : x2k MUL(x2k, x); fact MUL (fact, i); i INC(i); COMP(i,2k) || loop2 if LESS or EQUAL; temp DIV(x2k, fact); loop3 : sign MUL(sign, -1); j INC(j); COMP(j,k) || LESS or EQUAL; temp MUL(sign, temp); cosx ADD(cosx, temp); k INC(k); COMP(k,N) || loop1 if LESS or EQUAL; cosx ADD(cosx, 1); END FUNC
Tabel Iterasi k = 1,N i = 1,2k x2k awal = 1 fact awal = 1 temp= x2k/(2k)! cos(x) 0 = 0 x2k = x2k . x fact = fact . i cosx=cosx+temp 1 1 1.x 1.1 = 1! 2 x.x 1!.2 = 2! x 2 /2! 0 - x 2 /2! 2 1 1.x 1.1 = 1! 2 x.x 1!.2 = 2! 3 x 2 .x 2!.3 = 3! 4 x 3 .x 3!.4 = 4! x 4 /4! - x 2 /2! + x 4 /4! 3 1 1.x 1.1 = 1! 2 x.x 1!.2 = 2! 3 x 2 .x
2!.3 = 3! 4 x 3 .x 3!.4 = 4! 5 x 4 .x 4!.5 = 5! 6 x 5 .x 5!.6 = 6! x 6 /6! - x 2 /2! + x 4 /4! - x 6 /6! 4 1 1.x 1.1 = 1! 2 x.x 1!.2 = 2! 3 x 2 .x
2!.3 = 3! 4 x 3 .x 3!.4 = 4! 5 x 4 .x 4!.5 = 5! 6 x 5 .x 5!.6 = 6! 7 x 6 .x 6!.7 = 7! 8 x 7 .x 7!.8 = 8! x 8 /8! - x 2 /2! + x 4 /4! - x 6 /6! + x 8 /8!