Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

C18 precentage calculation

Status
Not open for further replies.

hhhsssmmm

New Member
Hello

I wish to calculate the precentage of an integer number in C18 compiler. I understand that floating point can be used. However I have read elsewhere on the internet that floating point arithmatic should be avoided as much as possible as its very CPU intensive...especially for PICs.

However, due to my limited knowledge I can not understand other than to simply use floating point.

Below are few lines of C18 code which show my understanding so far of how the precentage can be calculated.

Please can someone look at my code and correct it. Also please provide me feed back for any better and more efficient way of calculating the precentage of a number.

Thank you

Haseeb


Code:
     float precentage = 0; //declaring float variable

     precentage = (0x5555/0x8888) * 100.0; //calculating the percentage
 
With integers, always do the multiplication first and the division last. The multiplication is a zero error procedure but the division will introduce an error when it rounds down to integer.

so;
percentage = (0x5555 * 100) / 0x8888
will have a lot less error than;
precentage = (0x5555/0x8888) * 100

If the the second number is always the same it is much easier. So if you have a number X in the range 0-255 and you need it as a percentage you can do this;

percent = (X * 100) / 256

Which is good because the division is binary (256) so it will compile very small.

And if you want to minimise the rounding down error, you add half the divisor BEFORE you do the division;

percent = ((X * 100)+128) / 256

That will give you the closest integer rounded result to the actual floating point result, ie has the least error in the result. I've explained it a bit rushed, one of the math guys can probably explain it much better.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top