2 ms·
The arithmetic should either work, or be type checked. Multiplying a Q8.24 with another Q8.24 makes a Q16.48. In C that's not the same as the '∗' operator; yo
by jlokier 6y ago
The arithmetic should either work, or be type checked.
Multiplying a Q8.24 with another Q8.24 makes a Q16.48.
In C that's not the same as the '∗' operator; you'd generally cast both arguments to 64-bit first, and rely on the compiler being smart enough to use a 32x32->64 instruction if available instead of 64x64->64. But even that's ambiguous - is it signed or unsigned widening multiplication?
Adding a Q8.8 to a Q4.12 needs a 4-bit shift before the addition. So does adding a Q5.27 to Q1.31.
The right thing to do is, unfortunately, ambiguous.
E.g. when adding Q5.27 to Q1.31, do you need to keep the full range and precision and end up with Q6.31? Or do you right shift the second argument, ignore overflow, and call it a day with a Q5.27 result that is implemented in C as (uint32_t)(a + (b >> 4)? (Though if it's signed, which it usually is, (b >> 4) is dodgy in C anyway as it's implementation-defined.) If you do ignore overflow, is that a saturating addition (like used for audio/graphics) or wraparound (like in C)?
Really, those decisions depend on what the numbers mean, as well as range and precision assumptions the author may already know are valid for numerical reasons. So maybe there's a case for traits on number types which specify whether they are default-saturating, default-precision-maintaining, default-range-maintaining.
Another operation is to change the representation, either to truncate/round some precision bits, reduce range bits (saturating or assuming), or expand range bits prior to doing some sums (because addition doesn't expand the range bits in real implementations, you have to explicitly do that yourself in advance of adding).
The way I see this done in careful DSP in C or C-like languages is as a series of function or macro calls that specify input and output formats, avoiding operators and the ambiguity they imply.
- zozbot234 6y agoWorth noting that C does have a draft standard extension for fixed point arithmetic, that ought to address these issues.