473,668 Members | 2,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bisection method in C++

5 New Member
Hello,
I just started programming in C++ and i have a problem with a task.I need to write a program which illustrates the Bisection method in C++. I have some codes, which use the bisection code, but they are written in C not C++. I know that i am asking too much, but i really need to write the program and send it tomorrow(22.01) . I will be very gratefull to those who help me. Here are the codes that I mentioned above:
Expand|Select|Wrap|Line Numbers
  1. /* 
  2.    This is a demonstration program for the 
  3.    rootfinding subroutine 'bisect', given 
  4.    in Section 4.1. 
  5. */ 
  6.  
  7. #include <stdio.h> 
  8. #include <math.h> 
  9.  
  10.  
  11. float fcn(float); 
  12. float sign(float, float); 
  13. void bisect(float(*f)(float), float, float, float, float *, int *); 
  14.  
  15.  
  16. main() 
  17.  
  18.    float a, b, epsilon, root; 
  19.    int ier; 
  20.  
  21.  
  22.    while (1)  { 
  23.  
  24.       /*  Input problem parameters  */ 
  25.  
  26.       printf("\n\n What are a,b,epsilon"); 
  27.       printf("\n to stop, let epsilon=0 : \n"); 
  28.       scanf("%f %f %f", &a, &b, &epsilon); 
  29.       if (epsilon == 0.0) 
  30.          return 0; 
  31.  
  32.       /*  Calculate root  */ 
  33.  
  34.       bisect(fcn, a ,b ,epsilon, &root, &ier); 
  35.  
  36.       /*  Print answers  */ 
  37.  
  38.       printf("\n\n a = %11.4e     b = %11.4e     epsilon = %9.3e", 
  39.                a, b, epsilon); 
  40.       printf("\n root = %14.7e     ier = %1d", root, ier); 
  41.    } 
  42.    system ("pause"); 
  43.     return 0; 
  44.  
  45.  
  46.  
  47. float fcn(float x) 
  48.    float result; 
  49.  
  50.    result = x - exp(-x); 
  51.    return(result); 
  52.  
  53.  
  54. float sign(float a, float b) 
  55.    if (b < 0.0) 
  56.       return(-fabs(a)); 
  57.    else 
  58.       return(fabs(a)); 
  59.  
  60.  
  61. void bisect(float(*f)(float), float a, float b, float eps, 
  62.             float *root, int *ier) 
  63. /* 
  64.    The program uses the bisection method to solve 
  65.    the equation 
  66.       f(x) = 0. 
  67.    The solution is to be in [a,b] and it is assumed 
  68.    that 
  69.       f(a)*f(b) <= 0. 
  70.    The solution is returned in root, and it is to 
  71.    be in error by at most eps. 
  72.  
  73.    ier is an error indicator. 
  74.    If ier=0 on completion of the routine, then the 
  75.    solution has been computed satisfactorily. 
  76.    If ier=1, then f(a)*f(b) was greater than 0, 
  77.    contrary to assumption. 
  78. */ 
  79.  
  80.    const float zero = 0.0, one = 1.0, two = 2.0; 
  81.    float c, fa, fb, fc, sfa, sfb, sfc; 
  82.  
  83.  
  84.    /* Initialize  */ 
  85.  
  86.    fa = (*f)(a); 
  87.    fb = (*f)(b); 
  88.    sfa = sign(one, fa); 
  89.    sfb = sign(one, fb); 
  90.    if (sfa*sfb > 0.0)  
  91.    { 
  92.  
  93.       /*  The choice of a and b is in error  */ 
  94.  
  95.       *ier = 1; 
  96.       return; 
  97.    } 
  98.  
  99.    /* Create a new value of c, the midpoint of [a,b]  */ 
  100.  
  101.    while (1)  { 
  102.       c = (a + b)/two; 
  103.       if (fabs(b-c) <= eps)  
  104.       { 
  105.  
  106.          /* c is an acceptable solution of f(x)=0  */ 
  107.  
  108.          *root = c; 
  109.          *ier = 0; 
  110.          return; 
  111.       } 
  112.  
  113.       /* The value of c was not sufficiently accurate. 
  114.          Begin a new iteration  */ 
  115.  
  116.       fc = (*f)(c); 
  117.       if (fc == zero)  
  118.       { 
  119.  
  120.          /* c is an acceptable solution of f(x)=0  */ 
  121.  
  122.          *root = c; 
  123.          *ier = 0; 
  124.          return; 
  125.       } 
  126.  
  127.       sfc = sign(one, fc); 
  128.       if (sfb*sfc > zero)  
  129.       { 
  130.  
  131.          /*  The solution is in [a,c]  */ 
  132.  
  133.          b = c; 
  134.          sfb = sfc; 
  135.       } 
  136.       else  
  137.       { 
  138.  
  139.          /*  The solution is in [c,b]  */ 
  140.  
  141.          a = c; 
  142.          sfa = sfc; 
  143.       } 
  144.    } 
  145. }


