newton迭代法计算公式:(参考数值分析(第四版)P148——P152)
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f'(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f'(x0),称x1为r的一次近似值。过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f'(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f'(x(n)),称为r的n+1次近似值,上式称为牛顿迭代公式。
下面列出Newton法的计算步骤:
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=2199
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;
double x,y,r;
#define f 8*x*x*x*x+7*x*x*x+2*x*x+3*x+6-y
#define f1 32*x*x*x+21*x*x+4*x+3
double newton(double x)
{
int k=0;
while(fabs(f)>1e-6)
{
x=x-(f)/(f1);
k++;
if(k>50)
return -1;
}
return x;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>y;
int sign=0;
for(double x=0.0;x<100;x++)
{
r=newton(x);
if(r<=100.0&&r>=0.0)
{
sign=1;
break;
}
}
if(sign==0)
cout<<"No solution!"<<endl;
else
cout<<setiosflags(ios::fixed)<<setprecision(4)<<r<<endl;
}
return 0;
}