Post Reply 
(42, all flavours) Integer Division - how?
12-19-2020, 09:21 PM
Post: #44
RE: (42, all flavours) Integer Division - how?
(12-19-2020 10:03 AM)Werner Wrote:  Since b+b may overflow, I tend to stick to idiv3:

We can generalized, to r = a % (b*base), to avoid rounding errors (base must be even)

Halfway case, r = k*b, possible k = 0.5, 1.5, 2.5, 3.5, 4.5, ... (base-0.5)
Since we can subtract multiples of 2b, still keeping even quotient, we have:

k = 0.5, 2.5, 4.5 ... ⇒ remainder(a,b) = +b/2
k = 1.5, 3.5, 5.5 ... ⇒ remainder(a,b) = −b/2

→ if floor(k) is odd then q := q - 1

lua> a, b = 460, 40
lua> q = rint(a/b) -- rint(11.5) = 12 (round-to-even)
lua> for base = 2, 12, 2 do
:      k = a % (b*base) / b
:      print(base, k, q - floor(k)%2)
:      end

2   1.5   11
4   3.5   11
6   5.5   11
8   3.5   11
10  1.5   11
12 11.5   11


Of course, it is best if Free42 had REM function.
Both IEEE double and decimal128 already have them built-in.
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: (42, all flavours) Integer Division - how? - Albert Chan - 12-19-2020 09:21 PM



User(s) browsing this thread: 15 Guest(s)