Recursive Roots 2

Start with  X = . 1 + R2 , R2 No. 2 for the root, the root is pushed against this when the equation to obtain  X ^ 2 -2x- 2 = 0 , the deformation obtained:  X ^ 2 = 2 + . 1 / X 

While x obtained by dividing both sides:  x = 2 + . 1 / x 

So we get a recursive, write a recursive function according to this recursive formula:

#include<cstdio>
double g2(int n,double ans){
    if(n>0){
        return g2(--n,(2+1/ans));
    }
    return ans;
}
int main(){
    double a=g2(50,2.0);
    printf("%.10f\n",a-1);
    return 0;
}

Note that you must write: - n, can not write n--, otherwise it will cause n not diminishing.

After compiling run obtained:

$ ./s
1.4142135624

Note: see reference not understand the mathematical principle: the continued fraction ( C · D · Aldous)

Guess you like

Origin www.cnblogs.com/litifeng/p/12146513.html