본문 바로가기
C 언어

C 언어로 방정식의 해를 구하기 (Bisection method)

by treeCoder 2020. 12. 31.

 C 언어로 x^3 - x^2 + 2 = 0 의 해를 구하는 프로그램을 작성하였다.

3차 방정식이므로 3개의 근이 존재하는데, 이 프로그램은 그 중 한 해를 구한다.

 

#include <stdio.h>
#define EP 0.001

double solution(double x) {
    
   return x * x * x - x * x + 2;
   
}

void bisection(double a, double b) {

     if ( solution(a) * solution(b) >= 0) {
        puts("You have not assumed right a and b\n");
        return;
     }

     double c = a;
     while ( (b-a) >= EP) {
      
         c = ( a + b ) / 2;
      
         if ( solution( c ) == 0.0 )
            break;
         else if (solution( c ) * solution( a ) < 0)
            b = c;
         else
            a = c;
     }
     printf("The value of root is : %.6g", c);
}

int main() {
    
    double a = -500;
    double b =  100;

    bisection(a, b);

    return 0;
}

 

수행 결과는 아래와 같다. 결과는 -1 이다. 

 

댓글