# C/++/# Simple bisection program - solved

Tags:
1. Apr 12, 2017

Hello guys !! May you help me with this little bisection program ?

For some reason it is not changing the value of the variables x0 and x1 after every loop :c

Code (C):
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main () {

double x, x0, x1, f, f0, f1;

x0=0; x1= 1000;

do {

x=(x0+x1)/2;

f= pow( x, 2)- 77*x+ 78;

f0= pow( x0, 2)- 77*x0+ 78;

f1= pow( x1, 2)- 77*x1+ 78;

if( f0>0 and f1<0 ){

if( f > 0){

x0=x;

}

else {

x1=x;

}

}

if( f0<0 and f1>0){

if( f > 0){

x1=x;

}

else{

x0=x;

}

}

if( (f0<0 and f1<0) or ( f0<0 and f1<0) ){

x0=x0/10;

x1=10*x1;

}

cout << "x0= " << x0 << "    x1= " << x1 << "    x= "<< x << "    f0= " << f0 << "    f1= " << f1 << endl;

}

while ( f>pow( 10, -2) or f<-pow( 10, -3));

cout << "resultado: " << x;

}
it just gets the root for its simple function.

Thanks for the help

2. Apr 12, 2017

### Staff: Mentor

If you know it's not changing the values then you know the if statement that controls the change may have a problem.

The f0 and f1 variables are dependent on x0 and x1 so if they don't change then x0 and x1 can't change.

My suggestion is to place print statements inside your loop so you can see what the values are.

3. Apr 12, 2017

### Staff: Mentor

@Leonardo Machado, why do you have this line?
Code (C):
if( (f0<0 and f1<0) or ( f0<0 and f1<0) ){
I think your logic might be flawed here.
This one near the bottom of your code is a bit mysterious.
Code (C):
while ( f>pow( 10, -2) or f<-pow( 10, -3));
Your controlling expression for the do... while loop is when f > .01 or f < -.001. The lack of symmetry makes me think this is an error.

Also, I never do use pow() to calculate the square of a number, as in these lines:
Code (C):
f= pow( x, 2)- 77*x+ 78;
f0= pow( x0, 2)- 77*x0+ 78;
f1= pow( x1, 2)- 77*x1+ 78;

The first line would be much more efficient as f = x * x - 77 * x + 78; and similarly for the other two lines. The pow() function is extremely slow in comparison to multiplying a variable by itself.

Last edited: Apr 13, 2017
4. Apr 13, 2017

### SlowThinker

Are "and" and "or" some new additions to the C language?

5. Apr 13, 2017

### Staff: Mentor

They are if you #include <iso646.h> for C code or #include <ciso646> for C++ code.

6. Apr 16, 2017

### Svein

Or
Code (C):
#define and &&
#define or ||

Personally I abhor such conventions. I have seen it used to create a whole new language which is totally unreadable for people trying to debug the code.

7. Apr 16, 2017

### Staff: Mentor

Which is how they are defined in the header I cited.
Yeah, I don't see much advantage in writing 'and' instead of '&&', or 'or' instead of '||'.

8. Apr 18, 2017

### ChrisVer

except for if you come from a pythonic background.