title: Shannon Entropy
body: <p>The following C++ code (as is) is from <a href="http://rosettacode.org/wiki/Entropy" rel="nofollow">http://rosettacode.org/wiki/Entropy</a>. There are mistakes - can anyone correct them?</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;map&gt;
  #include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  #include &lt;cmath&gt;
  
  double log2( double number ) {
      return log( number ) / log( 2 ) ;
  }
  
  int main( int argc , char *argv[ ] ) {
      std::string teststring( argv[ 1 ] ) ;
      std::map&lt;char , int&gt; frequencies ;
  
      for ( char c : teststring )
          frequencies[ c ] ++ ;
  
      int numlen = teststring.length( ) ;
      double infocontent = 0 ;
  
      for ( std::pair&lt;char , int&gt; p : frequencies ) {
          double freq = static_cast&lt;double&gt;( p.second ) / numlen ;
          infocontent += freq * log2( freq ) ;
      }
  
      infocontent *= -1 ;
  
      std::cout &lt;&lt; "The information content of " &lt;&lt; teststring 
        &lt;&lt; " is " &lt;&lt; infocontent &lt;&lt; " !\n" ;
      return 0 ;
  }
  </code></pre>
  
  <p>The first error seems to be fixed with:</p>
  
  <pre><code>double log2( double n )  
  {  
      // log(n)/log(2) is log2.  
      return log( n ) / log( 2. );  
  }
  </code></pre>
  
  <p>I'm unsure what they are trying to say with:</p>
  
  <pre><code>for ( char c : teststring )
  </code></pre>