Namespaces
Variants
Views
Actions

cos

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
(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       cosf( float arg );
(since C99)
double      cos( double arg );
long double cosl( long double arg );
(since C99)

Computes cosine of arg

Contents

[edit] Parameters

arg - floating point value representing angle in radians

[edit] Return value

Cosine of arg in the range [-1.0 ; 1.0].

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

[edit] Example

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <string.h>
#define PI acos(-1)
 
#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("cos(PI/2.0)   = %.1f\n", cos(PI/2.0));
    printf("cos(+0.0)     = %.1f\n", cos(+0.0));
    printf("cos(-0.0)     = %.1f\n", cos(-0.0));
    printf("cos(NAN)      = %.1f\n", cos(NAN));
    printf("\n");
 
    /* domain error                       */
    /* "invalid" floating-point exception */
    /* same with cos(-INFINITY)           */
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("cos(INFINITY) = %f\n", cos(INFINITY));
    printf("%s\n",strerror(errno));
    show_fe_exceptions();
 
    return 0;
}

Possible output:

cos(PI/2.0)   = 0.0
cos(+0.0)     = 1.0
cos(-0.0)     = 1.0
cos(NAN)      = nan
 
cos(INFINITY) = -nan
Numerical argument out of domain
current exceptions raised:  FE_INVALID

[edit] See also

computes sine (sin(x))
(function) [edit]
computes tangent (tan(x))
(function) [edit]
computes arc cosine (arccos(x))
(function) [edit]