Skip to content

function to set log(0)=0 not working on tables or vectors

5 messages · maiya, Peter Ehlers, David Winsemius +1 more

#
There must be a very basic thing I am not getting...

I'm working with some entropy functions and the convention is to use
log(0)=0.

So I wrote a function:

llog<-function(x){
if (x ==0) 0 else log(x)
}

which seems to work fine for individual numbers e.g.
[1] 0

but if I try whole vectors or tables:

p<-c(4,3,1,0)
q<-c(2,2,2,2)
llog(p/q)

I get this:

[1]  0.6931472  0.4054651 -0.6931472       -Inf


What am I missing?

Thanks!

Maja
#
Are you telling us the whole story? Or did you also
get a warning message which should have twigged the
answer for you?

Try ifelse() instead of if().

  -Peter Ehlers
maiya wrote:

  
    
#
On Jan 17, 2010, at 8:17 PM, maiya wrote:

            
I suppose the outcome of that effort may depend on whether you have  
assumed the needed godlike capacities to change the laws of  
mathematics. But I suppose that as the Earth mother that might occur  
to you. Go ahead, define a new mathematics.
#
David Winsemius <dwinsemius <at> comcast.net> writes:
My guess is that the real intention here is 
to define 0*log(0) = 0 rather than log(0) = 0 -- 
really the assertion is that lim(x -> 0) x log(x) = 0,
which must be true for some reasonable limiting conditions.
#
Peter, you're right about the error - I had R commander open and used the
terminal instead - this makes me miss the error messages. Not that I would
have known how to solve it had I seen it :)

And yes, ifelse does work. Not sure I understand what the difference is, but
thanks!

David, I had no idea god could change the laws of mathematics. If that's
true then you have to choose between believing in on or the other? Nice one!

Of course Ben is right, the convention is 0*log(0)=0 but for the purposes of
programming it in an entropy function I only need to define log(0)=0. I
apologize for not being more precise.

Thanks guys!

Maja.
Ben Bolker wrote: