Below I present tcpl "two's-complement plus". It works with the
transpose of the arrangement below for adding two's-complement numbers:
1 1 0 0 (value _4)
1 1 0 1 (value _3)
-------
1 1 0 0 (carries shifted to the right)
1 0 0 1 (answer, value _7)
Working above from right to left, you say 0 plus 1 is 0 1 and write 0 1
vertically below the line. Next you say 0 plus 0 plus 0 is 0 0 (the
first 0 is the carry from the preceding step) and write 0 0 vertically
below the line. Continuing, you say 0 plus 1 plus 1 is 1 0 and 1 plus 1
plus 1 is 1 1 . The answer 1 0 0 1 is in the bottom line.
hc =: {.@#:@(,: 2 * |) NB. Raul's improved #: (hash colon)
hcinv =: ([: -/ [: #. (,: [: +: 1 {. ]))"1 NB. Henry Rich
Table =: 2 2 2 2 $ 0 0,0 1,0 1,1 0,0 1,1 0,1 0,1 1
(< 1 1 1) { Table NB. sum of three bits
1 1
stack =: ,.&.|: NB. stacks x over y
hv =: (0 {:: <"1) :: ] NB. returns head vector
op =: ] stack~ (2 {. [) , Table {~ [: < (2 {. [) , 2 { [: hv ]
ba =: 0 ,~ 0 ,.~ 0 ,.~ ,. NB. build argument
1 1 0 0 ba 1 1 0 1 NB. starting table
1 1 0 0
1 1 0 0
0 0 0 0
0 1 0 0
0 0 0 0
op/ 1 1 0 0 ba 1 1 0 1
1 1 1 1
1 1 1 0
0 0 0 0
0 1 0 1
0 0 0 0
NB. above see transpose of arrangement at top, with an added
NB. row of 0's
tcpl =: [: }: [: {:"1 [: op/ ba NB. two's-complement plus
1 1 0 0 tcpl 1 1 0 1 NB. _4 plus _3 is _7
1 0 0 1
hc _4 _3 _7
1 1 0 0
1 1 0 1
1 0 0 1
On 12/10/2011 6:48 PM, Kip Murray wrote:
> Cool. I think it is an improvement because it neatly avoids a case
> statement. Now I wonder if we could implement two's-complement addition
> and multiplication with overflow, basing these on bitwise operations
>
> 0 + 0 is 0, 0 + 1 is 1 + 0 is 1, and 1 + 1 is 1 0
>
> 0 * 0 is 0 * 1 is 1 * 0 is 0, and 1*1 is 1
>
> That is, I do not want hc and hcinv to be used except to produce data
> and check answers, and I want n-bit two's-complement answers for n-bit
> two's-complement data so some of them will be wrong because of overflow.
ADDED LATER -- ACCEPT 2n-bit multiplication answers from n-bit data
>
> Here for Linda is Henry's hcinv expressed without conjunctions other
> than " .
>
> hcinv =: ([: -/ [: #. (,: [: +: 1 {. ]))"1
>
> On 12/10/2011 10:00 AM, Henry Rich wrote:
>> Same idea, better implementation
>>
>> hcinv =. -/@:#.@:(,: +:@(1&{.))"1
>>
>> Henry Rich
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm