Good Bisection Method Output
Jan 2, 2014 at 3:21am UTC
Hello everyone, my code below solve for the root of the function f(x) = .5x - sin(x). It is working fine but i want to add a little bit to it.
I want to implement the following output without using printf(). How would i implment it? please help me modify my code.. i'm struggling.. thanks!:
_____________________________________________________________________
Iteration x+ x- f(x+) f(x-) midpoint
_____________________________________________________________________
1 4 2 -.08093 .9568 3
2 3 2 .0088 -.8093 2.5
3 3 2.5 .0088 .65153 2.75
4 2.75 2.5 .99333 .65153 2.625
.
.
.
______________________________________________________________________
The approximate root is: 2.625
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
#include <iostream>
#include <math.h>
using namespace std;
double f(double );
int main()
{
double a, b, lv, rv, midv, mid, root, tol;
cout << "Enter a: " ;
cin >> a;
cout << "Enter b: " ;
cin >> b;
cout << "Enter tolerable error: " ;
cin >> tol;
do
{
mid=(a+b)/2;
rv=f(b);
lv=f(a);
midv=f(mid);
if (midv==0)
{
root=mid;
break ;
}
if (midv*lv<0)
{
b=mid;
}
else
a=mid;
}while ((b-a)>tol);
root=(a+b)/2;
cout << " The Root is approximately: " ;
cout << root;
cin.get();
cin.get();
return 0;
}
double f(double x)
{
return .05*x-sin(x);
}
Last edited on Jan 2, 2014 at 4:11am UTC
Jan 2, 2014 at 4:07am UTC
Are you sure this is right?
if (midv*lv<0)
Jan 2, 2014 at 4:14am UTC
yes. i already tried running it.. it works fine.. my problem is how to implement the output above... please help me modify my code.. thaxnks!
Jan 2, 2014 at 4:36am UTC
The iomanip library has some things that would be useful.
Here's an example:
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
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
cout << "Iteration x+ x- f(x+) f(x-) midpoint" << endl;
cout << "_____________________________________________________________________" << endl;
int iteration = 0;
int xplus = 6666666;
int xneg = 999999;
double fxplus= .999999;
double fxneg = .999;
double midpoint = 5.5;
cout << setw(5) << iteration << ' '
<< setw(10) << xplus << ' '
<< setw(11) << xneg << ' '
<< setw(12) << fxplus << ' '
<< setw(12) << fxneg << ' '
<< setw(10) << midpoint << ' '
<< endl;
return 0;
}
Jan 4, 2014 at 8:36am UTC
problem solved! Thanks much!
Topic archived. No new replies allowed.