Ticker

6/recent/ticker-posts

CPNM LAB PROGRAM-9

 

9. Implement bisection method to find the square root of a given number to a given accuracy.

Algorithm: 

Step – 1 : Start 
Step – 2 : Read a, b, epsilon, xmid 
Step – 3 : Enter the no. for which square root has to be found 
Step – 4 : Enter the initial guess values and accuracy 
Step – 5 : If(f(a) * f(b) > 0) 
Step – 6 : Print unsuitable initial values 
Step – 7 : Exit 
 Step – 8 : Xmid = (a + b) / 2 
Step – 9 : While(fabs(xmid - b) / xmid >= epsilon) 
Step – 10 : If f(xmid == 0) 
Step – 11 : Break 
Step – 12 : If(f(a) * f(xmid) < 0) 
Step – 13 : B = xmid 
Step – 14 : Else a = xmid 
Step – 15 : Xmid = a + b / 2 
Step – 16 : Go to Step–10 
 Step – 17 : Print the square root is xmid 
Step – 18 : Stop

Program:-

#include<stdio.h>


#include<conio.h>


#include<stdlib.h>


#include<math.h>


 float n; 


 float f(float x)


return(x * x - n);  }


     main() 

{


float a, b, epsilon, xmid; 


clrscr(); 


printf("\nEnter the no. of which square root has to be found :\n"); 


scanf("%f",&n);


printf("\nEnter the initial guess values and accuracy: \n"); 


scanf("%f,%f,%f",&a, &b, &epsilon); 


if(f(a) * f(b) > 0)


{


printf("\n Unsuitable initial values \n"); exit(0);


}


xmid = (a + b) / 2;


while(fabs(xmid - b) / xmid >= epsilon)


{


if(f(xmid) == 0) 


{  break;  }


if(f(a) * f(xmid) < 0) 


{b = xmid;}


 else 


{a = xmid;


 xmid = (a + b) / 2;}


}


printf("\nThe Square root = %2f \n",xmid); 


getch(); return 0;




  

THIS CODE IS CREATED BY ECE THE WONDERS, HEMU THE SMART

output :-

Run 1:

 

Enter the no. of which square root has to be found :

25

 

Enter the initial guess values and accuracy:

4,6,0.0001

 

The Square root = 5.000000

 

Run 2:

 

Enter the no. of which square root has to be found :

49

 

Enter the initial guess values and accuracy:

4,6,0.0001

 

Unsuitable initial values 


Post a Comment

0 Comments