1

With reference to this post, can one define 0 Log[0] = 0 in Mathemtica?

H. Kenan
  • 663
  • 6
  • 13
  • 2
    This might be an XY problem. What are you trying to do? – J. M.'s missing motivation Mar 08 '19 at 11:08
  • 1
    That being said, I would use Function[r, Piecewise[{{Log[r^r], 0 < r < 1}, {r Log[r], 1 < r}}, 0], Listable]. – J. M.'s missing motivation Mar 08 '19 at 11:08
  • The problem I'm facing is that in my code I have terms like x Log[x]; when x becomes very small, Mathematica shows indeterminate when it should show 0. – H. Kenan Mar 08 '19 at 11:13
  • You might evaluate with Limit[f, x -> x0]. – Michael E2 Mar 08 '19 at 11:41
  • The problem is that my function f involves many such terms (many different variables x), so I need a general rule which will automatically set x Log[x] = 0 for small x. – H. Kenan Mar 08 '19 at 11:53
  • Is this for an entropy calculation? – Roman Mar 08 '19 at 13:02
  • 1
    *IF* the coefficient of Log[x] always vanishes with an order higher than some x^r, r > 0, as x -> 0, then the following should work: log[x_?NumericQ /; x != 0] := Log[x]; expr /. Log -> log /. Thread[{x, y, z} -> 0.] /. log -> Log. Some tweaking may be needed depending on the application. – Michael E2 Mar 08 '19 at 13:39
  • 1
    A similar approach could be used with @J.M.'s function but defining xlogx[x] and replacing expr /. Log -> (xlogx[#]/# &) // Simplify – Michael E2 Mar 08 '19 at 13:43

2 Answers2

2

You can use Inactive here.

expr = (1 - x) Log[1 - x];
iexpr = expr /. Log -> Inactive[Log];

Now, insert a number, activate after numeric evaluation of everything but Log.

iexpr /. x -> -2. // Activate
(* 3.29584 *)

Because you've controlled the order of evaluation, the troublesome case becomes zero.

iexpr /. x -> 1. // Activate
(* 0. *)

Activate not needed in this special case, but harmless.

This works for exact numbers and machine numbers. For controlled precision, you'll need to do more.

John Doty
  • 13,712
  • 1
  • 22
  • 42
  • 2
    This is similar to the approach in my comment, and probably should have the same priviso, "IF the coefficient of Log[x] always vanishes with an order higher than some x^r, r > 0, as x -> 0,..." – Michael E2 Mar 08 '19 at 16:09
0

You can define

s[0|0.] = 0;
s[x_] = -x*Log[x];
SetAttributes[s, Listable]

and then use the function s instead of x Log[x]. If you also have values of $x<0$ then other definitions should be added.

Roman
  • 47,322
  • 2
  • 55
  • 121
  • Thanks, @Roman. How can one put further restrictions like s[x]=0 for say x<10^(-15). – H. Kenan Mar 08 '19 at 16:31
  • @TobiasFritzn take a look at the Picewise function. – gothicVI Mar 09 '19 at 00:09
  • I don't think you need to make a separate definition for, say, x<10^(-15), as the function x*log(x) is well-behaved around x=0. There's only really a need for a special definition at the very point x=0. – Roman Mar 09 '19 at 01:23