Aussie AI
Integer Arithmetic
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Integer Arithmetic
Real arithmetic is slow compared to integer arithmetic. Hence, it is favorable to replace real arithmetic by equivalent integer arithmetic. Real arithmetic can be replaced by integer arithmetic when only limited precision is required (e.g. 1-3 decimal places). To do this, work in integer units that are 10, 100 or 1000 times larger (for 1, 2 and 3 decimal places) so that the decimal places appear as the lower digits of the integers.
To convert the integer into its true integer and fractional parts is quite simple. To get
at the fractional part, calculate the number modulo 10, 100 or 1000 (using the %
operator).
To get the true integer part, divide by 10 or 100 or 1000 — remember that integer
division truncates the fractional part.
A good example is: when working in dollars and cents, do all calculations in terms of cents (an integer). Then when printing it out, convert to dollars and cents using:
cents = value % 100; dollars = value / 100;
However, note that this is now using two of the worst integer operators: remainder and division. The hierarchy of cost for integer operations is similar to floating-point: integer addition and subtraction are faster than multiplication, but division is still the worst, even for integers.
There appears little to be done to replace integer division with multiplication.
Multiplying by the reciprocal will change an integer operation to a floating-point operation and
will probably increase execution time.
A power-of-two integer division could be done via the “>>
” right bitshift operator,
provided that it cannot be negative and uses an unsigned
type.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |