Post Reply 
(42S) Quotient and Remainder
04-06-2023, 02:55 PM
Post: #7
RE: (42S) Quotient and Remainder
Floor-divide may be more useful, in the sense that it is trivial to convert to other kinds.

Code:
def sign(x): return (x>0) - (x<0)
def qr_floor(y,x, s=1): return divmod(s*y,x)
def qr_trunc(y,x, s=1): q,r = divmod(s*abs(y),abs(x)); return sign(x*y)*q, sign(y)*r
def qr_ceil(y,x): q,r = qr_floor(y,x,-1); return -q,-r
def qr_away(y,x): q,r = qr_trunc(y,x,-1); return -q,-r

>>> y, x = 10, 7
>>> funcs = (qr_floor, qr_trunc, qr_ceil, qr_away)
>>> args = ((y,x), (-y,x), (y,-x), (-y,-x))
>>> for f in funcs: print f.__name__, [f(*a) for a in args]
...
qr_floor [(1, 3), (-2, 4), (-2, -4), (1, -3)]
qr_trunc [(1, 3), (-1, -3), (-1, 3), (1, -3)]
qr_ceil  [(2, -4), (-1, -3), (-1, 3), (2, 4)]
qr_away  [(2, -4), (-2, 4), (-2, -4), (2, 4)]



Truncated quotient, because of symmetry, is easier to implement.
It also has the accuracy advantage: y = (qt x) + rt

RHS terms have same sign, thus no cancellation errors.
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
(42S) Quotient and Remainder - Werner - 04-05-2023, 09:38 AM
RE: (42S) Quotient and Remainder - Werner - 04-05-2023, 01:11 PM
RE: (42S) Quotient and Remainder - Werner - 04-05-2023, 03:55 PM
RE: (42S) Quotient and Remainder - Albert Chan - 04-06-2023 02:55 PM



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