# Bisection method in c++

• Comp Sci

## Homework Statement

find the roots ( interval halving ) , I want to know how to make a condition statement that when fun3 be less than 0.001 and then loop will stop and i get the root .(here in my code i don't know why the loop doesn't work as it should ..

## Homework Equations

the equation is : x^3+4x^2-x-1

## The Attempt at a Solution

Code:
// UniqueName.cpp : Bisection Method in c++
//

#include "stdafx.h"
#include<iostream>
#include <math.h>
using namespace std;
float fun1(float);
float fun2(float);
float fun3(float);
void main()
{
float a,b,c,a1,b1,c1;
int i=0;
cin>>a>>b;
a1=fun1(a);
b1=fun2(b);
c=(a+b)/2;
c1=fun3(c);

if((a1*b1)<0)
do{

if ((a1*c1)<0)
b=c;
else if((c1*b1)<0)
a=c;
else
break;

}
while(fabs (c1)<0.01);

cout<<"The root  is    "<<c<<endl;
}

float fun1( float a)
{
float y;
y=a*a*a+4*a*a-a-1;
return y;
}
float fun2( float b)
{
float y;
y=b*b*b+4*b*b-b-1;
return y;
}
float fun3( float c)
{
float y;
y=c*c*c+4*c*c-c-1;
return y;
}

Mark44
Mentor

## Homework Statement

find the roots ( interval halving ) , I want to know how to make a condition statement that when fun3 be less than 0.001 and then loop will stop and i get the root .(here in my code i don't know why the loop doesn't work as it should ..

## Homework Equations

the equation is : x^3+4x^2-x-1

## The Attempt at a Solution

Code:
// UniqueName.cpp : Bisection Method in c++
//

#include "stdafx.h"
#include<iostream>
#include <math.h>
using namespace std;
float fun1(float);
float fun2(float);
float fun3(float);
void main()
{
float a,b,c,a1,b1,c1;
int i=0;
cin>>a>>b;
a1=fun1(a);
b1=fun2(b);
c=(a+b)/2;
c1=fun3(c);

if((a1*b1)<0)
do{

if ((a1*c1)<0)
b=c;
else if((c1*b1)<0)
a=c;
else
break;
}
while(fabs (c1)<0.01);

cout<<"The root  is    "<<c<<endl;
}

float fun1( float a)
{
float y;
y=a*a*a+4*a*a-a-1;
return y;
}
float fun2( float b)
{
float y;
y=b*b*b+4*b*b-b-1;
return y;
}
float fun3( float c)
{
float y;
y=c*c*c+4*c*c-c-1;
return y;
}
Just as in the other thread you started, the logic in your do while loop is backwards. The first time through fabs(c1) > .01, so the loop doesn't do more than one iteration.

thank u all <3