1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
double f(double, double[],int);
double deriv(double,double[],int);
int main()
{
cout<<"What is the degree of the polynomial equation of the form f(x)=0?";
int d;
cin>>d;
double coef[d+1];
int i=d;
while(i<=d && i>=0)
{
if(i>0)
{
cout<<"Enter the coefficient of the x^"<<i<<" term: ";
cin>>coef[i];
i--;
}
if (i==0)
{
cout<<"Enter the constant term: ";
cin>>coef[i];
i--;
}
}
cout<<"Enter a guess for the solution: ";
double x0;
cin>>x0;
//cout<<"the derivative of f(x0)= "<< deriv(x0,coef,d+1)<<endl;
//cout<<"the value of f(x0)= "<<f(x0, coef,d+1)<<endl;
double x1=x0-f(x0, coef,d+1)/deriv(x0,coef,d+1);
//cout<<x1-x0<<endl;
int n=1, j=1;
char t='y';
while(t=='y')
{
while(n<1000*j)
{
double temp=x1;
x1=temp-f(temp, coef,d+1)/deriv(temp,coef,d+1);
n++;
//cout<<n<<" "<<x1<<endl;
if( abs(x1-temp)<0.001)
{
cout<<"One solution is "<<x1<<endl;
system("Pause");
return 2;
}
}
cout<<"I have gone through "<<n<<" times of the process, and haven't found a solution."<<endl;
cout<<"Do you want me go through some more? enter y for yes, anything else for no.";
cin>>t;
if (t!='y')
cout<<"No solution has been found.";
if(t=='y')
j++;
}
cout<<endl;
system("Pause");
return 4;
}
double f(double x, double a[], int n)
{
double sum=0;
while(n>0)
{
sum+=a[n-1]*pow(x, n-1);
n--;
}
return sum;
}
double deriv(double x, double a[], int n)
{
double deriv=0;
while(n>0)
{
deriv+=a[n-1]*(n-1)*pow(x,n-2);
n--;
}
return deriv;
}
| |