(42, all flavours) Integer Division - how?
|
12-19-2020, 09:56 PM
(This post was last modified: 12-21-2020 10:04 PM by Albert Chan.)
Post: #45
|
|||
|
|||
RE: (42, all flavours) Integer Division - how?
In the mean time, this is my implementation for remainder(a,b), for Free42 Decimal.
Since a = q*b + r = (-q)*(-b) + r, remainder(a,b) = remainder(a,|b|) That's why I set b = |b|, before the code even started. This allowed REM work with signed arguments, both a and b. Code: 00 { 44-Byte Prgm } Example: (for halfway case, quotient must be even) 459 40 XEQ "REM" → 19 = 459 - 11*40 460 40 XEQ "REM" → -20 = 460 - 12*40 461 40 XEQ "REM" → -19 = 461 - 12*40 -459 40 XEQ "REM" → -19 = -459 + 11*40 -460 40 XEQ "REM" → 20 = -460 + 12*40 -461 40 XEQ "REM" → 19 = -461 + 12*40 9 PI XEQ "MOD" → 2.716814692820413523074713233440994 9 PI XEQ "REM" → -0.424777960769379715387930149838509 Since REM based from MOD, it is numerically better if we pull out a's sign. This way, we avoided floor-mod subtraction cancellation errors, when it "fix" sign. remainder(a,b) = sign(a) * remainder(|a|, b) We can use REM to implement DIV, like this (12-18-2020 12:08 AM)Albert Chan Wrote: remainder() based idiv is very elegant. |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 10 Guest(s)