Commit 83185ab
committed
Add mult_frac() to handle fractional multiplication safely
Introduce a new inline function mult_frac() to compute "x * n / d" with
enhanced precision and safety. This function addresses the common
issues of overflow and loss of precision that can occur with
straightforward approaches to this calculation.
Directly computing "x * n / d" can lead to problems:
- Performing the division first can result in loss of precision due to
integer truncation.
- Performing multiplication before division can risk overflow.
The mult_frac() function mitigates these issues by:
1. Calculating the quotient and remainder of 'x' divided by 'd'.
2. Using these intermediate results to perform the final calculation,
thus avoiding intermediate overflow and preserving precision.
This approach is based on the Linux kernel's mult_frac() macro [1],
which follows a similar method to handle these calculations robustly.
Link: https://elixir.bootlin.com/linux/v6.10.7/source/include/linux/math.h#L121 [1]1 parent 1023b4c commit 83185ab
1 file changed
+13
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
22 | 35 | | |
23 | 36 | | |
24 | 37 | | |
| |||
0 commit comments