5
$\begingroup$

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

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

3 Answers 3

6
$\begingroup$

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

$\endgroup$
0
4
$\begingroup$

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}
$\endgroup$
0
2
$\begingroup$

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

$\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.