Update
This commit is contained in:
parent
f96124b085
commit
93ed05f715
7 changed files with 101 additions and 14 deletions
|
@ -31,9 +31,51 @@ The normalization is basically the only thing you have to think about, apart fro
|
|||
|
||||
Remember to **always use a power of two scaling factor** -- this is crucial for performance. I.e. you want to count 1/2th, 1/4th, 1/8ths etc., but NOT 1/10ths, as might be tempting. Why are power of two good here? Because computers work in binary and so the normalization operations with powers of two (division and multiplication by the scaling factor) can easily be optimized by the compiler to a mere [bit shift](bit_shift.md), an operation much faster than multiplication or division.
|
||||
|
||||
## Implementation Example
|
||||
## Code Example
|
||||
|
||||
The following is an example of a simple [C](c.md) program using fixed point with 10 fractional bits, computing [square roots](sqrt.md) of numbers from 0 to 10.
|
||||
For start let's compare basic arithmetic operations in [C](c.md) written with floating point and the same code written with fixed point. Consider the floating point code first:
|
||||
|
||||
```
|
||||
float
|
||||
a = 21,
|
||||
b = 3.0 / 4.0,
|
||||
c = -10.0 / 3.0;
|
||||
|
||||
a = a * b; // multiplication
|
||||
a += c; // addition
|
||||
a /= b; // division
|
||||
a -= 10; // subtraction
|
||||
a /= 3; // division
|
||||
|
||||
printf("%f\n",a);
|
||||
```
|
||||
|
||||
Equivalent code with fixed point may look as follows:
|
||||
|
||||
```
|
||||
#define UNIT 1024 // our "1.0" value
|
||||
|
||||
int
|
||||
a = 21 * UNIT,
|
||||
b = (3 * UNIT) / 4, // note the brackets, (3 / 4) * UNIT would give 0
|
||||
c = (-10 * UNIT) / 3;
|
||||
|
||||
a = (a * b) / UNIT; // multiplication, we have to normalize
|
||||
a += c; // addition, no normalization needed
|
||||
a = (a * UNIT) / b; // division, normalization needed, note the brackets
|
||||
a -= 10 * UNIT; // subtraction
|
||||
a /= 3; // division by a number NOT in UNITs, no normalization needed
|
||||
|
||||
printf("%d.%d%d%d\n", // writing a nice printing function is left as an exercise :)
|
||||
a / UNIT,
|
||||
((a * 10) / UNIT) % 10,
|
||||
((a * 100) / UNIT) % 10,
|
||||
((a * 1000) / UNIT) % 10);
|
||||
```
|
||||
|
||||
These examples output `2.185185` and `2.184`, respectively.
|
||||
|
||||
Now consider another example: a simple [C](c.md) program using fixed point with 10 fractional bits, computing [square roots](sqrt.md) of numbers from 0 to 10.
|
||||
|
||||
```
|
||||
#include <stdio.h>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue