#include #include double f(double x){ // given function double y; y = (x+1.0)*(x-2.0)*(x-10.0); // y = sqrt(x) - tan(x); return y; } int main(){ double xleft, xright, xmiddle; double yleft, yright, ymiddle; double accuracy; int i=1; // loop for reading data // will loop until valid data is entered or user-cancelled // i=1: read data (no or invalid data entered), i=0: cancel calculation, i=2: valid data entered while(i == 1){ printf("Left bound? = "); scanf("%le",&xleft); printf("Right bound? = "); scanf("%le",&xright); printf("Accuracy? = "); scanf("%le",&accuracy); yleft = f(xleft); yright = f(xright); if(yleft*yright > 0){ // check for root between bounds - if no found, cancel calculation and ask for re-enter data printf("#################\n"); printf("Invalid bounds! (no root between bounds?)\n"); printf("Re-enter values? (0 - no, 1 - yes) "); scanf("%d",&i); } else{ // abort loop xmiddle = xleft; ymiddle = f(yleft); i=2; } } if(i==2){ // calculate root if valid data is entered while(fabs(ymiddle) > accuracy){ xmiddle = 0.5*(xright+xleft); // middle of the intervall [xleft,xright] ymiddle = f(xmiddle); if((ymiddle*yleft) > 0){ // set left bound to middle if sign changes in the right half of the interval xleft = xmiddle; yleft = ymiddle; }else{ // set right bound to middle if sign changes in the left half of the interval xright = xmiddle; yright = ymiddle; } printf("xl: %le\txr: %le\tymid: %le\twidth: %le\n",xleft,xright,ymiddle,(xright-xleft)); } printf("------------------------------------------\n"); printf("Root found at %.15le with accuracy of %.10le\n",xmiddle,ymiddle); } return(0); }