Efficient inverse (1/x) for AVR

One nice thing about division is that more or less everyone is doing it. It is a pretty core feature of the C language, and compilers like AVR-GCC (called by the Arduino IDE) will choose the best division algorithm available, even when the microcontroller does not have a hardware division instruction.

In other words, you don't need to worry about how division is implemented unless you have a very strange special case.


If you do worry, then you might enjoy reading Atmel's official suggested division algorithms (one optimized for code size, and one optimized for execution speed; neither take any data memory). They are in:

http://www.atmel.com/dyn/resources/prod_documents/doc0936.pdf

which is the Application Note "AVR200: Multiply and Divide Routines" listed on the Atmel page for its (reasonably big) Atmega processors like the Atmega 168 and Atmega 328 used in the standard Arduinos. The list of data-sheets and application notes is at:

http://www.atmel.com/dyn/products/product_card.asp?part_id=4720


looks to me like all you need is a 100-entry lookup table. Doesn't get much faster than that.

#define VALUE_FOR_V_EQUALS_ZERO 0
uint16_t formula_lookup[100] = {VALUE_FOR_V_EQUALS_ZERO, 500, 399, 365, 348, ..., 300};

...

//"calculate" formula
p = formula_lookup[v > 67 ? 67 : v];

EDIT you actually only a 68 value lookup table since values of v greater than 67 always evaluate to 300.


There are some very good techniques mentioned in the book "Hackers Delight by Henry Warren and on his website hackersdelight.org. For a technique that works well with smaller microcontrollers when dividing by constants have a look at this file.