Math operation gives wrong answer

Thread Starter

AlbertHall

Joined Jun 4, 2014
12,293
PIC24EP256GP204, MPLABX v6.00, XC16 v2.10, PICKIT3
In the code below DutyCycle is int8_t and OC2RS, OC2R are processor registers uint16t.
OC2RS is 0xFFFF
DutyCycle is 75
Gives OC2R = Temp = 0x028F - INCORRECT
With commented out code enabled and the 'Temp = OC2RS * DutyCycle / 100' line commented out gives Temp = 0xBFFF - CORRECT.

How should I perform this calculation?
Is there any disadvantage in splitting up the calculation?

Code:
    uint32_t Temp;
   
#ifdef SWAP_DIRECTION_LEFT
#ifdef SWAP_PWM_LEFT
    //Temp = OC2RS;
    //Temp *= DutyCycle;
    //Temp /= 100;
    Temp = OC2RS * DutyCycle / 100;
    OC2R = Temp;
 

Picbuster

Joined Dec 2, 2013
1,045
PIC24EP256GP204, MPLABX v6.00, XC16 v2.10, PICKIT3
In the code below DutyCycle is int8_t and OC2RS, OC2R are processor registers uint16t.
OC2RS is 0xFFFF
DutyCycle is 75
Gives OC2R = Temp = 0x028F - INCORRECT
With commented out code enabled and the 'Temp = OC2RS * DutyCycle / 100' line commented out gives Temp = 0xBFFF - CORRECT.

How should I perform this calculation?
Is there any disadvantage in splitting up the calculation?

Code:
    uint32_t Temp;
  
#ifdef SWAP_DIRECTION_LEFT
#ifdef SWAP_PWM_LEFT
    //Temp = OC2RS;
    //Temp *= DutyCycle;
    //Temp /= 100;
    Temp = OC2RS * DutyCycle / 100;
    OC2R = Temp;
What happens when you split calculate Temp * Temp * (Temp/100)
Temp and Dutycycle are Integers
what happens when you divide integer 1264/100 is answer 12 or 13?


Picbuster
 

MrChips

Joined Oct 2, 2009
29,858
What happens when you split calculate Temp * Temp * (Temp/100)
Temp and Dutycycle are Integers
what happens when you divide integer 1264/100 is answer 12 or 13?


Picbuster
Answer is 12.
Do the multiplication first in order to avoid rounding errors, assuming no overflows.

To do rounding, add one half of the divisor first before dividing.
 
Top