三分法

三分法 用于求单峰函数顶点

对于已知 [l, r]中函数单峰

求得 [l + (r - l) / 3, r - (r - l) / 3] 即横坐标的两个三等分点

计算这两点的函数值(使用秦九韶即可

较远离顶点的那个(比如向上的峰 就取函数值比较小的那个三等分点)作为下一次的边界

每次把范围缩小三分之一

与找零点的二分法十分类似

模板题链接:

 
附上代码:
 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstdlib>
 4 #include <cmath>
 5 using namespace std;
 6 const int N = 15;
 7 const double eps = 1e-7;
 8 int n;
 9 double l, r;
10 double a[N];
11 
12 double qjs(double x){
13     double ans = 1.0;
14     for(int i = n; i >= 2; i--)
15         ans = ans * a[i] * x + 1.0;
16     ans = ans * a[1] * x + a[0];
17     return ans;
18 }
19  
20 int main(){
21     scanf("%d%lf%lf", &n, &l, &r);
22     for(int i = n; i >= 0; i--)
23         scanf("%lf", &a[i]);
24     for(int i = n; i >= 2; i--){
25         a[i] /= a[i - 1];
26     }
27     double t1, t2;
28     while(r - l > eps){
29         t1 = l + (r - l) / 3;
30         t2 = r - (r - l) / 3;
31         if(qjs(t1) > qjs(t2)) r = t2;
32         else l = t1;
33     }
34     printf("%.5lf", l);
35     return 0;    
36 }
View Code
原文地址:https://www.cnblogs.com/hjmmm/p/9426387.html