Bisection Method in C
Bisection Method in C
Cappo
Newbie
Hi,
I wrote befor about the bisection method in C++. This time I managed to make two sour
But both give me some error that i don't understand. Here are the codes:
Expand|Select|Wrap|Line Numbers
1. #include <iostream>
2. #include <stdlib.h>
3. #include <math.h>
4.
5. using namespace std;
6.
7. double f1( double x) {
8. return x*x-pow(1.034554,2);
9. }
10. double f2( double x) {
11. return 2*x;
12. }
13.
14. double bisection(double (*f)(double),
15.
16. double xL=-100, double xR=100) {
17.
18. double xN;
19.
20. if( (*f)(xL)*(*f)(xR) >0) {
21. cout << "Error!" << endl;
22. return xL;
23. }
24.
25. while (fabs(xL-xR)>0.0001) {
26. xN = (xL+xR)/2;
27. if( (*f)(xL)*(*f)(xN) <0)
28. xR = xN; // i.e. xL and xN have different signs
29. // so xRand xN have the same signs
30. else
31. xL = xN;
32. }
33. return (xL+xR)/2;
34. }
35.
36. int main() {
37. double tmp;
38. cout << bisection(f1,-100,100) << endl;
39. system("PAUSE");
40. }
1. Error!
2. -100
3. Press any key to continue...
1. #include <iostream>
2. #include <cmath>
3. #include <stdlib.h>
4. #include <math.h>
5. using namespace std;
6.
7. int main()
8. {
9. int xR, xL,xM, epsilon;
10. cout <<"Enter a value for the left side: " "\n";
11. cin >> xL;
12. cout <<"Enter a value for the right side: " "\n";
13. cin >> xR;
14. cout <<"Enter a value for epsilon: " "\n";
15. cin >> epsilon;
16.
17. while ((xR - xL) > epsilon)
18.
19.
20. xM = (xR + xL) / 2;
21.
22.
23. if (xL * xM > 0)
24. xL = xM;
25. else
26.
27. xR = xM;
28.
29. system ("pause");
30. return 0;
31. }
Could anyone try the program and help me solve the problem.
I need this program working untill 12 o'clock tonight.
Please try to explain the things in a simple way because i am entirely new to programmin
Thank you!
Ads by Google
horace1
Expert
re: Bisection method in C++
you appear to have your xL and xR start points wrong as there are two roots at -1.03459
test fails
try
Expand|Select|Wrap|Line Numbers
1. cout << bisection(f1,0,100) << endl;
2. cout << bisection(f1,-100,0) << endl;
3.