4

In my numerical calculations I have a list of Eigenvalues with some of them equal to zero. So, when I calculate the log to the base 2 I get infinity those eigenvalues due to Log[2,0] output.

Question: How can I avoid Log[2,0] in my lengthy code, i.e. to get 0 instead of -Infinity?

Thanks and regards

garej
  • 4,865
  • 2
  • 19
  • 42
Usman
  • 157
  • 7
  • 2
    What do you want it to be equal to instead? 0? – march Dec 13 '15 at 20:39
  • @march yes i want it equal to zero instead of infinity – Usman Dec 13 '15 at 20:54
  • 4
    That sounds like a bad idea... –  Dec 14 '15 at 00:03
  • @Rahul, this would also be the first time I've seen anyone wanting to zero out an infinite logarithm, but there certainly is precedent for zeroing out an infinity: consider the computation of the pseudoinverse from the SVD. Now, whether this zeroing out is appropriate here… is the OP's responsibility. – J. M.'s missing motivation Dec 14 '15 at 03:24
  • 2
    @Usman, do you think you will ever start to accept the answers to your questions according to the site charter? It helps other users and clean the site queue... – garej Dec 14 '15 at 19:15

3 Answers3

6

Let's assume you want to avoid indeterminate values by replacing them with 0

ClearAll@LogTwo
SetAttributes[LogTwo, {Listable, NumericFunction}]

LogTwo[0 | 0.] := 0
LogTwo[x_?NumericQ] := Log2[x]

list = {1, 0, 2.};

Log[2, list]

{0, -Infinity, 1.}

LogTwo[list]

{0, 0, 1.}

eldo
  • 67,911
  • 5
  • 60
  • 168
4

Another approach is to directly set the unwanted infinities to zero:

list = {1, 0, 2.};
Log[list] /. {Infinity -> 0, -Infinity -> 0}

{0, 0, 0.693147}
bill s
  • 68,936
  • 4
  • 101
  • 191
2

You may use constrain on pattern and use ReplaceAll (/.):

list = {1, 1., 0, 0., 2, 2.}

list /. (x_ /; x > 0) -> Log2[x]

or

list /. x_?Positive -> Log[2, x]

Result:

{0, 0., 0, 0., 1, 1.}

garej
  • 4,865
  • 2
  • 19
  • 42