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
|
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
double RootMethod1(double fx1, double E, double I, double x1, double x2, double root1 );
double RootMethod2(double fx1, double E, double I, double x1, double x2, double root2 );
int main()
{
int choice;
double x, x1, x2, x3, I, E, fx1, root1, root2;
ofstream outfile;
outfile.open("RootMethod1.txt");
outfile.open("RootMethod2.txt");
cout << "this is a root finding program" << endl;
cout << "which equation would you like to solve for ?" << endl;
cout << "1 : f(x)=2x-2" << endl;
cout << "2 : x^2-2x+2" << endl;
cout << "3 : e^(-1.4x)sin(2x)" << endl;
cout << "4 : x^4-10x^3-2x+3" << endl;
cin >> choice;
cout << "what is your low x guess?" <<endl;
cin >> x1;
cout << "what is your high x guess?" <<endl;
cin >> x2;
cout << "how many iterations do you want?" <<endl;
cin >> I;
cout << "how close do you want the estimate (Epsilon)?" <<endl;
cin >> E;
switch (choice){
case 1:
fx1 = 2*x-2;
root1 = RootMethod1 ( fx1, E, I, x1, x2, root1 );
root2 = RootMethod2 ( fx1, E, I, x1, x2, root2 );
break;
case 2:
fx1 = x*x-2*x+2;
root1 = RootMethod1 (fx1, E, I, x1, x2, root1 );
root2 = RootMethod2 ( fx1, E, I, x1, x2, root2 );
break;
case 3:
fx1 = pow( 10, -1.4*x)*sin(2*x);
root1 = RootMethod1 (fx1, E, I, x1, x2, root1);
root2 = RootMethod2 ( fx1, E, I, x1, x2, root2 );
break;
case 4:
fx1 = (pow(x,4)-pow(10*x,3)-2*x+3);
root1 = RootMethod1 (fx1, E, I, x1, x2, root1);
root2 = RootMethod2 ( fx1, E, I, x1, x2, root2 );
break;
}
cout << "your root is "<< x3 << endl;
outfile.close();
outfile.close();
cout<<endl;
return (0);
}
double RootMethod1 (double fx1, double E, double I, double x1, double x2, double root1 ){
int n;
double c;
for(n=0;n<I;n++){
c=(x1+x2)/2.0;
if(fabs(f(c))<E)
break; //break if solution becomes close to the convergence point(root)
if(f(x1)*f(c)<0.0)
x2=c;
else x1=c;
}
return c;
}
double RootMethod2 (double fx1, double E, double I, double x1, double x2, double root2 ){
}
|