1 /* ----------------------------------------------------------------------
2  * Project:      CMSIS DSP Library
3  * Title:        arm_cos_q31.c
4  * Description:  Fast cosine calculation for Q31 values
5  *
6  * $Date:        23 April 2021
7  * $Revision:    V1.9.0
8  *
9  * Target Processor: Cortex-M and Cortex-A cores
10  * -------------------------------------------------------------------- */
11 /*
12  * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
13  *
14  * SPDX-License-Identifier: Apache-2.0
15  *
16  * Licensed under the Apache License, Version 2.0 (the License); you may
17  * not use this file except in compliance with the License.
18  * You may obtain a copy of the License at
19  *
20  * www.apache.org/licenses/LICENSE-2.0
21  *
22  * Unless required by applicable law or agreed to in writing, software
23  * distributed under the License is distributed on an AS IS BASIS, WITHOUT
24  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25  * See the License for the specific language governing permissions and
26  * limitations under the License.
27  */
28 
29 #include "dsp/fast_math_functions.h"
30 #include "arm_common_tables.h"
31 
32 /**
33   @ingroup groupFastMath
34  */
35 
36 /**
37   @addtogroup cos
38   @{
39  */
40 
41 /**
42   @brief         Fast approximation to the trigonometric cosine function for Q31 data.
43   @param[in]     x  Scaled input value in radians
44   @return        cos(x)
45 
46   The Q31 input value is in the range [0 +0.9999] and is mapped to a radian value in the range [0 2*PI).
47  */
48 
arm_cos_q31(q31_t x)49 q31_t arm_cos_q31(
50   q31_t x)
51 {
52   q31_t cosVal;                                  /* Temporary input, output variables */
53   int32_t index;                                 /* Index variable */
54   q31_t a, b;                                    /* Two nearest output values */
55   q31_t fract;                                   /* Temporary values for fractional values */
56 
57   /* add 0.25 (pi/2) to read sine table */
58   x = (uint32_t)x + 0x20000000;
59   if (x < 0)
60   { /* convert negative numbers to corresponding positive ones */
61     x = (uint32_t)x + 0x80000000;
62   }
63 
64   /* Calculate the nearest index */
65   index = (uint32_t)x >> FAST_MATH_Q31_SHIFT;
66 
67   /* Calculation of fractional value */
68   fract = (x - (index << FAST_MATH_Q31_SHIFT)) << 9;
69 
70   /* Read two nearest values of input value from the sin table */
71   a = sinTable_q31[index];
72   b = sinTable_q31[index+1];
73 
74   /* Linear interpolation process */
75   cosVal = (q63_t) (0x80000000 - fract) * a >> 32;
76   cosVal = (q31_t) ((((q63_t) cosVal << 32) + ((q63_t) fract * b)) >> 32);
77 
78   /* Return output value */
79   return (cosVal << 1);
80 }
81 
82 /**
83   @} end of cos group
84  */
85