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

  1. Nov 8, 2008 #1
    Hi, Ive written code to resolve the routes of a function using the bisection method. The code works for the current route brackets (xb and xt) and for a decimal place value of 2. However when the decimal place value is changed the loop gets stuck. Code below:

    #include <iostream>
    #include <cmath>
    #include <iomanip>
    #include <fstream>

    using namespace std;

    //declaration and initiation of fixed variables
    double m=5.0,L=0.6,k=1000.0,g=9.81;

    //Setup of function to be solved
    double f(double x){
    return tan(x)-sin(x)-(m*g)/(k*L);
    }

    //Main function
    int main(){

    //Declaration of decimal places var d
    int d;

    //Declaration of upper, lower and middle limit vars
    double xb,xt,xm,dp;

    //Promt user to input no. dec places of accuracy
    cout << "Please input the number of decimal places to which the calculation will be accurate to.. " << endl;
    cin >> d;

    //Declaration of count var i
    int i;

    //Setup of initial route bracket and decimal place var dp
    xb=0.5;
    xt=1.0;
    dp=pow(0.1,d);
    double ans;

    do{
    xm=(xb+xt)/2;
    ans=f(xm);

    if((f(xb)*f(xt))>0){
    xb=xm;
    }
    else{
    xt=xm;
    }
    i++;
    }

    while ((ans>dp)||(ans<-(dp)));

    cout << endl << i << " " << xm << " " << ans;

    }

    Any resolution to this would be greatly appreciated


    Thanks

    Sol
     
  2. jcsd
  3. Nov 8, 2008 #2

    uart

    User Avatar
    Science Advisor

    It's only by good luck that it even works for d=2 actually.

    The error is in the line "if((f(xb)*f(xt))>0)". Here you are testing if f(xb) and f(xt) are the same sign, but you really should be comparing the sign of f(xm) and that of the end points.
     
  4. Nov 8, 2008 #3
    Thankyou v much
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Bisection Method
  1. Bisection method by c (Replies: 10)

  2. Bisection c++ problem (Replies: 10)

Loading...