How do you calculate a percentage from 2 int values into a int value that represents a percentage(perthousands for more accuracy)?
Background/purpose: using a processor that doesn't have a FPU, floating point computations take 100's of times longer.
int x = 25;
int y = 75;
int resultPercentage; // desire is 250 which would mean 25.0 percent
resultPercentage = (x/(x+y))*1000; // used 1000 instead of 100 for accuracy
printf("Result= ");
printf(resultPercentage);
output:
Result= 0
When really what I need is 250. and I can't use ANY Floating point computation.
Example of normal fpu computation:
int x = 25;
int y = 75;
int resultPercentage; // desire is 250 which would mean 25.0 percent
resultPercentage = (int)( ( ((double)x)/(double(x+y)) ) *1000); //Uses FPU slow
printf("Result= ");
printf(resultPercentage);
output:
Result= 250
But the output came at the cost of using floating point computations.
If your requirement is just to find a value which gives the relation between two numbers then instead of using 1000 you may use 1024
The multiplication with 1000 will take several cycles but instead you may use
resultRelation = (x<<10)/(x+y);
It will take only 10 cycle for multiplication. Even the result will not have very large variation with 1000. After you find the percentage you may be doing some thresholding with the percentage you got, just change the comparing values.
Suppose you are using
instead of that use
This way you can find the corresponding mapped values and replace it with them. If you are very strict on both cycles and accuracy then go for a saved lookup table which converts 0-1024 into 0-1000 but it uses a lot of RAM