Here is a pseudocode vor Visual Basic:
Expand|Select|Wrap|Line Numbers
  1. 'Bisection Method
  2.  
  3. 'Start loop
  4. Do While (xR - xL) > epsilon
  5.  
  6.   'Calculate midpoint of domain
  7.   xM = (xR + xL) / 2
  8.  
  9.   'Find f(xM)
  10.   If ((f(xL) * f(xM)) > 0) Then
  11.     'Throw away left half
  12.     xL = xM
  13.   Else
  14.     'Throw away right half
  15.     xR = xM
  16.   End If
  17. Loop

Unfortunately this is everything i can give you for the moment. As i mentioned i am new in programming and i can't give any more help.
Jan 21 '07 #1
6 11879
richw42
2 New Member
In most cases, a C program can be compiled as a C++ program, and it will work with only minor fixups. What is it you need, really? Have you tried your C code?
Jan 21 '07 #2
willakawill
1,646 Top Contributor
The only real difference here would be the use of cin and cout for your interface rather than scanf and printf. The rest stays the same
Jan 22 '07 #3
horace1
1,510 Recognized Expert Top Contributor
rather than using pointers when passing parameters to bisect
Expand|Select|Wrap|Line Numbers
  1. void bisect(float(*f)(float), float a, float b, float eps, 
  2.             float *root, int *ier) 
  3.  
