標題:使用遞迴函式計算二分法
使用遞迴
VC++ (recursion.cpp):
//Chapter 3 - Recursion
#include <iostream>
using namespace std;
const int No = 1000;
const double tolerance = 0.00001;
const double minimal = 0;
const double maximal = 1;
double equation(double);
double determine(double, double, double=equation(minimal), int=0);
int main(void)
{
cout << "Best: " << scientific << determine(minimal, maximal) << endl;
system("pause");
return 0;
}
double determine(double a, double b, double fa, int n) {
double p = 0, fp = 0;
p = a+(b-a)/2;
fp = equation(p);
//cout << dec << n << '\t' << scientific << p << endl;
if(( fp==0 || (b-a)/2 < tolerance ) || n >= No)
return p;
return (fa*fp>0) ? determine(p, b, fp, n+1) : determine(a, p, fa, n+1);
}
double equation(double x) {
return x - 1/pow(2.0, x);
}
/*double equation(double x) {
return pow(x, 4)-2*pow(x, 3)-4*pow(x, 2)-4*x+4;
}*/
不使用遞迴
VC++ (bisectionMethod.cpp):
//Chapter 3 - Bisection Method
#include <iostream>
using namespace std;
const int No = 1000;
const double tolerance = 0.00001;
const double minimal = 0;
const double maximal = 1;
double equation(double);
int main(void)
{
int i=0;
double x=0, y=0, fa=0, fp=0, p=0, a=0, b=0;
a = minimal;
b = maximal;
fa = equation(a);
while(i<No) {
p = a+(b-a)/2;
fp = equation(p);
if(fp==0 || (b-a)/2 < tolerance) {
break;
}
if(fa*fp>0) {
a = p;
fa = fp;
} else {
b = p;
}
i++;
}
cout << scientific << p << endl;
system("pause");
return 0;
}
/*
double equation(double x) {
return pow(x, 4)-2*pow(x, 3)-4*pow(x, 2)-4*x+4;
}
*/
double equation(double x) {
return x - 1/pow(2.0, x);
}
說明:
比較遞迴與不遞迴方式計算二分法。