unit Unit1;
interface
uses
System.Generics.Defaults, System.Generics.Collections, System.SysUtils,
System.Math;
type
TShannonEntropy =
class
public
class function Calculate<T > (
const Source:
array of T ): Double;
overload;
class function Calculate<T > (
const Source:
array of T;
const Comparer: IEqualityComparer<T> ): Double;
overload;
end;
implementation
{ TShannonEntropy }
class function TShannonEntropy.Calculate<T>(
const Source:
array of T;
const Comparer: IEqualityComparer<T> ): Double;
var
d: TDictionary<T, Integer>;
i: Integer;
p,r: Double;
begin
d := TDictionary<T, Integer>.Create( Comparer );
try
for i := Low( Source )
to High( Source )
do
begin
if d.ContainsKey( Source[i] )
then
d[Source[i]] := d[Source[i]] + 1
else
d.Add(Source[i],1);
end;
Result := 0;
for i
in d.Values
do
begin
p := i / Length( Source );
r := p * Log2( p );
Result := Result + r;
end;
Result := -Result;
finally
FreeAndNil( d );
end;
end;
class function TShannonEntropy.Calculate<T>(
const Source:
array of T ): Double;
begin
Result := Calculate<T > ( Source, TEqualityComparer<T>.
Default );
end;
end.