you could use reference parameters (which don't exist in C)

also you could make it a template function so it could take parameters of different types (float, double, complex, etc)

for example, this is a copy of the Newton-Raphson method using a template function with reference parameters
Expand|Select|Wrap|Line Numbers
  1. // Newton-Raphson method of finding roots                                     //
  2. //   Passing references to functions f(x) and f'(x) as function parameters    //
  3. //   also demonstrates use of a function template                             //
  4.  
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <math.h>
  8. #include <complex>
  9.  
  10. using namespace std;
  11.  
  12. //----------------------------------------------------------------------------//
  13. // Function template: Newton-Raphson method find a root of the equation f(x)  //
  14. //  see http://en.wikipedia.org/wiki/Newton's_method                          //
  15. // Parameters in:  &x            reference to first approximation of root     //
  16. //                 (&f)(x)       reference to function f(x)                   //
  17. //                 (fdiv)(x)     reference to function f'(x)                  //
  18. //                 max_loop      maxiumn number of itterations                //
  19. //                 accuracy      required accuracy                            //
  20. //            out: &x            return root found                            //
  21. // function result: > 0 (true) if root found, 0 (false) if max_loop exceeded  //
  22. template <class T1>
  23.  int newton(T1 &x, T1 (&f)(T1), T1 (&fdiv)(T1),
  24.                   int max_loop, const double accuracy)
  25.  {
  26.     T1 term;
  27.     do
  28.         {
  29.          // calculate next term f(x) / f'(x) then subtract from current root  
  30.          term = (f)(x) / (fdiv)(x);
  31.          x = x - term;                                               // new root
  32.         }
  33.     // check if term is within required accuracy or loop limit is exceeded
  34.     while ((abs(term / x) > accuracy) && (--max_loop));
  35.     return max_loop;
  36.  }
  37.  
  38. //----------------------------------------------------------------------------//
  39. // test functions
  40.  
  41. double func_1(double x)                       // root is 1.85792
  42.   {  return (cosh(x) + cos(x) - 3.0); }       // f(x) = cosh(x) + cos(x) - 3 = 0
  43.  
  44. double fdiv_1(double x)
  45.   {  return (sinh(x) - sin(x));  }            // f'(x) = sinh(x) - sin(x)
  46.  
  47. double func_2(double x)                       // root is 5.0
  48.   {  return (x*x - 25.0);  }                  // f(x) = x * x - 25 = 0   
  49.  
  50. double fdiv_2(double x)
  51.   {  return (2.0 * x);  }                     // f'(x) = 2x      
  52.  
  53. complex<double> func_3(complex<double> x)     // roots 5 + or - 3
  54.   { return  x*x - 10.0*x + 34.0;   }          // f(x) x^2 - 10x + 34                               
  55.  
  56. complex<double> fdiv_3(complex<double> x)      
  57.   { return  2.0*x -10.0;   }                  // f'(x) 2x - 10                              
  58.  
  59. double func_4(double x)                             // three real roots 4, -3, 1
  60.   {  return 2*x*x*x - 4*x*x - 22*x + 24 ;  }    // f(x) = 2x^3 - 4x^2 - 22x + 24   
  61.  
  62. double fdiv_4(double x)
  63.   {  return 6*x*x - 8*x - 22;  }                       // f'(x) = 6x^2 - 8x - 22     
  64.  
  65. //----------------------------------------------------------------------------//
  66. // Main program to test above function
  67. int main()
  68. {
  69.     cout << "\nFind root of f(x) = cosh(x) + cos(x) - 3 = 0";
  70.     double x = 1.0;                                   // initial 'guess' at root
  71.     if (newton(x, func_1, fdiv_1, 100, 1.0e-8))
  72.           cout << "\n   root x = " << x << ", test of f(x) = " << func_1(x);
  73.     else  cout << "\n   failed to find root ";
  74.  
  75.     cout << "\n\nFind root of f(x) = x * x - 25 = 0";
  76.     x = 1.0;                                          // initial 'guess' at root
  77.     if ( newton(x, func_2, fdiv_2, 100, 1.0e-8))
  78.           cout << "\n   root x = " << x << ", test of f(x) = " << func_2(x);
  79.     else  cout << "\n   failed to find root ";
  80.  
  81.     cout << "\n\nFind root of f(x) = x^2 - 10x + 34  = 0";
  82.     complex<double> xc = complex<double>(1.0, 1.0);   // initial 'guess' at root
  83.     if ( newton(xc, func_3, fdiv_3, 100, 1.0e-8))
  84.           cout << "\n   root x = " << xc << ", test of f(x) = " << func_3(xc);
  85.     else  cout << "\n   failed to find root ";
  86.  
  87.     cout << "\n\nFind root of f(x) = x^2 - 10x + 34  = 0";
  88.     xc = complex<double>(1.0, -1.0);                  // initial 'guess' at root
  89.     if ( newton(xc, func_3, fdiv_3, 100, 1.0e-8))
  90.           cout << "\n   root x = " << xc << ", test of f(x) = " << func_3(xc);
  91.     else  cout << "\n   failed to find root ";
  92.  
  93.     cout << "\n\nFind root of f(x) = 2x^3 - 4x^2 - 22x + 24 = 0";
  94.     x = 5.0;                                          // initial 'guess' at root
  95.     if ( newton(x, func_4, fdiv_4, 100, 1.0e-8))
  96.           cout << "\n   root x = " << x << ", test of f(x) = " << func_4(x);
  97.     else  cout << "\n   failed to find root ";
  98.  
  99.     cin.get();
  100.     return 0;
  101. }
  102.  
  103.  
Jan 22 '07 #4
Cappo
5 New Member
The only real difference here would be the use of cin and cout for your interface rather than scanf and printf. The rest stays the same
I changed the printf and scanf to cout and cin and it here's what i got:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3. #include <stdio.h> 
  4. #include <math.h> 
  5.  
  6.  
  7. float fcn(float); 
  8. float sign(float, float); 
  9. void bisect(float(float), float, float, float, float *, int *); 
  10.  
  11.  
  12. int main() 
  13.  
  14.    float a, b, epsilon, root; 
  15.    int ier; 
  16.  
  17.  
  18.    while (1)  { 
  19.  
  20.       /*  Input problem parameters  */ 
  21.  
  22.       cout <<("\n\n What are a,b,epsilon"); 
  23.       cout <<("\n to stop, let epsilon=0 : \n"); 
  24.       cin >>a, b, &epsilon; 
  25.       if (epsilon == 0.0) 
  26.          return 0; 
  27.  
  28.       /*  Calculate root  */ 
  29.  
  30.       bisect(fcn, a ,b ,epsilon, &root, &ier); 
  31.  
  32.       /*  Print answers  */ 
  33.  
  34.       cout <<("\n\n a = %11.4e     b = %11.4e     epsilon = %9.3e", 
  35.                a, b, epsilon); 
  36.       cout <<("\n root = %14.7e     ier = %1d", root, ier); 
  37.    } 
  38.  
  39.     return 0; 
  40.  
  41.  
  42.  
  43. float fcn(float x) 
  44.    float result; 
  45.  
  46.    result = x - exp(-x); 
  47.    return(result); 
  48.  
  49.  
  50. float sign(float a, float b) 
  51.    if (b < 0.0) 
  52.       return(-fabs(a)); 
  53.    else 
  54.       return(fabs(a)); 
  55.  
  56.  
  57. void bisect(float(*f)(float), float a, float b, float eps, 
  58.             float *root, int *ier) 
  59. /* 
  60.    The program uses the bisection method to solve 
  61.    the equation 
  62.       f(x) = 0. 
  63.    The solution is to be in [a,b] and it is assumed 
  64.    that 
  65.       f(a)*f(b) <= 0. 
  66.    The solution is returned in root, and it is to 
  67.    be in error by at most eps. 
  68.  
  69.    ier is an error indicator. 
  70.    If ier=0 on completion of the routine, then the 
  71.    solution has been computed satisfactorily. 
  72.    If ier=1, then f(a)*f(b) was greater than 0, 
  73.    contrary to assumption. 
  74. */ 
  75.  
  76.    const float zero = 0.0, one = 1.0, two = 2.0; 
  77.    float c, fa, fb, fc, sfa, sfb, sfc; 
  78.  
  79.  
  80.    /* Initialize  */ 
  81.  
  82.    fa = (*f)(a); 
  83.    fb = (*f)(b); 
  84.    sfa = sign(one, fa); 
  85.    sfb = sign(one, fb); 
  86.    if (sfa*sfb > 0.0)  
  87.    { 
  88.  
  89.       /*  The choice of a and b is in error  */ 
  90.  
  91.       *ier = 1; 
  92.       return; 
  93.    } 
  94.  
  95.    /* Create a new value of c, the midpoint of [a,b]  */ 
  96.  
  97.    while (1)  { 
  98.       c = (a + b)/two; 
  99.       if (fabs(b-c) <= eps)  
  100.       { 
  101.  
  102.          /* c is an acceptable solution of f(x)=0  */ 
  103.  
  104.          *root = c; 
  105.          *ier = 0; 
  106.          return; 
  107.       } 
  108.  
  109.       /* The value of c was not sufficiently accurate. 
  110.          Begin a new iteration  */ 
  111.  
  112.       fc = (*f)(c); 
  113.       if (fc == zero)  
  114.       { 
  115.  
  116.          /* c is an acceptable solution of f(x)=0  */ 
  117.  
  118.          *root = c; 
  119.          *ier = 0; 
  120.          return; 
  121.       } 
  122.  
  123.       sfc = sign(one, fc); 
  124.       if (sfb*sfc > zero)  
  125.       { 
  126.  
  127.          /*  The solution is in [a,c]  */ 
  128.  
  129.          b = c; 
  130.          sfb = sfc; 
  131.       } 
  132.       else  
  133.       { 
  134.  
  135.          /*  The solution is in [c,b]  */ 
  136.  
  137.          a = c; 
  138.          sfa = sfc; 
  139.       } 
  140.    } 
Now it compilates and runs properly, but it doesn'n calculate anything. Maybe because I changed this line:
Expand|Select|Wrap|Line Numbers
  1. scanf("%f %f %f ",&a, &b, &epsilon; 
to:
Expand|Select|Wrap|Line Numbers
  1. cin >> a,b,epsilon
I dont know if it's ok but it's the only way in which the program compilates.
Should I do something else to make it better.
About the :
Expand|Select|Wrap|Line Numbers
  1. float fcn(float); 
  2. float sign(float, float); 
  3. void bisect(float(float), float, float, float, float *, int *); 
I don't understand what should i do with this floats could you give me more tips?
Jan 22 '07 #5
Cappo
5 New Member
I managed to make some source which compilates with no errors, but when i start it here's what comes out:
Expand|Select|Wrap|Line Numbers
  1. Error!
  2. -100
  3. Press any key to continue...
Jan 22 '07 #6
Cappo
5 New Member
I managed to make some source which compilates with no errors, but when i start it here's what comes out:
Expand|Select|Wrap|Line Numbers
  1. Error!
  2. -100
  3. Press any key to continue...
I forgot the code here it is:
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. double f2( double x) { 
  10. return 2*x; 
  11.  
  12. double bisection(double (*f)(double), 
  13.  
  14. double xL=-100, double xR=100) { 
  15.  
  16. double xN; 
  17.  
  18. if( (*f)(xL)*(*f)(xR) >0) { 
  19. cout << "Error!" << endl; 
  20. return xL; 
  21.  
  22. while (fabs(xL-xR)>0.0001) { 
  23. xN = (xL+xR)/2; 
  24. if( (*f)(xL)*(*f)(xN) <0) 
  25. xR = xN; // i.e. xL and xN have different signs 
  26. // so xRand xN have the same signs 
  27. else 
  28. xL = xN; 
  29. return (xL+xR)/2; 
  30.  
  31. int main() { 
  32. double tmp; 
  33. cout << bisection(f1,-100,100) << endl; 
  34.  system("PAUSE"); 
Jan 22 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
22533
by: aruna | last post by:
to write a c program to find the roots of the equation using bisection method that too using array or pointers
2
5693
by: t4zone58 | last post by:
Hey guys! I am beginner at VB studying. I got confused with solve the functions by applying bisection method in VB. Basically I can understand the bisection method mathmatically. However i got stucked when i trying to write a code for it. My code writing is Dim xr, xl, xm as double do xl=0 (coz the domain is greater than 0)
1
7644
by: Cappo | last post by:
Hi, I wrote befor about the bisection method in C++. This time I managed to make two source's and compile them. But both give me some error that i don't understand. Here are the codes: #include <iostream> #include <stdlib.h> #include <math.h> using namespace std; double f1( double x) { return x*x-pow(1.034554,2);
1
1721
by: beneyam | last post by:
i want to develop a program on bisection method using c++. the program should ask user to enter the function and the no of iterations at the run time. any one do this i really appreciate. 10qs 4 ur help.
2
3178
by: Baba sina | last post by:
How can I solve f(x) with bisection method with the interval ?
1
2372
by: zxipo | last post by:
the numerical prolem is is x*x*x*x-4*x-10=0 this to be solve by bisection method
0
1288
by: jhen61315 | last post by:
Hello there, First time here in forum, I hope im welcome here.... And I hope you'll help me in my assignment in bisection method because i dont know how to start to make in visual basic.. If you dont mind, Im just asking and help me? or if its okay for you please e-mail me in my email addres so that I ask formally to help, some open question for visual basic and C++. This is my email: jhen61315@yahoo.com Thanks and GOD BLESS!!!!
1
3450
by: lhbrown | last post by:
Hi. I'm looking for some help with the Bisection method in Visual Basic, which I'm using for the first time as part of a university project. I am using the bisection method to work out the water level of a river for a given flow. My variables are Wla, Wlb, Wlc, I have a sub routine called Qcalculate which calculates the discharge using the bisection method. My problem is my original Wlb, I did have it set at a ridiculously high level that...
0
8462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8382
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8658
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7405
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1787
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.