sqrt, sqrtf, sqrtl

From cppreference.com
< c‎ | numeric‎ | math
 
 
 
Common mathematical functions
Functions
Basic operations
(C99)
(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)(C99)
Floating point manipulation functions
(C99)(C99)
(C99)
(C99)
Classification
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)
Macro constants
 
Defined in header <math.h>
float       sqrtf( float arg );
(1) (since C99)
double      sqrt( double arg );
(2)
long double sqrtl( long double arg );
(3) (since C99)
Defined in header <tgmath.h>
#define sqrt( arg )
(4) (since C99)
1-3) Computes square root of arg.
4) Type-generic macro: If arg has type long double, sqrtl is called. Otherwise, if arg has integer type or the type double, sqrt is called. Otherwise, sqrtf is called. If arg is complex or imaginary, then the macro invokes the corresponding complex function (csqrtf, csqrt, csqrtl).

Contents

[edit] Parameters

arg - floating point value

[edit] Return value

If no errors occur, square root of arg (arg), is returned.

If a domain error occurs, an implementation-defined value is returned (NaN where supported).

If a range error occurs due to underflow, the correct result (after rounding) is returned.

[edit] Error handling

Errors are reported as specified in math_errhandling.

Domain error occurs if arg is less than zero.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If the argument is less than -0, FE_INVALID is raised and NaN is returned.
  • If the argument is +∞ or ±0, it is returned, unmodified.
  • If the argument is NaN, NaN is returned

[edit] Example

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
 
#pragma STDC FENV_ACCESS ON
 
int main(void)
{
    // normal use
    printf("sqrt(100) = %f\n", sqrt(100));
    printf("sqrt(2) = %f\n", sqrt(2));
    printf("golden ratio = %f\n", (1+sqrt(5))/2);
    // special values
    printf("sqrt(-0) = %f\n", sqrt(-0.0));
    // error handling
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("sqrt(-1.0) = %f\n", sqrt(-1));
    if(errno == EDOM) perror("    errno == EDOM");
    if(fetestexcept(FE_INVALID)) puts("    FE_INVALID was raised");
}

Possible output:

sqrt(100) = 10.000000
sqrt(2) = 1.414214
golden ratio = 1.618034
sqrt(-0) = -0.000000
sqrt(-1.0) = -nan
    errno = EDOM: Numerical argument out of domain
    FE_INVALID was raised

[edit] See also

(C99)(C99)
computes a number raised to the given power (xy)
(function)
(C99)(C99)(C99)
computes cubic root (3x)
(function)
(C99)(C99)(C99)
computes square root of the sum of the squares of two given numbers (x2
+y2
)
(function)
(C99)(C99)(C99)
computes the complex square root
(function)