38 ms·
I came up with a cute algorithm for arbitrary division with repeated shifts when working on one of my earlier projects, which was an emulator for a trinary comp
by marginalia_nu 4y ago
I came up with a cute algorithm for arbitrary division with repeated shifts when working on one of my earlier projects, which was an emulator for a trinary computer (where obviously dividing by 3 was a thing of import).
A recursive expression is derived like this
1 1 b-a
--- - --- = ----
a b a b
1 1 (b-a) 1
--- = --- + ----- ---
a b b a
If you select 1/b to be nearby a power of your base, this recursive relationship can be expanded until you get adequate precision.
e.g. to express 1/7 in terms of divisions by 8 (i.e. binary shifts by 3)
1 1 1
- = - ( 1 + ---)
7 8 7
1 1 1 1
- = - + --- (1 + ---)
7 8 64 7
1 1 1 1 1
- = - + --- + --- ( 1 + --- )
7 8 64 512 7
So you get v/7 = v>>3 + v>>6 + v>>9 + v>>12 + ... (mind the carry). You sometimes end up needing to do some multiplication too but usually b can be chosen to make the problem a series of trivial operations.
Good expression to be able to derive in case you need to rebuild humanity from a box of nand gates.
Thanks for coming to my TED talk.