HDU 2199
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2199
题意:
求一个给定高次方程的根。
思路:
练习牛顿迭代。至于为什么要遍历所有整数点来取根暂且不知,精度的取法和退出方式好像也有讲究。
源码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const double eps = 1e-6;
double Newton_iterative(double a, double b, double c, double d, double e, double x0)
{
int cnt = 0;
double x = x0;
while(1){
x0 = x;
long double f1 = ((((a * x + b) * x + c) * x + d) * x + e);
long double f2 = (((4 * a * x + 3 * b) * x + 2 * c) * x + d);
x = x0 - f1 / f2;
cnt++;
if(fabs(f1) < eps)
break;
if( cnt > 50)
return -1;
}
return x;
}
int main()
{
double a, b, c, d, e;
a = 8, b = 7, c = 2, d = 3;
int t;
scanf("%d", &t);
while(t--){
double lv;
scanf("%lf", &lv);
e = 6 - lv;
int ok = 0;
double u = 0;
double x;
for(u = 0.0 ; u < 100.0 ; u++){
x = Newton_iterative(a, b, c, d, e, u);
if(x >= 0 && x <= 100){
// printf("u = %f\n", u);
ok = 1;
break;
}
}
if(ok)
printf("%.4f\n", x);
else
printf("No solution!\n");
}
return 0;
}