8

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.

kglr
  • 394,356
  • 18
  • 477
  • 896
a20
  • 912
  • 5
  • 17

2 Answers2

10
SetAttributes[division, Listable]
division[{1, 2, 0}, {0, 1, 2}]

{-1, 2, 0}

kglr
  • 394,356
  • 18
  • 477
  • 896
4

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}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355