Program mencari akar dari persamaan kuadrat tanpa menggunakan fungsi sqrt() dengan menggunakan Metode Bagi Dua.
Metode berikut saya temukan dari http://en.wikipedia.org/wiki/Bisection_method.
Jangan cuma di copas aja. Coba dipelajari gimana kerjanya..
/*======================================================================
PSEUDOCODE
INPUT: Function f, endpoint values a, b, tolerance TOL, maximum iterations NMAX
CONDITIONS: a < b, either f(a) < 0 and f(b) > 0 or f(a) > 0 and f(b) < 0
OUTPUT: value which differs from a root of f(x)=0 by less than TOL
N ← 1
While N ≤ NMAX { limit iterations to prevent infinite loop
c ← (a + b)/2 new midpoint
If (f(c) = 0 or (b – a)/2 < TOL then { solution found
Output(c)
Stop
}
N ← N + 1 increment step counter
If sign(f(c)) = sign(f(a)) then a ← c else b ← c new interval
}
Output("Method failed.") max number of steps exceeded
=======================================================================*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b, c ;
float ats, bwh, x; //batas atas, batas bawah, nilai tengah
int n, nMax; //untuk looping
float tol, y, z; //toleransi, y = f(x), z = f(bwh)
printf("ax^2 + bx + c = 0\n");
printf("Masukkan 'a', 'b', 'c': ");scanf("%d %d %d", &a, &b, &c);
printf("Masukkan batas atas & batas bawah kira-kira x berada: ");scanf("%f %f", &bwh, &ats);
n=1; //inisialisasi untuk looping
nMax=25;
tol=0.0001; //batas akurasi yang diterima
while (n<=nMax) { //mencegah looping terus menerus
x = (bwh+ats)/2; //mencari nilai tengah
y=a*x*x + b*x + c; //nilai f(x)
z=a*bwh*bwh + b*bwh + c;
if ((y ==0) || ((ats - bwh)/2)<tol) {
printf("hasilnya adalah %.3f", x); //cetak 3 angka dibelakang koma
break; //berhenti looping
}
n++;
//menentukan batas atas atau batas bawah yang pindah ke tengah
if (y>0) {
if (z>0) {
bwh=x;}
else {
ats=x;}
}
else {
if (z>0) {
ats=x;}
else {
bwh=x;}
}
}
printf("\nselesai");
getch();
}