I have a more likeable tcpl (two's-complement plus) which does not
overflow, has (n+1)-bit sum for n-bit addends. The old version is still
useful and is named tcpl0. I include all of the definitions below
because there are places where the old tcpl has been replaced by tcpl0.
hcinv 1 0 0 0
_8
tcpl~ 1 0 0 0 NB. previously answer would have been 0 0 0 0
1 0 0 0 0
hcinv tcpl~ 1 0 0 0
_16
tcml~ 1 0 0 0 NB. no change of behavior for multiplication
0 1 0 0 0 0 0 0
hcinv tcml~ 1 0 0 0
64
Definitions
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 NB. sum of three
bits
stack =: ,.&.|: NB. stack x over y
hv =: (0 {:: <"1) :: ] NB. return head vector
op =: ] stack~ (2 {. [) , Table {~ [: < (2 {. [) , 2 { [: hv ]
ba =: 0 ,~ 0 ,.~ 0 ,.~ ,. NB. build argument
tcpl0 =: ([: }: [: {:"1 [: op/ ba)"1 NB. simple two's-complement
plus, overflows
arg =: (0 , tcav)`([: tcng 0 , tcav)@.{. NB. equivalent with one
more bit
tcpl =: (tcpl0&arg)"1 NB. NO-OVERFLOW TWO'S-COMPLIMENT PLUS, one
more answer bit
Tbln =: 2 2 2 $ 0 0,1 1,1 1,0 1 NB. table for tcng, see opn
ban =: 0 ,~ 0 ,.~ 0 ,.~ ] NB. build argument, see tcng
opn =: ] stack~ (0 { [) , Tbln {~ [: < (0 { [) ,~ 2 { [: hv ]
tcng =: (1 {"1 [: }: [: opn/ ban)"1 NB. TWO'S-COMPLEMENT NEGATIVE
tcav =: ]`tcng@.{."1 NB. TWO'S-COMPLEMENT ABSOLUTE VALUE
NB. base two multiply by a standard unit vector like 0 0 1 0
bme =: ([ ( (0 #~ 0 { ]) , [ , 0 #~ 1 { ]) [ (>:@] , [: <: #@[ - ])
1 i.~ ])"1
diag =: (* [: = [: i. #)"1 NB. diagonal matrix from diagonal
NB. BASE TWO MULTIPLY
bmul =: ([: tcpl0/ [ bme [: ( (1 = +/)"1@] # ] ) [: diag ])"1
eor =: ((2 2$0 1 1 0) {~ [: < ,)"0 NB. exclusive or
NB. TWO'S-COMPLEMENT MULTIPLY
tcml =: (bmul&tcav`([: tcng bmul&tcav)@.(eor&{.))"1
> On 12/13/2011 9:21 AM, Raul Miller wrote:
>> After some thought, I am in favor of this version (I think first
>> proposed by Henry):
>>
>> ((* *<&0) ,. #:) i:3
>> _1 0 1
>> _1 1 0
>> _1 1 1
>> 0 0 0
>> 0 0 1
>> 0 1 0
>> 0 1 1
>> #. ((* *<&0) ,. #:) i:3
>> _3 _2 _1 0 1 2 3
>>
>> Note also:
>> 2 | ((* *>&0) ,. #:) i:3
>> 0 0 1
>> 0 1 0
>> 0 1 1
>> 0 0 0
>> 1 0 1
>> 1 1 0
>> 1 1 1
>>
>> That said this could be further "improved" by making the #: result
>> follow the p. result pattern (least significant bit first):
>>
>> (|.@#: ,. * *<&0) i:3
>> 1 1 _1
>> 1 0 _1
>> 0 1 _1
>> 0 0 0
>> 1 1 0
>> 1 0 0
>> 0 1 0
>> (|.@#: , * *<&0)"0 i:3
>> 1 0 _1
>> 0 1 _1
>> 1 _1 0
>> 0 0 0
>> 1 0 0
>> 0 1 0
>> 1 1 0
>> #.@|. :(#. |.)"1 (|.@#: ,. * *<&0) i:3
>> _1 _3 _2 0 3 1 2
>> #.@|. :(#. |.)"1 (|.@#: , * *<&0)"0 i:3
>> _3 _2 _1 0 1 2 3
>> 2 p.~ (|.@#: , * *<&0)"0 i:3
>> _3 _2 _1 0 1 2 3
>
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm