3 ms·
Understanding the precision of floats is a small pain, but fixed point math is much more painful. With fixed point, you have to decide how many fraction bits y
by jacquesgt 15y ago
Understanding the precision of floats is a small pain, but fixed point math is much more painful.
With fixed point, you have to decide how many fraction bits you're going to have. If you have more than zero fractions bits, multiplies and divdes end up looking like this (assuming 16 fraction bits):
result = (a * b + 1 << 15) >> 16
result = (a / b) << 16; // rounds to zero is a is close to b
result = ((a << 4) / b) << 20; // not much range or precision on the result
Of course, if your variables can't all be represented with the same number of fraction bits, you need to keep track of that and adjust your shifts for each calculation. You also need to do shifts when you add two numbers with different numbers of fraction bits. This stuff is all taken care of for you by floating point numbers.
With fixed point, if you mess up a calculation and it overflows, you get completely whacky results (wrap around) which will cause massive bugs. With floating point, you lose a bit or two of accuracy.
There are definitely places where fixed-point is needed. If you're on a microcontroller without an FPU, you'll have to learn your way around floating point. If you absolutely can't deal with the loss of precision you get with big floating point numbers, you'll have to use fixed point and make sure you understand the range of parameters that can go into each calculation and prevent overflow.
If floats work for you, just use them.