您的位置:首页 > 其它

【单峰函数,三分搜索算法(Ternary_Search)】UVa 1476 - Error Curves

2015-03-25 20:09 543 查看

Josephina is a clever girl and addicted to Machine Learning recently. She pays much attention to a method called Linear Discriminant Analysis, which has many interesting properties.

In order to test the algorithm's efficiency, she collects many datasets. What's more, each data is divided into two parts: training data and test data. She gets the parameters of the model on training data and test the model on test data.

To her surprise, she finds each dataset's test error curve is just a parabolic curve. A parabolic curve corresponds to a quadratic function. In mathematics, a quadratic function is a polynomial function of the form f(x) = ax2 + bx + c. The quadratic will degrade to linear function if a = 0.

 

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
const double eps = 1e-14;
const int maxn = 10010;
int a[maxn], b[maxn], c[maxn];
int n;

double F(double x)
{
double ans = a[0]*x*x + b[0]*x + c[0];
for(int i = 1; i < n; i++)
{
ans = max(ans, a[i]*x*x + b[i]*x + c[i]);
}
return ans;
}

void Ternary_Search()
{
double L = 0.0, R = 1000.0;
for(int i = 0; i < 100; i++)
{
double m1 = L+(R-L)/3;
double m2 = R-(R-L)/3;

if(F(m1) < F(m2)) R = m2;
else L = m1;
}
printf("%.4lf\n", F(L));
}
int main()
{

int T; scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%d%d%d", &a[i], &b[i], &c[i]);

Ternary_Search();
}
return 0;
}
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: