I'm trying to write a generic algorithm for integer-only (no floating-point involved) division that includes rounding (rounding 0.5 away from zero) and avoids overflow. The function should basically work like this floating-point equivalent.
Code: Select all
(define (int-div-round1 i1 i2)
(round (div i1 i2))
)
Code: Select all
(define (int-div-round2 i1 i2)
(setq half2 (/ i2 2))
(/ (+ i1 half2) i2)
)
(1) only accurate when i1 and i2 have the same sign (i.e. both positive or both negative)
(2) can overflow
#1 isn't too difficult to fix, but I haven't found an approach that avoid #2. All my brainstorming, trial-and-errors, and Googling have failed me.
Maybe a clever newLISPer has some thoughts?