Main Content


Compute cos(X*pi) accurately



Y = cospi(X) computes cos(X*pi) without explicitly computing X*pi. This calculation is more accurate than cos(X*pi) because the floating-point value of pi is an approximation of π. In particular:

  • For odd integers, cospi(n/2) is exactly zero.

  • For integers, cospi(n) is +1 or -1.


collapse all

Compare the accuracy of cospi(X) vs. cos(X*pi).

Create a vector of values.

X = [0 1/2 1 3/2 2];

Calculate the cosine of X*pi using the normal cos function.

Y = cos(X*pi)
Y = 1×5

    1.0000    0.0000   -1.0000   -0.0000    1.0000

The results contain small numerical errors due to the fact that pi is a floating-point approximation of the true value of π. For instance, Y(2) is not exactly zero even though cos(π2)=0.

ans = 6.1232e-17

Use cospi to calculate the same values. In this case, the results are exact.

Z = cospi(X)
Z = 1×5

     1     0    -1     0     1

ans = 0

Input Arguments

collapse all

Input array, specified as a scalar, vector, matrix, or multidimensional array.

Data Types: single | double
Complex Number Support: Yes

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced in R2018b

See Also

| |