Problem Description
Use Newton's method to solve a polynomial equation. The equation can be represented as
The input contains two lines. The first line contains an integer n. The second line contains n+1 floating point numbers .
Examples
When you test your answer with the given examples, the root you get may be slightly different from the examples because of the precision or multiple roots of the equation. All available answers will be accepted! When you debug your program, you can run it on your PC.
1. The equation
Input: 2
-1.0 1.0 1.0
Your Answer: 0.618034
2. The equation
Input: 3
1.0 3.0 3.0 1.0
Your Answer: -1.000000
Note
1. Recommend to use double
to store the values in your program.
2. Don't round your answer! Our test program will substitute your answer back into the given equation and check if the result is near 0.
3. For Newton's method, use the following configuration:
- Maximum iterations:
- Stopping criterion:
4. The iteration of the given equation will be convergent with the configuration mentioned in 3 (Other initial value may not!).
5.
Reference Code
//newton.h
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
/* This is the class you need to implement. *DO NOT* output anything in your code.
We will get your answer as below:
Newton solution(n, a);
double answer = solution.solve();
Feel free to add any members in the class.*/
int iteration=0;
class Newton
{
int n;
vector<double> a;
vector<double> b;
public:
Newton(int _n, vector<double> _a)
{
n=_n;
//cout<<n<<endl;
a=_a;
//cout<<a[2]<<endl;
double tmp;
for(int i=1;i<=n;i++)
{
tmp=a[i]*i;
b.push_back(tmp);
}
//cout<<b[1]<<endl;
}
double solve()
{
// Fill in code here!
//cout<<"here3"<<endl;
if(a[0]==0)
{
return 0.0;
}
return g(0.0);
}
double f(double x)
{
//cout<<"here5"<<endl;
double res=0;
for(int i=0;i<=n;i++)
{
res+=a[i]*pow(x,i);
}
//cout<<"fx0="<<res<<endl;
return res;
}
double df(double x)
{
//cout<<"here6"<<endl;
double res=0;
for(int i=0;i<n;i++)
{
res+=b[i]*pow(x,i);
}
//cout<<"dfx0="<<res<<endl;
return res;
}
double g(double xk)
{
//cout<<"here4"<<endl;
double xk1=xk-f(xk)/df(xk);
iteration++;
if(iteration==pow(10,5))
{
return xk;
}
//cout<<"x1="<<xk1<<endl;
if(fabs(xk1-xk)<pow(10,-6))
{
return xk1;
}
else
{
//cout<<"here7"<<endl;
//system("pause");
return g(xk1);
}
}
};