Here is an alternative, that could seem more useful to me.

( ''"_`(_"_)@.(_1 = *) , #:@|) _3
_ 1 1
( ''"_`(_"_)@.(_1 = *) , #:@|) 3
1 1

Your version creates an encoding of _3 that is identical to 5.  Which might be 
a problem when inverting.


there is also this traditional encoding where 31 could be a dyadic or adverb 
parameter.


( 0:`1:@.(_1 = *) , (31#2) #: |) _3
________________________________
From: Raul Miller <[email protected]>
To: Programming forum <[email protected]> 
Sent: Thursday, November 12, 2015 12:34 PM
Subject: [Jprogramming] twos complement


The #: monad as designed and implemented gets quirky when working with
negative numbers.

Here's a workaround for that issue:

sbits=: $ $ #:@(, -@+:@(>./)@|)@,

Here's how it looks in action:

   sbits 3
0 1 1
   sbits 2
0 1 0
   sbits 1
0 1
   sbits -3
1 0 1
   sbits i.3 3
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0

0 0 0 1 1
0 0 1 0 0
0 0 1 0 1

0 0 1 1 0
0 0 1 1 1
0 1 0 0 0
   sbits i:4
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
   sbits 0
0

In other words, you get a leading sign bit, which is 0 for positive
numbers and 1 for negative numbers.

But this would mean that #. isn't an inverse here. (It's already not,
for negative numbers, but we have all the information we need with
this approach). So:

   sbits=: ($ $ #:@(, -@+:@(>./)@|)@,) :.((-@-:@]+]|-:@]+#.@[) 2^{:@$)
   sbits inv sbits i:4
_4 _3 _2 _1 0 1 2 3 4

I think this would be more readable with explicit definitions (because
then I could use &. ). So:

sbits=:3 :0  :.isbits
  anchor=: -2*>./|y
  ($y) $ #:(,y),anchor
)

isbits=:3 :0  :.sbits
  i=.2^{:$y
  e=.<.i%2
  i&|&.(e&+) #.y
)

(examples work the same).

It might be worth having isbits give an arbitrary precision result for
right arguments which would otherwise be approximated? (Or, something
approximating that.) Given that I don't know how the numbers will be
used, I'm sure for a 64 bit machine if that should be at 53 bits
(floating point representation) or at 64 bits (integer
representation). Probably integer representation makes more sense and
it's the user's responsibility if that's a problem...

As for the subject line, it's a reference to this:
https://en.wikipedia.org/wiki/Two%27s_complement

Thanks,

-- 
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to