递归求根2

先由 x=1+r2 ,r2代表根号2,逆推根是这个时的方程,得到 x^2-2x-2=0 ,变形得: x^2=2+1/x 

两边同时除以x得: x=2+1/x 

这样我们就得到一个递归式,根据这个递归式写出一个递归函数:

#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
",a-1);
    return 0;
}

注意必须写:--n,不能写n--,否则会导致n无法递减。

编译后运行求得:

$ ./s
1.4142135624

注:看不懂数学原理的参考:连分数(C·D·奥尔德斯)

原文地址:https://www.cnblogs.com/litifeng/p/12146513.html