1.1節 プログラムの要素
問題1.1~1.6はSchemeの練習なのでパス。
問題1.7~1.8:平方根計算の改善と立方根
----
//ヘッダincludeと関数プロトタイプ宣言は略
int
main(int argc, char** argv)
{
cout<<"Excersize
1.7:"<<endl;
const double r1(calculateSquareRoot(2.0));
cout<<setprecision(16)<<"sqrt(2)="<<r1<<endl
<<"sqrt(2)^2="<<r1*r1<<endl;
const double
r2(calculateSquareRoot(10000));
cout<<endl<<setprecision(16)<<"sqrt(10000)="<<r2<<endl
<<"sqrt(10000)^2="<<r2*r2<<endl;
const double
r3(calculateSquareRoot(0.0001));
cout<<endl<<setprecision(16)<<"sqrt(0.0001)="<<r3<<endl
<<"sqrt(0.0001)^2="<<r3*r3<<endl;
cout<<endl<<"Excersize
1.8:"<<endl;
const double c1(calculateCubicRoot(2.0));
cout<<setprecision(16)<<"cbrt(2)="<<c1<<endl
<<"cbrt(2)^3="<<c1*c1*c1<<endl;
return(0);
}
const
double calculateSquareRoot(const double x)
{
return(squareRootIteration2(1.0,x,x));
}
const
bool isGoodEnoughSquareRoot(const double guess, const double x)
{
if (abs(x-guess*guess)<0.001){
return(true);
}
return(false);
}
const
double average(const double x, const double y)
{
return((x+y)/2.0);
}
const
double improveGuessSquareRoot(const double guess,const double x)
{
return(average(guess, x/guess));
}
const
double squareRootIteration(const double guess, const double x)
{
if(isGoodEnoughSquareRoot(guess,x)){
return(guess);
}else{
return(squareRootIteration(improveGuessSquareRoot(guess,x),x));
}
}
const
bool isGoodEnoughSquareRoot2(const double guess, const double oldGuess)
{
if (abs((guess-oldGuess)/guess)<0.001){
return(true);
}
return(false);
}
const
double squareRootIteration2(const double guess, const double oldGuess, const
double x)
{
if(isGoodEnoughSquareRoot2(guess,oldGuess)){
return(guess);
}else{
return(squareRootIteration2(improveGuessSquareRoot(guess,x),guess,x));
}
}
const
double calculateCubicRoot(const double x)
{
return(cubicRootIteration(1.0,x));
}
const
bool isGoodEnoughCubicRoot(const double guess, const double x)
{
if (abs(x-guess*guess*guess)<0.001){
return(true);
}
return(false);
}
const
double improveGuessCubicRoot(const double guess,const double x)
{
return(average(guess,
(x/guess/guess+2*guess)/3.0));
}
const
double cubicRootIteration(const double guess, const double x)
{
if(isGoodEnoughCubicRoot(guess,x)){
return(guess);
}else{
return(cubicRootIteration(improveGuessCubicRoot(guess,x),x));
}
}
--------------
出力
--------------
Excersize
1.7:
sqrt(2)=1.41421356237469
sqrt(2)^2=2.000000000004511
sqrt(10000)=100.0000002549074
sqrt(10000)^2=10000.00005098149
sqrt(0.0001)=0.01000000002549074
sqrt(0.0001)^2=0.0001000000005098149
Excersize
1.8:
cbrt(2)=1.259765013452635
cbrt(2)^3=1.999257014785836
0 件のコメント :
コメントを投稿