我終於找到一個代碼可能工作香農熵計算,但由於我不完全理解C#,有人可以幫助我完全掌握它?我的意思是純粹理解代碼,而不是它在做什麼。如果你問,我確實瞭解德爾福。瞭解這個C#代碼,我的意思是隻有代碼,而不是Entropy的理論
public static double ShannonEntropy(string s)
{
var map = new Dictionary<char, int>();
foreach (char c in s)
{
if (!map.ContainsKey(c))
map.Add(c, 1);
else
map[c] += 1;
}
double result = 0.0;
int len = s.Length;
foreach (var item in map)
{
var frequency = (double)item.Value/len;
result -= frequency * (Math.Log(frequency)/Math.Log(2));
}
return result;
}
關於代碼的「什麼」不清楚?有一種方法,序列上的兩個循環,一些賦值變量,一個Dictionary和一些數學......非常程序化,就像Delphi。 – user2864740
@ user2864740字典我不清楚 – Vlastimil
它與Delphi中的TDictionary具有相同的作用:http://delphi.about.com/od/beginners/a/using-t-dictionary-hash-tables-in-delphi .htm - 請參閱http://www.dotnetperls.com/dictionary,https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx等 – user2864740