8
$\begingroup$

I have some lists of data that I need to divide by each-other, but my problem is that for some values the denominator is zero. Now these particular values are not very important, but I still need to keep them in the lists.

To solve my problem, I tried defining my own division function:

division[a_,b_]:=a/b
division[a_,0]=-1

This works great for single numbers,

division[52,0]
out: -1

but not for lists:

division[{1,2,0},{0,1,2}]
out: {ComplexInfinity,2,0}

How do I make my predefined output work for lists as well?

Of course, another solution to my problem would be to iterate over the list with e.g. a For loop and an If, but I think there should be a neater way of doing this.

$\endgroup$
10
$\begingroup$
SetAttributes[division, Listable]
division[{1, 2, 0}, {0, 1, 2}]

{-1, 2, 0}

$\endgroup$
4
$\begingroup$

Another possibility is to use Block:

division[a_, b_] := Quiet @ Block[{DirectedInfinity},
    DirectedInfinity[]=-1;
    Divide[a, b]
]

division[{1, 2, 0}, {0, 1, 2}]

{-1, 2, 0}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.