Details the implementation of the square root in C language

  • 2020-04-02 03:15:50
  • OfStack

The SQRT () function is of course the first thing that comes to mind about the square root calculation in C. Let's review its basic usage:
Header: #include < Math. H >

SQRT () is used to find the square root of a given value. Its prototype is:


  double sqrt(double x);

parameter

X is the value of the square root to be computed.

If x < 0, will cause a domain error and set the value of the global errno to EDOM.

The return value

Returns the square root of x.

Note that when compiling with GCC, join -lm.

The example calculates the square root value of 200.


#include <math.h>
main(){
  double root;
  root = sqrt(200);
  printf("answer is %fn", root);
}

Output results:
The answer is 14.142136

The title
Take the square root of the integer N, with an accuracy of 0.001

dichotomy
If N is greater than 1, then starting from [1, N], low = 1, high = N, mid = low + (high-low) > > 1. Start numerical approximation

If N is less than 1, then starting from [N, 1], low = 0, high = N, mid = low + (high-low) > > 1. Start numerical approximation

Ac code



  
   
  #include <stdio.h> 
  #include <stdlib.h> 
  #include <math.h> 
   
  #define ACCURACY 0.001 
   
  double newSqrt(double n) 
  { 
    double low, high, mid, tmp; 
   
    //Get upper and lower bounds
    if (n > 1)  { 
      low = 1; 
      high = n; 
    } else { 
      low = n; 
      high = 1; 
    } 
   
    //The dichotomy takes the square root
    while (low <= high) { 
      mid = (low + high) / 2.000; 
   
      tmp = mid * mid; 
   
      if (tmp - n <= ACCURACY && tmp -n >= ACCURACY * -1) { 
        return mid; 
      } else if (tmp > n) { 
        high = mid; 
      } else { 
        low = mid; 
      } 
    } 
   
    return -1.000; 
  } 
   
  int main(void) 
  { 
    double n, res; 
   
    while (scanf("%lf", &n) != EOF) { 
      res = newSqrt(n); 
      printf("%lfn", res); 
    } 
   
    return 0; 
  } 


Related articles: