pub const fn cos(x: Real) -> RealExpand description
Computes the cosine of x in radians (cos(x)).
Returns a value in the range [-1.0, 1.0].
§Special cases
cos(NaN)returnsNaNcos(±∞)returnsNaNcos(±0.0)returns1.0(preserves the even property of cosine)
§Implementation notes
This is a const fn-compatible port of the FreeBSD libm implementation
(s_cos.c). It first checks whether |x| ≤ π/4 (fast path via k_cos),
handles infinities/NaNs, and otherwise performs argument reduction with
rem_pio2 before dispatching to the appropriate kernel (k_cos or
k_sin) based on the quadrant.
§Modifications for this crate
- Adapted to the generic
Realtype (which isf64under the hood) - Made fully
const fncompatible - Uses the crate’s own
rem_pio2,k_cos, andk_sinimplementations
§Testing
The function is validated by a comprehensive test suite that includes:
- Special values (NaN, infinities, zeros)
- Symmetry (
cos(-x) == cos(x)) - Small arguments (fast path)
- Values near multiples of π/2 (critical accuracy region)
- Medium and very large arguments (argument reduction stress)
- Subnormal numbers
- Deterministic pseudo-random inputs
- Explicit
constevaluation checks
All tests pass and produce results matching std::f64::cos within 1 ULP.