Guest User

Untitled

a guest
Dec 11th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <cmath>
  5. #include <string>
  6.  
  7. using namespace std;
  8.  
  9. double funcval(double, double[], int );
  10. double derival(double, double[], int);
  11.  
  12. int main (){
  13.     //vector<double> coef;
  14.     int coefNum;
  15.     ifstream file("polynomial.txt");
  16.     if (!file){
  17.         return 0;
  18.     }
  19.     string useless;
  20.     getline(file, useless);
  21.     file >> coefNum;
  22.     double poly[coefNum + 1];
  23.     while (file.good()){
  24.         int d;
  25.         file >> d;
  26.         file >> poly[d];
  27.         cout << poly[d] << "    ";
  28.     }
  29.     cout << endl;
  30.     for (int i = 0; i<=coefNum; i++){
  31.     cout << poly[i] << "    ";
  32.     }
  33.     file.close();
  34.  
  35.     double xval;
  36.     cout<<"Enter an initial estimate for the root.  ";
  37.     cin>>xval;
  38.     double h=.002;
  39.     int dir = -1;
  40.     while (h > .000002){
  41.         if (derival(xval + h * dir, poly, coefNum) * dir < 0){
  42.             xval += h;
  43.             cout << xval << endl;
  44.         } else {
  45.             dir *= -1;
  46.             h /= 10;
  47.         }
  48.         //cout << h << endl;
  49.     }
  50.     cout << funcval(xval, poly, coefNum);
  51.  
  52.     return 0;
  53. }
  54.  
  55.  
  56. double funcval(double xval, double coeff[], int deg){
  57.     double y = 0;
  58.     for(int i = 0; i <= deg; i++){
  59.         y = y + coeff[i] * pow(xval, i);
  60.     }
  61.     return y;
  62. }
  63. double derival(double xval, double coeff[], int deg){
  64.     double dy = 0;
  65.     for (int i = 1; i <= deg; i++){
  66.         dy = dy + coeff[i] * pow(xval, i - 1);
  67.     }
  68.     return dy;
  69. }
Add Comment
Please, Sign In to add comment