Thread: Math Cordic Square root API

1. Math Cordic Square root API

Hello All,

I want to use square root api provided with math library :

int16_t XMC_MATH_CORDIC_Q15_Sqrt(int16_t x) and
int32_t XMC_MATH_CORDIC_Q31_Sqrt(int32_t x)

But I am not getting the desired results.

Is there any changes has to be made for getting the result, like some sort of number format?

Suppose I want to find the square root of 144 and 34567. what steps I have to follow to get the desired result?

Argument x has to be converted in which data format and result will be in which format?

Regards,
Tinchu

2. The function names say all.

Q15 and Q31 format.

3. Q15 and Q31 format for argument or return value or for both?

Have you used these API?

If yes then could you please share some code

4. Any one could please tell me how to use sqrt api in math.h

If I want to find the square root of

144
200
1000
50000

which API should I use and how to interpret the result

5. Hi,

The functions as explained receive and return Q31 or Q15. In these format you can represent numbers in the range (1.0,-1.0). So you will need to use scaling factors.

Code:
```#include <xmc_common.h>
#include "xmc_math.h"

__STATIC_INLINE float q15_to_float(int16_t a) { return (float)a / 0x8000; }
__STATIC_INLINE float q31_to_float(int32_t a) { return (float)a / 0x80000000; }
__STATIC_INLINE int32_t float_to_q15(float a) { return (int16_t)((a * 0x8000) + 0.5); }
__STATIC_INLINE int32_t float_to_q31(float a) { return (int32_t)((a * 0x80000000) + 0.5); }

int main(void)
{
int32_t a;
float b;

a = XMC_MATH_CORDIC_Q31_Sqrt(0x40000000);
b = q31_to_float(a);

...```

If you want to use the sqrt from the standard library:
Code:
```#include <math.h>
int main(void)
{
float b;
b = sqrtf(0.5F);
...```
Here the result should be the same as in the first example 0x40000000 is quivalent to 0.5F in signed Q31.

Regards,
Jesus

6. BTW: If you want to use floating point in cortex M0, you may want to give a try at https://www.quinapalus.com/qfplib.html

Code:
```float f;
int32_t x, y;

f = 144.0;
y = float_to_q15(f);
x = XMC_MATH_CORDIC_Q15_Sqrt((int16_t)y);
y = q15_to_float((int16_t)x);

f = 34567.0;
y = float_to_q31(f);
x = XMC_MATH_CORDIC_Q31_Sqrt(y);
y = q31_to_float((int32_t)x);```
In both cases I am getting result zero.

You can try any number and see the result.

For finding the square root of 144 and 34567, Am i following the correct rule shown above?

Could you please guide me for the above two values

8. Any one to help and guide me?

9. You don't understand Q Format.

It could only represent [-1,1) range.

You will need to normalize the input and output.

10. So for 144 and 34567, I have to use

float_to_Q15(144) and float_to_Q31(34567) first before calling sqrt function?

How will I get values -1 To 1 for 144 and 34567?

I couldnt understand this logic.

Please guide me what need to be done for any value.