Computational Intelligence/수치계산

Secant Method법에 관한 C언어 정리

초인로크 2012. 12. 20. 17:34
반응형

Secant Method 위키백과 링크


앞서 설명했던 뉴턴법은 미분을 이용하는 방법으로,

미분이 간단하게 계산이 되지 않을 경우에 문제가 발생하므로,

미분형태를 [ f'(x) = f(x1)-f(x1-1) / x1-x0 ] 라는 근이식으로 바꿔서 계산하는 방법이 Secant 방법이다.

f'(x) = f(x1)-f(x1-1) / x1-x0 를 앞서 뉴턴법에서 본 x1 = x0 - f(x0)/f'(x0) 식에 대입하면,

x2 = x1 - (f(x1)*(x1-x0) / f(x1)-f(x0)) 라는 식이 나온다.(과정생략)


초기 추정값 x0, x1를 선택해서 대입하면 루프안에서 계산된다.

여기서 사용한건 y=x^2-2 식 이므로, 해가 두개가 나오도록 초기 추정값을 설정할 경우

무한루프에 빠져드므로 주의.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <math.h>
 
double graph (double x);
double secant_method(double x,double y);
 
double graph (double x){
    double y;
    y = (x*x) - 2;
    return y;
}
 
double secant_method(double x0,double x1){
   
    double x2;
    int co=1;
   
    while(1){
        x2 = x1 - (graph(x1)*(x1-x0))/(graph(x1)-graph(x0));
        printf("No.%d answer is %lf\n",co,x2);
 
        x0 = x1;
        x1 = x2;
        co++;
       
        if(fabs(graph(x1)-graph(x0))<0.0000001)
            break;
    }
    return x2;
   
}
 
int main (int argc, const char * argv[])
{
    double a,b,c;
    printf("Input the number (a,b): \n");
    scanf("%lf %lf",&a,&b);
 
    c = secant_method(a,b);
    printf("The answer is %lf\n",c);
    return 0;
}


반응형