Input
A matrix M
represented as two space separated lines of integers. Each line will have the same number of integers and each integer will be either -1 or 1. The number of integers per line will be at most 20. M
will therefore be 2
by n
where n
is the number of integers on each of the two lines.
Your code should be a complete program. and accept the input either on standard in or from a file (that is your choice). You can accept input from standard in, from a file or simply as a parameter. However, if you do the latter please give an explicit example of how your code should work and remember that it must be a complete program and how the matrix M
will be represented in the input. In other words, you are likely to have to do some parsing.
Output
The binary Shannon entropy of the distribution of M*x
where the elements of x
are uniformly and independently chosen from {-1,1}. x
is an n
-dimensional column vector.
The entropy of a discrete probability distribution is
- sum p_i log_2(p_i)
In this case, p_i
is the probability of the i
th unique possible M*x
.
Example and helpful hints
As a worked example, let the matrix M
be
-1 1
-1 -1
Now look at all 2^2
different possible vectors x
. For each one we compute M*x
and put all the results in an array (a 4-element array of 2-component vectors). Although for each of the 4 vectors the probability of it occurring is 1/2^2 = 1/4
, we are only interested in the number of times each unique resultant vector M*x
occurs, and so we sum up the individual probabilities of the configurations leading to the same unique vectors. In other words, the possible unique M*x
vectors describe the outcomes of the distribution we're investigating, and we have to determine the probability of each of these outcomes (which will, by construction, always be an integer multiple of 1/2^2
, or 1/2^n
in general) to compute the entropy.
In the general n
case, depending on M
the possible outcomes of M*x
can range from "all different" (in this case we have n
values of i
in p_i
, and each p_i
is equal to 1/2^n
), to "all the same" (in this case there is a single possible outcome, and p_1 = 1
).
Specifically, for the above 2x2
matrix M
we can find by multiplying it with the four possible configurations ([+-1; +-1]
), that each resulting vector is different. So in this case there are four outcomes, and consequently p_1 = p_2 = p_3 = p_4 = 1/2^2 = 1/4
. Recalling that log_2(1/4) = -2
we have:
- sum p_i log_2(p_i) = -(4*(-2)/4) = 2
So the final output for this matrix is 2.
Test cases
Input:
-1 -1
-1 -1
Output:
1.5
Input:
-1 -1 -1 -1
-1 -1 -1 -1
Output:
2.03063906223
Input:
-1 -1 -1 1
1 -1 -1 -1
Output:
3
x
? 2. In the interests of making the question self-contained, how is the binary Shannon entropy ofMx
defined? \$\endgroup\$ – Peter Taylor Dec 30 '15 at 10:37