Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

mul_u64_u64_div_u64: increase precision by conditionally swapping a and b

As indicated in the added comment, the algorithm works better if b is big.
As multiplication is commutative, a and b can be swapped. Do this if a
is bigger than b.

Link: https://lkml.kernel.org/r/20240303092408.662449-2-u.kleine-koenig@pengutronix.de
Signed-off-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Tested-by: Biju Das <biju.das.jz@bp.renesas.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>

authored by

Uwe Kleine-König and committed by
Andrew Morton
8c86fb68 4bb7be96

+15
+15
lib/math/div64.c
··· 22 22 #include <linux/export.h> 23 23 #include <linux/math.h> 24 24 #include <linux/math64.h> 25 + #include <linux/minmax.h> 25 26 #include <linux/log2.h> 26 27 27 28 /* Not needed on 64bit architectures */ ··· 191 190 192 191 /* can a * b overflow ? */ 193 192 if (ilog2(a) + ilog2(b) > 62) { 193 + /* 194 + * Note that the algorithm after the if block below might lose 195 + * some precision and the result is more exact for b > a. So 196 + * exchange a and b if a is bigger than b. 197 + * 198 + * For example with a = 43980465100800, b = 100000000, c = 1000000000 199 + * the below calculation doesn't modify b at all because div == 0 200 + * and then shift becomes 45 + 26 - 62 = 9 and so the result 201 + * becomes 4398035251080. However with a and b swapped the exact 202 + * result is calculated (i.e. 4398046510080). 203 + */ 204 + if (a > b) 205 + swap(a, b); 206 + 194 207 /* 195 208 * (b * a) / c is equal to 196 209 *