5

I'm writing some code on an Arduino that needs to run fast and make rough approximations to percentages of integers.

For example, given a number I want to find 90% of it, or 70% or 30% etc. The obvious way to do it is multiply by a floating point eg. x * 0.9; or x * 0.3; But because I need speed, I want to avoid a floating point calculation. If I was just dividing by a power of two, I'd do a bitwise shift, but are there similar techniques for approximating 90%, 80% etc. using integers?

interstar
  • 26,048
  • 36
  • 112
  • 180

2 Answers2

5

You can approximate those percentages with fractions that have a power-of-two denominator.

Here's a simple example with 2^16:

90% = 90 / 100 ~ 58982 / 65536
70% = 70 / 100 ~ 45875 / 65536
30% = 30 / 100 ~ 19661 / 65536

 x% =  x / 100 ~ x * 655 / 65536

The divisions (which are now powers-of-two) can be done with shifts.

Of course, it may take some pre-computation to generate those fractions.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
2

Bit shifting How can I multiply and divide using only bit shifting and adding?

You can use bit shifting for to multiply and divide arx example x = (x*9)/10

As for a code example, if you get stuck I could try and burn some brain cells to work it out. Just ask :)

Community
  • 1
  • 1
Hellonearthis
  • 1,664
  • 1
  • 18
  • 26