Entropy/Narcissist: Difference between revisions

→‎{{header|Ruby}}: Used newer tally method, calculate size outside the loop
(Ada version)
(→‎{{header|Ruby}}: Used newer tally method, calculate size outside the loop)
Line 884:
=={{header|Ruby}}==
<lang ruby>def entropy(s)
counts = s.each_char.with_object(Hash.new(0.0)) {|c,h| h[c] += 1}tally
size = s.size.to_f
counts.values.reduce(0) do |entropy, count|
freq = count / s.size
entropy - freq * Math.log2(freq)
end
end
s = File.read(__FILE__)
p entropy(s)</lang>
 
s = File.read(__FILE__)
p entropy(s)</lang>
</lang>
{{out}}
<pre>4.653607496799478
4.885234973253878
</pre>
 
1,149

edits