sqrt() with custom precision

Published on 2007-10-14 18:13:50.

tags = {  "math" "fun" "c"   };

bookmarks = {  Digg! , Del.icio.us! , Google! , Slashdot! , Netscape! , Technorati! , Yahoo! , Stumbleupon! };

Description

A driver & function for calculating the square root a number with custom precision.

Content

   1  #include <stdlib.h>
   2  #include <stdio.h>
   3  #include <math.h>
   4  
   5  #define PRECISION pow( 10, -6 )
   6  
   7  float mysqrt( float, float );
   8  
   9  int main( ){
  10      float x = 0.0;
  11     
  12      for( ;; )
  13      {
  14          printf( "Enter number: " );
  15          scanf( "%f", &x );
  16         
  17          if( x < 0 ){
  18              printf( "Number is less than 0, exiting cowardly!\n" );
  19              exit( 0 );
  20          }
  21  
  22          printf( "Square root: %f\n", mysqrt( x, PRECISION ) );
  23      }
  24  
  25  }
  26  
  27  /**
  28   * Function for calculating the square root of a given number "r"
  29   * with a precision of "e"
  30   *
  31   * @param   float   r   number whose root to find
  32   * @param   float   e   root precision
  33   *
  34   * @return  float   the root of r
  35   */

  36  float mysqrt( float r, float e ){
  37      float x = r / 2.0, x_last = 0;
  38  
  39      while( fabs( x - x_last ) / x > e ){
  40          x_last = x;
  41          x = 0.5 * ( x + r / x );
  42      }
  43  
  44      return x;
  45  }
  46  
  47   
Code statistics
Physical lines Code lines Comment lines Empty lines Size
46 [ 100.00% ] 22 [ 47.83% ] 12 [ 26.09% ] 12 [ 26.09% ] 864 bytes
[ Download ]