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
|
#include<iostream>
#include<fstream>
#include<cmath>
#include<iomanip>
void Secant(double x0, double x1, double & ans, int & iters, bool & valid);
double f(double);
using namespace std;
ofstream outfile;
int main()
{
double init, x0, x1, root; int ct ; char ch, response; bool good;
outfile.open("out1.txt");
cout<< setiosflags(ios::showpoint|ios::fixed)<<setprecision(8);
outfile<< setiosflags(ios::showpoint|ios::fixed)<<setprecision(8);
do{
good = false;
ct=0;
cout<<"\n\n Enter the initial estimate of the root: ";
cin >> init;
if(f(init) == 0)
cout<<"\n\n The root is "<< init;
else
{
if(f(x0)==f(x1))
init+=0.1;
Secant(init, root, ct, good);
if(good)
cout<<"\n\n The root of the function is " << root << " and it took " << ct << "\n iterations to obtain the root.";
else
cout<<"\n\n No root found using the initial guess " << init;
}
cout<<"\n\n Would you like to continue ? ";
cin>>response;
}while(response == 'y' || response == 'Y');
outfile.close();
}
double f(double x)
{
return pow(x, 3.0) - x - 1;
}
void Secant(double x0, double x1, double & ans, int & iters, bool & valid)//secant method
{
double const tol = 0.000001; double x2;int const Max_iters=100;
x2 = x0 - (x1 - x0)*f(x0)/f(x1)- f(x0);iters++;
outfile<< x1 << endl;
if(f(x1)==0)
valid = true;
while(fabs(x1 - x0) > tol && !valid && iters<Max_iters)
{
x0 = x1;
x1 = x2;
if(f(x1)==f(x0))
x0+=0.1;
x2 = x0 - (x1 - x0)*f(x0)/f(x1)- f(x0);iters++;
outfile<< x1 << endl;
if(f(x1)==0)
valid=true;
}
if(valid)
ans = x1;
if(fabs(x0 - x1) < tol)
{
valid=true;
ans=x1;
}
}
|