False Position Method - Example Code

Example Code

C code was written for clarity instead of efficiency. It was designed to solve the same problem as solved by the Newton's method and secant method code: to find the positive number x where cos(x) = x3. This problem is transformed into a root-finding problem of the form f(x) = cos(x) - x3 = 0.

#include #include double f(double x) { return cos(x) - x*x*x; } /* s,t: endpoints of an interval where we search e: half of upper bound for relative error m: maximal number of iterations */ double FalsiMethod(double s, double t, double e, int m) { int n,side=0; double r,fr,fs = f(s),ft = f(t); for (n = 1; n <= m; n++) { r = (fs*t - ft*s) / (fs - ft); if (fabs(t-s) < e*fabs(t+s)) break; fr = f(r); if (fr * ft > 0) { t = r; ft = fr; if (side==-1) fs /= 2; side = -1; } else if (fs * fr > 0) { s = r; fs = fr; if (side==+1) ft /= 2; side = +1; } else break; } return r; } int main(void) { printf("%0.15f\n", FalsiMethod(0, 1, 5E-15, 100)); return 0; }

After running this code, the final answer is approximately 0.865474033101614

Read more about this topic:  False Position Method

Famous quotes containing the word code:

    Wise Draco comes, deep in the midnight roll
    Of black artillery; he comes, though late;
    In code corroborating Calvin’s creed
    And cynic tyrannies of honest kings;
    He comes, nor parlies; and the Town, redeemed,
    Gives thanks devout; nor, being thankful, heeds
    The grimy slur on the Republic’s faith implied,
    Which holds that Man is naturally good,
    And—more—is Nature’s Roman, never to be
    scourged.
    Herman Melville (1819–1891)

    ...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.
    Ellen Glasgow (1873–1945)