C examples for Data Structure:Algorithm
To Find the Roots of an Equation Using the Regula Falsi Method
#include<stdio.h> #include<math.h> #define EPS 0.00001//from w w w. ja v a2s . co m #define f(x) 3*x*x*x + 5*x*x + 4*cos(x) - 2*exp(x) void falsePosition(); void main() { printf("\nEquation : 3*x*x*x + 5*x*x + 4*cos(x) - 2*exp(x) = 0"); falsePosition(); } void falsePosition(){ float fun1, fun2, fun3; float x1, x2, x3; int iterations =7; int i; x2 = 0.0; do { fun2 = f(x2); if(fun2 > 0) { break; } else { x2 = x2 + 0.1; } } while(1); x1 = x2 - 0.1; fun1 = f(x1); printf("\nIteration No.\t\tx\t\tF(x)\n"); i = 0; while (i < iterations) { x3 = x1 - ((x2 - x1) / (fun2 - fun1)) * fun1; fun3 = f(x3); if(fun1 * fun3 > 0) { x2 = x3; fun2 = fun3; } else { x1 = x3; fun1 = fun3; } printf("\n%d\t\t\t%f\t%f\n", i+1, x3, fun3); if (fabs(fun3) <= EPS) break; i++; } printf("\n\nTotal No. of Iterations: %d", i+1); printf("\nRoot, x = %8.6f \n", x3); }