(42, all flavours) Integer Division - how?
|
12-13-2020, 01:24 AM
Post: #11
|
|||
|
|||
RE: (42, all flavours) Integer Division - how?
There is the "cheating" way, by temporarily setting the rounding mode
I coded mathx.setround() for this purpose PHP Code: require 'mathx' Another way is to correct the quotient of a and b (assumed both integers) Here, we assumed q, Q may have errors of ±1 a = q*b + r = q*c - q + r , where c = b+1 a = Q*c + R 0 = (q-Q)*c - q + r - R → -q + r - R ≡ 0 (mod c) Since r and R can be calculated with MOD, we can correct for q Assuming |q| < 2^53, this is the code: PHP Code: function idiv2(a,b) -- assumed b > 0 lua> a = 0x1p72 lua> for b=1e6+1, 1e6+9 do : q = idiv1(a,b) -- reference : print(b, q - floor(a/b), q - idiv2(a,b)) : end 1000001 -1 0 1000002 -1 0 1000003 -1 0 1000004 0 0 1000005 0 0 1000006 0 0 1000007 0 0 1000008 0 0 1000009 -1 0 |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 15 Guest(s)