#includeusing namespace std; //0.618法 class Solution { public: Solution(double x, double y) :a(x), b(y) { cout << "init parameter successn"; } double func(double& x) const//计算函数值 { return x*(x + 2); } double solve(double lamda, double dif) { while (b - a > dif) { x1 = b - lamda*(b - a); x2 = a + lamda*(b - a); f1 = func(x1); f2 = func(x2); if (f1 > f2) { a = x1; x1 = x2; f1 = f2; x2 = a + lamda*(b - a); f2 = func(x2); } else { b = x2; x2 = x1; f2 = f1; x1 = b - lamda*(b - a); f1 = func(x1); } } res = 0.5*(b + a); return func(res); } private: double a; double b; double x1; double x2; double f1; double f2; double res; }; int main() { Solution sol(-4, 6); cout << sol.solve(0.618, 0.3); system("pause"); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)