This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

_IQmpy() error on multiply a negative number

I use _IQmpy() to multiply two IQ(15) numbers. When apply it to a negative number, it failed to give the correct answer. Here is a example:

 

#define GLOBAL_Q 15

_iq a = 50;

_iq b = -92;

_iq c;

c=_IQmpy(a, b); // c=-1, error

c= a*b /32768; // c=0, correct

I guess there is a truncation error. 50x(-92) = -4600 = 0xFFFFEE08. After a right shift 15 bit, it is 0xFFFFFFFF = -1. Even the error is only one bit, I used it in my PID controller with 10KHz control loop time, and it saturates my PID output quickly. Any suggestion?

Regards,

Yaoxin

 

  • Hello Yaoxin,

    Maybe you should make sure in your IQmathLib.h that these lines are opened:

    #if GLOBAL_Q == 15
    #define   _IQ(A)  _IQ15(A)

    Or you can use the default one (Q24). I tried with the default one (Q24) and in Expressions window I saw that it can calculate correctly:

    _iq a;

    _iq b;

    _iq c;
    a = _IQ15(50.0);
    b = _IQ15(-92.0);

    c =_IQ15mpy(a,b);

    Best regards,

    Maria

  • Maria,

    Thank you for your suggestion! I have to use IQ(15) format for my application. I found that the problem is caused by the round. Therefore, I created a macro for the _IQmpy().

    #define MACRO_IQMPY(a, b) ((long)((long)a*(long)b + _IQ(0.5)) >> 15)

    #define GLOBAL_Q 15

    _iq a = 50;

    _iq b = -92;

    _iq c;

    c = MACRO_IQMPY(a, b); // c=0, (50x(-92)+16384)>>15=(0xFFFFEE08+0x4000)>>15=0x2E08>>15=0

    c = a*b /32768; // c=0, Correct

    It works for me right now.

    Regards,

    Yaoxin

  • I am glad you found the way!

    Please close the tread by verify it to mention that this problem has been solved.

    Best regards,

    Maria