Namespaces
Variants
Views
Actions

sqrt

From cppreference.com
< c‎ | numeric‎ | math
 
 
 
Common mathematical functions
Functions
Basic operations
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)(C99)(C99)
Exponential functions
(C99)
(C99)
(C99)
(C99)
Power functions
sqrt
(C99)
(C99)
Trigonometric and hyperbolic functions
(C99)
(C99)
(C99)
Error and gamma functions
(C99)
(C99)
(C99)
(C99)
Nearest integer floating point operations
(C99)(C99)(C99)
(C99)
(C99)(C99)(C99)
Floating point manipulation functions
(C99)(C99)
(C99)
(C99)
Classification
(C99)
(C99)
(C99)
Macro constants
 
Defined in header <math.h>
float       sqrtf( float arg );
(since C99)
double      sqrt( double arg );
long double sqrtl( long double arg );
(since C99)

Computes square root of arg.

Contents

[edit] Parameters

arg - floating point or integer value

[edit] Return value

Square root of arg.

Domain error occurs if arg is negative. NAN is returned in that case.

[edit] Example

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <string.h>
 
#pragma STDC FENV_ACCESS ON
 
void show_fe_exceptions(void)
{
    printf("current exceptions raised: ");
    if(fetestexcept(FE_DIVBYZERO))     printf(" FE_DIVBYZERO");
    if(fetestexcept(FE_INEXACT))       printf(" FE_INEXACT");
    if(fetestexcept(FE_INVALID))       printf(" FE_INVALID");
    if(fetestexcept(FE_OVERFLOW))      printf(" FE_OVERFLOW");
    if(fetestexcept(FE_UNDERFLOW))     printf(" FE_UNDERFLOW");
    if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
    printf("\n");
}
 
int main(void)
{
    printf("sqrt(4.0)      = %.1f\n", sqrt(4.0));
    printf("pow(2.0,2.0)   = %.1f\n", pow(2.0,2.0)); /* pow(x,2.0) is inverse of sqrt */
    printf("sqrt(INFINITY) = %.1f\n", sqrt(INFINITY));
    printf("sqrt(NAN)      = %.1f\n", sqrt(NAN));
    printf("\n");
 
    /* domain error                       */
    /* "invalid" floating-point exception */
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("sqrt(-1.0)     = %f\n", sqrt(-1.0));
    printf("%s\n",strerror(errno));
    show_fe_exceptions();
 
    return 0;
}

Possible output:

sqrt(4.0)      = 2.0
pow(2.0,2.0)   = 4.0
sqrt(INFINITY) = inf
sqrt(NAN)      = nan
 
sqrt(-1.0)     = -nan
Numerical argument out of domain
current exceptions raised:  FE_INVALID

[edit] See also

(C99)
computes cubic root (3x)
(function) [edit]
raises a number to the given power (xy)
(function) [edit]