I'm also a J-newbie, but I would make up a new verb that did "divide, but not by
zero".
I can distinguish between zero and non-zero by Bonding[0] a 0 to Equal[1]
0&= y
1 0
0 0
I know about Agenda[2] which selects a verb from a gerund[2]. E.g.,
x ( + ` - ` * ` % @. 3) y
_ 2
1 0.666667
is an awkward way to say x % y , but try it for other values of 3.
If the input is non-zero (0&=y produces a 0) then I want to apply %, but if the
input is zero (0&=y produces a 1) I want to return a 0. So my gerund is
myGerund=. % ` 0:
to allow me to select either Divide or the constant 0 verb[3].
The "divide, but not by zero" verb will be a dyad, but in this case the
selector for Agenda is a monad (just a function of the right argument), so I need to make
a dyad that only uses its right argument
mySelector=. [: 0&= ]
and then I want to use Agenda to select from the gerund
x (myGerund @. mySelector)"(0 0) y
0 2
1 0.666667
Compare this to the "Case statement" example from the Agenda dictionary entry.
I can wrap that in a new dyad
divideButNotByZero=: 4 : 0
myGerund=. % ` 0:
mySelector=. [: 0&= ]
x (myGerund @. mySelector)"(0 0) y
)
x divideButNotByZero y
0 2
1 0.666667
Or I can use it as a one-liner
x ((% ` 0:) @. ([: 0&= ]))"(0 0) y
0 2
1 0.666667
I'm not happy about parts of this and about and I hope others will educate me. I'm not happy
about the way I turned 0&= into a monad, though I have to say that nothing says "I'm a
monad" like [: g ] . The other is that I had to apply the Agenda to atoms of x and y by
using the "(0 0) conjunction. It would seem more J-ish to make up an appropriate matrix of
verbs and then apply that to the items of x and y. I know I don't know how to do that.
... peter
[0] http://www.jsoftware.com/help/dictionary/d630n.htm
[1] http://www.jsoftware.com/help/dictionary/d000.htm
[2] http://www.jsoftware.com/help/dictionary/d621.htm
[3]http://www.jsoftware.com/help/dictionary/dconsf.htm
On 05/17/13 15:44, P T wrote:
I am learning J (J602) and dividing one table with another. When division
by zero occurs, I want the the value to be zero instead of infinity. For
example, in the results below, I want the first element to be 0.0 instead
of _
]x =. 2 2 $ 2
2 2
2 2
]y=. 2 2 $ i.4
0 1
2 3
x%y
_ 2
1 0.666667
May be I can replace all occurrences of _ with 0.0. But, can I avoid this
additional step?
Thanks,
PT
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm