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
|
#include <iostream>
#include <cmath>
using namespace std;
// function prototypes
double linear (double a, double b, double x);
double quadratic (double a, double b, double c, double d, double x);
double cubic (double a, double b, double c, double d, double x);
double NRF1 (double a, double b, double c, double d, double x);
double NRF (double a, double b, double c, double d, double x);
int main ()
{
char again = 'y';
while (again == 'y')
{
// Variable declarations
double a (0.0), b(0.0), c (0.0), d (0.0), x (0.0), r1 (0.0), r2 (0.0), sr (0.0), mr (0.0), lr (0.0);
cout << "Please enter values for a, b, c, and d:" << endl;
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
cout << "c: "; cin >> c;
cout << "d: "; cin >> d;
x = -2*b / 6*a; // root of f''(x)
r1 = x - 0.5;
double f1xr1 = NRF1 (a, b, c, d, r1); // one root of f'(x)
r2 = x + 0.5;
double f1xr2 = NRF1 (a, b, c, d, r2); // other root of f'(x)
sr = r1 - 0.5;
double fx1 = NRF (a, b, c, d, sr); // first root of f(x)
mr = (r1 + r2)/2.0;
double fx2 = NRF (a, b, c, d, mr); // second root of f(x)
lr = r2 + 0.5;
double fx3 = NRF (a, b, c, d, lr); // third root of f(x)
cout << endl << endl;
cout << "The roots of " << a << "x^3 + " << b << "x^2 + " << c << "x + " << d << " are ";
cout << fx1 << ", " << fx2 << ", " << fx3 << endl;
cout << endl << endl;
cout << "Would you like to continue? (y/n): ";
cin >> again;
} // end of loop
cout << endl << endl;
cout << "Good bye!" << endl;
return 0;
}
double cubic (double a, double b, double c, double d, double x)
{
return a*pow(x,3) + b*pow(x,2) + c*x + d;
}
double quadratic (double a, double b, double c, double d, double x)
{
return 3.0*a*pow(x,2) + 2.0*b*x + c;
}
double linear (double a, double b, double x)
{
return 6.0*x + 2.0*b;
}
double NRF1 (double a, double b, double c, double d, double x) // function for the roots of f'(x)
{
double xi (0.0), xi1 (0.0);
int count (0);
do
{
double f1x = quadratic (a, b, c, d, x);
double f2x = linear (a, b, x);
xi = xi1;
xi1 = xi - f1x/f2x;
count++;
} while ( (abs (xi1 - xi) > 0.001) && (count < 200) );
return xi1;
}
double NRF (double a, double b, double c, double d, double x) // function for the root of f(x)
{
double xi (0.0), xi1 (0.0);
int count (0);
do
{
double fx = cubic (a, b, c, d, x);
double f1x = quadratic (a, b, c, d, x);
xi = xi1;
xi1 = xi - fx/f1x;
count++;
} while ( (abs (xi1 - xi) > 0.001) && (count < 200) );
return xi1;
}
|