I have a function in Python which calculates the entropy of a number of parameters which I call ps as follows
def H(*ps):
sum = 0.0
for pi in ps:
sum = sum - pi*np.log2(pi)
return sum
I want to be able to pass in multiple parameters as a list or tuple, i.e. H([x]) but this doesn't give the correct result, rather it calculates the value of H(xi) and returns a tuple with each result. I am able to sum each element of the tuple to get the correct result due to the nature of the function but I'd rather be able to have the function give the desired output for convenience. If I enter H(x1, x2, ...) the function gives the correct output.
If anyone has any suggestions please let me know.
Thanks in advance.
EDIT:
Sample input and output:
x = [0.1, 0.2]
print H(0.1, 0.2), H(x)
0.796578428466 [ 0.33219281 0.46438562]
Don't unpack via the * operator in your function definition. You are already iterating your list via your for loop. It's natural to use an iterable as a function argument.
def H(ps):
x = 0.0
for pi in ps:
x = x - pi*np.log2(pi)
return x
res = H([0.1, 0.2])
print(res)
0.796578428466
In addition, don't shadow the built-in sum, this is poor practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With