//To compute the square root of a number using Newton-Raphson method //To be compiled using: gcc -lm //For example,if your filename is squareroot.c,compile it using: gcc -lm squareroot.c //@author-Karan Narain(karan@iitk.ac.in) #include #include int main() { double m,x,y,diff; int i; /*The while loop below is included to satisfy the requirement that the inputs need to be positive.The while loop keeps repeating till the user enters valid inputs.To enter into this while loop the first time,we initialize m to an illegal value(-1).We maintain a counter i which counts the number of times the user has entered values and display a message accordiingly*/ m=-1; i=0; while(m<=0) { //This is the first time the user is entering the value if(i==0) printf("\nPlease enter a positive value for m\n"); //The user had entered an incorrect value.Print appropriate message else printf("The value of m needs to be positive.Please enter a proper value\n"); scanf("%lf",&m); i++; } x=m; //The first term diff=m; do { y=((x/2)+(m/(2*x))); //X(n+1)= X(n)/2 + m/(2*X(n)) diff=x-y; x=y; //X(n)=X(n+1) }while(diff>=0.01); printf("The square root of %lf as computed by Newton-Raphson method is %lf\n",m,y); x=sqrt(m); printf("The square root using sqrt is %lf\n",x); diff=y-x; printf("The difference between the two roots is %lf\n",diff); return 0; }