cancel
Showing results for 
Search instead for 
Did you mean: 

Cosine function giving unexpected result

NicRoberts
Senior II

NUCLEO F411RE, CubeIDE

As a learning exercise I'm trying to generate 100Hz cosine wave & then eventually do a DFT on it but I'm getting some odd results from the cos function using code below...

 
#include "arm_math.h"

#define NUM_SAMP 100
#define SIGNAL_FREQ 100.0
#define SAMPLING_FREQ 1000

static void fpu_enable(void);

typedef struct
{
  float real;
  float imag;
}complex_number;

complex_number samples[NUM_SAMP];

main()
{
  fpu_enable();
  /* Generate a test signal 100Hz */
  for(int n = 0; n < NUM_SAMP; n++ )
   {
     samples[n].real = cos(2 * PI* SIGNAL_FREQ * n / SAMPLING_FREQ);
     samples[n].imag = 0.0;
   }
}

static void fpu_enable(void)
{
  SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2));
}
 

 

When I check the values in samples in the debugger....

weird_cos.png

I was expecting a value of 1 for the first entry and then subsequent values in the interval [-1, 1]

Is this a formatting issue in Cube's debugger or am I missing something obvious here?

 

9 REPLIES 9
mfgkw
Senior

arm_math.h is for fixed point values or 32 bit floating point functions arm_sin_cos_q31() and arm_sin_cos_f32().

cos() is a double precision function from math.h.

(1) Do you really want to compute in double precision?

(2) Did you include math.h?

 

 

P.S.: The floating point unit on your STM32F411RET6 does not support double precision, only single precision (32 bit values).

bmckenney
Associate III

It's a formatting error. 1065353216 is 0x3F800000 which is =1 (single-precision). The debugger should figure this out but sometimes it doesn't.

Right-click on the number and choose "Number Format".

 

It was doing the same with cosf  which made me think it was a formatting thing

Thanks that must be it as the rest of the code is working as expected.

Unfortunately the debugger doesn't give me that option when I right click the number, only the option to remove the variable.

The debugger "knows" the variables are of type float as the screenshot proves, but nonetheless fails to display the value properly.
An issue with the CubeIDE debugger, obviously.

Thanks, have now added bug-report tag.

bmckenney
Associate III

Unfortunately the debugger doesn't give me that option when I right click the number, only the option to remove the variable.

That's odd, I don't think I've encountered that, and I (have to) do this fairly often.

Are you sure your cursor was over the value (display)? You can only set "Number Format" on a particular element, not a structure nor even an array of scalars. (You can group-select elements in an array of scalars with shift-click.)

No matter what I try I dont get the option.

Perhaps the debugger has a problem with struct members.
Could you try with a "freestanding" float variable ?