Main Content

cospi

Compute cos(X*pi) accurately

Description

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.

example

Examples

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.

Y(2)
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

Z(2)
ans = 
0

Input Arguments

collapse all

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

Data Types: single | double | table | timetable
Complex Number Support: Yes

Extended Capabilities

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

Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

Version History

Introduced in R2018b

expand all

See Also

| |