Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

Bisection Method - Maths (in Cpp)

You Suck.txt
File size: 1.27 KB

File content type: text/plain

Category: Notes and Practical Files

Course: B.Tech.

Semester: 4

College: Govind Ballabh Pant Engineering College(GBPEC)

#include <iostream>
#include <math.h>

using namespace std ;

float Func( float x )
{
    float y = x*x*x - 4*x - 9 ;
    return y ;
}

float Bisect( float a, float b, int &iter )
{
    iter++ ;
    float x = (a + b)/2.0 ;
    return x ;
}

int main( )
{
    int max_iter, iter=0 ;
    float a, b, x, aerr, prev_x=INT_MAX ;
    
    cout<<"\nEnter the value of a : " ;
    cin>>a;
    cout<<"\nEnter the value of b : " ;
    cin>>b;

    if( Func(a)*Func(b)>=0 )
    {
        cout<<"\nThere is no root between "<<a<<" and "<<b ;
        return 0 ;
    }

    cout<<"\nEnter Max iterations and Allowed Error : " ;
    cin>>max_iter>>aerr ;

    while( iter<=max_iter )
    {
        x = Bisect( a, b, iter ) ;
        if( fabs( x-prev_x )<= aerr )
        {
            cout<<"\nRoot found after "<<iter<<" iterations.";
            cout<<"\nRoot is : "<<x ;
            return 0 ;
        }

        cout<<"\nIteration no. = "<<iter<<"\tCurrent value of x = "<<x<<endl ;
        if( Func(a)*Func(x)<0 )
            b = x ;
        else
            a = x ;

        prev_x = x ;
    }

    cout<<"\nGiven value of Max Iterations is not sufficient." ;
    
    return 0 ;
}

Added by StAn

Comments
Posted by StAn,

If there is any error, do let me know.
Else Thank me later. ;)