1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Bisection method in c++

  1. Sep 18, 2012 #1
    1. The problem statement, all variables and given/known data
    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 ..


    2. Relevant equations

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

    3. The attempt at a solution

    Code (Text):
    // 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;
    }



     
    thanx in advance
     
  2. jcsd
  3. Sep 18, 2012 #2

    Mark44

    Staff: Mentor

    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.
     
  4. Oct 7, 2012 #3
    thank u all <3
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook