# How to Handle Infinity in calculations?

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

• What do you want it to be equal to instead? 0? Dec 13, 2015 at 20:39
• @march yes i want it equal to zero instead of infinity Dec 13, 2015 at 20:54
• That sounds like a bad idea...
– user484
Dec 14, 2015 at 0: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. Dec 14, 2015 at 3:24
• @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... Dec 14, 2015 at 19:15

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.}

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}


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.}