Sei sulla pagina 1di 3

Problem: Solve the following equation by Regula Falsii: f(x)=x-exp(-x)=0 Note: From knowledge of graph we know that the

e given function has one and only one root. The root must be positive as exp(-x) cannot be negative or zero. So a root must lie in (0,infinity) f(0)<0 [as exp(-x)>0] Algorithm: Step 1: START Step 2: Operate a while loop to start from zero and find a positive value of b such that f(0)*f(b)<0 ie. f(b)>0. Step 3: Assign p=0=a. Specify a suitable tolerance. Step 4: Run a do-while loop if abs(f(p))<tolerance and abs(p-p0)<tolerance Step 6:The root is found by the following scheme: p0=p p= b-f(b)*(b-a)/(f(b)-f(a)) If f(a)*f(p)<0 then b=p and a=a. Else if f(a)*f(p)>0 then a=p and b=b Step 7: Print p, which is the required root. Step 8: STOP C++ Code: #include<iostream> #include<math.h> #define ABS(x) (x>0?x:(-x)) using namespace std; double f(double x) { float y; y=x-exp(-x); return (y); } int main() { double tol,k,a,b,p,p0; int maxita,i,rem; cout<<"This program finds the root of x-exp(-x)=0 by regula falsi method"<<endl; do{ cout<<"Enter the tolerence"<<endl; cin>>tol; tol=ABS(tol);

retry1: cout<<"Enter the max no. of iterations for the incrementing"<<endl; cout<<"search func that locates the interval of the root"<<endl; cin>>maxita; if((maxita<=0)) { cout<<"Please enter a positive value"<<endl; goto retry1; } cout<<"Enter the increment of the incrementing search func that"<<endl; cout<<" locates the interval of the root"<<endl; cin>>k; i=0; b=0; a=0; while((f(b)<0)&&(i<maxita)) { b=b+k; i++; } if(i>=maxita) { cout<<"No roots between 0 and "<<(k*maxita)<<endl; cout<<"Enter a higher incrementing factor or no of iterations"<<endl; goto retry; } cout<<"A root lies between 0 and "<<b<<endl; if(f(b)==0) cout<<"The root is easily found to be "<<b<<endl; else { p=0; do { p0=p; p=b-f(b)*(b-a)/(f(b)-f(a)); if(f(a)*f(p)<0) b=p; else if(f(a)*f(p)>0) a=p; else break; }while((((p-p0)>tol)||((p-p0)<-tol))||(f(p)>tol)); cout<<"The root is "<<p<<endl;

cout<<"The functional value at x="<<p<<" is "<<f(p)<<endl; } retry: cout<<"Enter 1 to do again"<<endl; cin>>rem; }while(rem==1); return 0; } Output: This program finds the root of x-exp(-x)=0 by regula falsii method. Enter tolerance .005 Enter the maximum no. of iterations for the incrementing search function that locates the interval of the root. 100 Enter the increment of the incrementing search function that locates the interval of the root. 0.4 A root lies between 0 and .8 The root is .567453 The functional value at x=.567453 is .000485831 Enter 1 to do again.

Potrebbero piacerti anche