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 103 104 105 106
|
#include <iostream>
#include <math.h>
using namespace std;
int input_pol(double coef[],int& Pow);
double get_fx(double coef[],int Pow,double l,double x,double fx);
double falsi(double, double);
const int MAX = 1000;
void d1();
void d2();
void d3();
void d4();
int main()
{
double coef[1000];
double xnew[MAX], xplus[MAX], xminus[MAX];
int imax, Pow;
input_pol(coef,Pow);
cout << endl;
cout << "Enter first guess: ";
cin >> xplus[0];
cout << endl;
cout << "Enter Second guess: ";
cin >> xminus[0];
cout << endl;
cout << "Set maximum iteration: ";
cin >> imax;
for(int i = 0; i < imax; i++)
{
xnew[i] = falsi(xplus[i], xminus[i]);
if(get_fx(xnew[i])> 0)
{
xplus[i+1] = xnew[i];
xminus[i+1]=xminus[i];
}
else
{
xminus[i+1] = xnew[i];
xplus[i+1]=xplus[i];
}
}
cout << endl << endl;
for(int i = 0; i < imax; i++)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(20);
cout << xnew[i] << endl;
}
cout << endl << endl << endl;
cout << "The Approximate root is: ";
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(20);
cout << endl << endl << xnew[imax - 1];
cin.get();
cin.get();
return 0;
}
int input_pol(double coef[],int& Pow)
{
cout<<"Enter the highest degree in the polynomial: ";
cin>>Pow;
cout<<endl;
for(int i=Pow;i>=0;i--)
{
cout<<"Enter the coefficient of each term with thier corresponding sign."<<endl;
cout<<i+1<<" term: ";
cin>>coef[i];
cout<<coef[i]<<"x^"<<i<<endl;
}
}
double get_fx(double coef[],int Pow,double l,double x,double fx)
{
for(int i=Pow;i>=0;i--)
{
l+=(coef[i]*pow(x,i));
fx=l;
}
return fx;
}
double falsi(double xp, double xm)
{
return xp - get_fx(xp) *(xp - xm)/(get_fx(xp) -get_fx(xm));
}
|