2012-08-01

SCIP in C++11 ― 1.3.3節 その3


問題1.36
問題1.35のコードに標準ストリームへの出力を1行混ぜるだけなのだが、
まあ一応全部。
-----
const double fixedPoint
(const function<double(double)>& f,
 const double firstGuess)
{
    const double tolerance(0.00001);
    const function<bool(double,double)> isCloseEnough
        =[tolerance](const double v1,const double v2)
        {return(abs(v1-v2)<tolerance);};
    function<double(double)> Try;
    Try=[&f,&isCloseEnough,&Try](const double guess)->const double{
        cout<<setprecision(16)<<"guess="<<guess<<endl;
        const double next(f(guess));
        if(isCloseEnough(guess,next)){return(next);}
        else{return(Try(next));}
    };
    return(Try(firstGuess));
}

const function<double(double,double)> average
=[](const double a,const double b){return((a+b)/2.0);};

const function<double(double)> xPowXEquation
=[](const double x){return(log(1000.0)/log(x));};

const function<double(void)> xPowXFixedRaw=[](void)
{
    return(fixedPoint(xPowXEquation,2.0));
};
const function<double(void)> xPowXFixedAverageDamped=[](void){
    return(fixedPoint([](const double x)
    {
        return(average(x,xPowXEquation(x)));
    },2.0));
};

int main(int argc, char** argv)
{
    cout<<"without average damping:"<<endl;
    cout<<setprecision(16)<<"Solution="
         <<xPowXFixedRaw()<<endl<<endl;

    cout<<"with average damping:"<<endl;
    cout<<setprecision(16)<<"Solution="
         <<xPowXFixedAverageDamped()<<endl;

    return(0);
}
-----
出力
-----
without average damping:
guess=2
guess=9.965784284662087
guess=3.004472209841214
guess=6.279195757507157
guess=3.759850702401539
guess=5.215843784925895
guess=4.182207192401397
guess=4.827765098344591
guess=4.387593384662677
guess=4.671250085763899
guess=4.481403616895052
guess=4.6053657460929
guess=4.523084967871887
guess=4.577114682047341
guess=4.541382480151454
guess=4.564903245230833
guess=4.549372679303342
guess=4.559606491913287
guess=4.552853875788271
guess=4.557305529748263
guess=4.554369064436181
guess=4.556305311532999
guess=4.555028263573554
guess=4.555870396702851
guess=4.555315001192079
guess=4.555681263543327
guess=4.555439715736846
guess=4.555599009998291
guess=4.555493957531389
guess=4.555563237292884
guess=4.555517548417651
guess=4.555547679306398
guess=4.555527808516254
guess=4.555540912917957
Solution=4.555532270803653

with average damping:
guess=2
guess=5.982892142331043
guess=4.922168721308343
guess=4.628224318195455
guess=4.568346513136242
guess=4.5577305909237
guess=4.555909809045131
guess=4.555599411610624
guess=4.555546552147367
Solution=4.555537551999825

0 件のコメント :

コメントを投稿