Entropy: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 39: Line 39:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>F entropy(source)
<syntaxhighlight lang="11l">F entropy(source)
DefaultDict[Char, Int] hist
DefaultDict[Char, Int] hist
L(c) source
L(c) source
Line 49: Line 49:
R r
R r


print(entropy(‘1223334444’))</lang>
print(entropy(‘1223334444’))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 57: Line 57:
=={{header|Ada}}==
=={{header|Ada}}==
Uses Ada 2012.
Uses Ada 2012.
<lang Ada>with Ada.Text_IO, Ada.Float_Text_IO, Ada.Numerics.Elementary_Functions;
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Float_Text_IO, Ada.Numerics.Elementary_Functions;


procedure Count_Entropy is
procedure Count_Entropy is
Line 84: Line 84:
Put(Result, Fore => 1, Aft => 5, Exp => 0);
Put(Result, Fore => 1, Aft => 5, Exp => 0);
end;
end;
end Count_Entropy;</lang>
end Count_Entropy;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer c;
<syntaxhighlight lang="aime">integer c;
real h, v;
real h, v;
index x;
index x;
Line 102: Line 102:
}
}


o_form("/d6/\n", h);</lang>
o_form("/d6/\n", h);</syntaxhighlight>
Examples:
Examples:
<pre>$ aime -a tmp/entr 1223334444
<pre>$ aime -a tmp/entr 1223334444
Line 112: Line 112:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# calculate the shannon entropy of a string #
# calculate the shannon entropy of a string #
PROC shannon entropy = ( STRING s )REAL:
PROC shannon entropy = ( STRING s )REAL:
Line 142: Line 142:
print( ( shannon entropy( "1223334444" ), newline ) )
print( ( shannon entropy( "1223334444" ), newline ) )


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 150: Line 150:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
{{trans|ALGOL 68}}
{{trans|ALGOL 68}}
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% calculates the shannon entropy of a string %
% calculates the shannon entropy of a string %
% strings are fixed length in algol W and the length is part of the %
% strings are fixed length in algol W and the length is part of the %
Line 203: Line 203:
write( shannon_entropy( "1223334444", 10 ) )
write( shannon_entropy( "1223334444", 10 ) )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 210: Line 210:


=={{header|APL}}==
=={{header|APL}}==
<lang apl>
<syntaxhighlight lang="apl">
ENTROPY←{-+/R×2⍟R←(+⌿⍵∘.=∪⍵)÷⍴⍵}
ENTROPY←{-+/R×2⍟R←(+⌿⍵∘.=∪⍵)÷⍴⍵}


Line 235: Line 235:
-+/RATIO×2⍟RATIO
-+/RATIO×2⍟RATIO
1.846439345
1.846439345
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 244: Line 244:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>entropy: function [s][
<syntaxhighlight lang="rebol">entropy: function [s][
t: #[]
t: #[]
loop s 'c [
loop s 'c [
Line 257: Line 257:
]
]


print entropy "1223334444"</lang>
print entropy "1223334444"</syntaxhighlight>


{{out}}
{{out}}
Line 264: Line 264:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox, % Entropy(1223334444)
<syntaxhighlight lang="autohotkey">MsgBox, % Entropy(1223334444)


Entropy(n)
Entropy(n)
Line 281: Line 281:
}
}
return, e
return, e
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1.846440</pre>
<pre>1.846440</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
{
{
for (i=1; i<= length($0); i++) {
for (i=1; i<= length($0); i++) {
Line 300: Line 300:
}
}
print E/log(2);
print E/log(2);
}</lang>
}</syntaxhighlight>
{{out|Usage}}
{{out|Usage}}
<lang bash> echo 1223334444 |./entropy.awk
<syntaxhighlight lang="bash"> echo 1223334444 |./entropy.awk
1.84644 </lang>
1.84644 </syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Works with older (unstructured) Microsoft-style BASIC.
Works with older (unstructured) Microsoft-style BASIC.
<lang basic>10 DEF FN L(X)=LOG(X)/LOG(2)
<syntaxhighlight lang="basic">10 DEF FN L(X)=LOG(X)/LOG(2)
20 S$="1223334444"
20 S$="1223334444"
30 U$=""
30 U$=""
Line 329: Line 329:
210 E=E-R(I)
210 E=E-R(I)
220 NEXT I
220 NEXT I
230 PRINT E</lang>
230 PRINT E</syntaxhighlight>
{{out}}
{{out}}
<pre>1.84643935</pre>
<pre>1.84643935</pre>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>FUNCTION L (X)
<syntaxhighlight lang="qbasic">FUNCTION L (X)
L = LOG(X) / LOG(2)
L = LOG(X) / LOG(2)
END FUNCTION
END FUNCTION
Line 360: Line 360:
NEXT I
NEXT I
PRINT E
PRINT E
END</lang>
END</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM.
Works with 1k of RAM.
<lang basic> 10 LET X$="1223334444"
<syntaxhighlight lang="basic"> 10 LET X$="1223334444"
20 LET U$=""
20 LET U$=""
30 FOR I=1 TO LEN X$
30 FOR I=1 TO LEN X$
Line 385: Line 385:
200 LET E=E-R(I)
200 LET E=E-R(I)
210 NEXT I
210 NEXT I
220 PRINT E</lang>
220 PRINT E</syntaxhighlight>
{{out}}
{{out}}
<pre>1.8464393</pre>
<pre>1.8464393</pre>
Line 391: Line 391:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{trans|APL}}
{{trans|APL}}
<lang bbcbasic>REM >entropy
<syntaxhighlight lang="bbcbasic">REM >entropy
PRINT FNentropy("1223334444")
PRINT FNentropy("1223334444")
END
END
Line 414: Line 414:
:
:
DEF FNlogtwo(n)
DEF FNlogtwo(n)
= LN n / LN 2</lang>
= LN n / LN 2</syntaxhighlight>
{{out}}
{{out}}
<pre>1.84643934</pre>
<pre>1.84643934</pre>


=={{header|BQN}}==
=={{header|BQN}}==
<lang bqn>H ← -∘(+´⊢×2⋆⁼⊢)∘((+˝⊢=⌜⍷)÷≠)
<syntaxhighlight lang="bqn">H ← -∘(+´⊢×2⋆⁼⊢)∘((+˝⊢=⌜⍷)÷≠)


H "1223334444"</lang>
H "1223334444"</syntaxhighlight>
{{out}}
{{out}}
<pre>1.8464393446710154</pre>
<pre>1.8464393446710154</pre>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>blsq ) "1223334444"F:u[vv^^{1\/?/2\/LG}m[?*++
<syntaxhighlight lang="burlesque">blsq ) "1223334444"F:u[vv^^{1\/?/2\/LG}m[?*++
1.8464393446710157</lang>
1.8464393446710157</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdbool.h>
Line 476: Line 476:
printf("%lf\n",H);
printf("%lf\n",H);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
Examples:
Examples:
<lang>$ ./entropy
<syntaxhighlight lang="text">$ ./entropy
1223334444
1223334444
1.846439
1.846439
$ ./entropy
$ ./entropy
Rosetta Code is the best site in the world!
Rosetta Code is the best site in the world!
3.646513</lang>
3.646513</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Translation of C++.
Translation of C++.
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
Line 527: Line 527:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>The Entropy of 1223334444 is 1.84643934467102</pre>
<pre>The Entropy of 1223334444 is 1.84643934467102</pre>
Without using Hashtables or Dictionaries:
Without using Hashtables or Dictionaries:
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
namespace Entropy
namespace Entropy
{
{
Line 573: Line 573:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <map>
#include <map>
#include <iostream>
#include <iostream>
Line 601: Line 601:
<< " is " << infocontent << std::endl ;
<< " is " << infocontent << std::endl ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>(entropy "1223334444")
<pre>(entropy "1223334444")
Line 607: Line 607:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(defn entropy [s]
<syntaxhighlight lang="clojure">(defn entropy [s]
(let [len (count s), log-2 (Math/log 2)]
(let [len (count s), log-2 (Math/log 2)]
(->> (frequencies s)
(->> (frequencies s)
Line 613: Line 613:
(let [rf (/ v len)]
(let [rf (/ v len)]
(-> (Math/log rf) (/ log-2) (* rf) Math/abs))))
(-> (Math/log rf) (/ log-2) (* rf) Math/abs))))
(reduce +))))</lang>
(reduce +))))</syntaxhighlight>
{{out}}
{{out}}
<lang Clojure>(entropy "1223334444")
<syntaxhighlight lang="clojure">(entropy "1223334444")
1.8464393446710154</lang>
1.8464393446710154</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% NOTE: when compiling with Portable CLU,
<syntaxhighlight lang="clu">% NOTE: when compiling with Portable CLU,
% this program needs to be merged with 'useful.lib' to get log()
% this program needs to be merged with 'useful.lib' to get log()
%
%
Line 647: Line 647:
po: stream := stream$primary_output()
po: stream := stream$primary_output()
stream$putl(po, f_form(shannon("1223334444"), 1, 6))
stream$putl(po, f_form(shannon("1223334444"), 1, 6))
end start_up </lang>
end start_up </syntaxhighlight>
{{out}}
{{out}}
<pre>1.846439</pre>
<pre>1.846439</pre>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>entropy = (s) ->
<syntaxhighlight lang="coffeescript">entropy = (s) ->
freq = (s) ->
freq = (s) ->
result = {}
result = {}
Line 664: Line 664:
((frq[f]/n for f of frq).reduce ((e, p) -> e - p * Math.log(p)), 0) * Math.LOG2E
((frq[f]/n for f of frq).reduce ((e, p) -> e - p * Math.log(p)), 0) * Math.LOG2E


console.log "The entropy of the string '1223334444' is #{entropy '1223334444'}"</lang>
console.log "The entropy of the string '1223334444' is #{entropy '1223334444'}"</syntaxhighlight>
{{out}}
{{out}}
<pre>The entropy of the string '1223334444' is 1.8464393446710157</pre>
<pre>The entropy of the string '1223334444' is 1.8464393446710157</pre>
Line 672: Line 672:
Not very Common Lisp-y version:
Not very Common Lisp-y version:


<lang lisp>(defun entropy (string)
<syntaxhighlight lang="lisp">(defun entropy (string)
(let ((table (make-hash-table :test 'equal))
(let ((table (make-hash-table :test 'equal))
(entropy 0))
(entropy 0))
Line 681: Line 681:
(log (/ v (length input-string)) 2))))
(log (/ v (length input-string)) 2))))
table)
table)
entropy))</lang>
entropy))</syntaxhighlight>


More like Common Lisp version:
More like Common Lisp version:


<lang lisp>(defun entropy (string &aux (length (length string)))
<syntaxhighlight lang="lisp">(defun entropy (string &aux (length (length string)))
(declare (type string string))
(declare (type string string))
(let ((table (make-hash-table)))
(let ((table (make-hash-table)))
Line 692: Line 692:
(- (loop for freq being each hash-value in table
(- (loop for freq being each hash-value in table
for freq/length = (/ freq length)
for freq/length = (/ freq length)
sum (* freq/length (log freq/length 2))))))</lang>
sum (* freq/length (log freq/length 2))))))</syntaxhighlight>


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang ruby># Method to calculate sum of Float64 array
<syntaxhighlight lang="ruby"># Method to calculate sum of Float64 array
def sum(array : Array(Float64))
def sum(array : Array(Float64))
res = 0
res = 0
Line 734: Line 734:
puts ".[Results]."
puts ".[Results]."
puts "Length: " + l.to_s
puts "Length: " + l.to_s
puts "Entropy: " + (entropy h, l).to_s</lang>
puts "Entropy: " + (entropy h, l).to_s</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm, std.math;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.math;


double entropy(T)(T[] s)
double entropy(T)(T[] s)
Line 752: Line 752:
void main() {
void main() {
"1223334444"d.dup.entropy.writeln;
"1223334444"d.dup.entropy.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1.84644</pre>
<pre>1.84644</pre>
Line 760: Line 760:
{{Trans|Pascal}}
{{Trans|Pascal}}
Just fix Pascal code to run in Delphi.
Just fix Pascal code to run in Delphi.
<syntaxhighlight lang="delphi">
<lang Delphi>
program Entropytest;
program Entropytest;


Line 820: Line 820:
Writeln('Entropy of "', strng, '" is ', entropy(strng): 2: 5, ' bits.');
Writeln('Entropy of "', strng, '" is ', entropy(strng): 2: 5, ' bits.');
readln;
readln;
end.</lang>
end.</syntaxhighlight>
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'hash)
(lib 'hash)
;; counter: hash-table[key]++
;; counter: hash-table[key]++
Line 841: Line 841:
(for/sum ((s (make-set S))) (hi (hash-ref ht s) n)))
(for/sum ((s (make-set S))) (hi (hash-ref ht s) n)))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang="scheme">
;; by increasing entropy
;; by increasing entropy


Line 857: Line 857:
(H (for/list ((i 1000_000)) (random 1000_000))) → 19.104028424596976
(H (for/list ((i 1000_000)) (random 1000_000))) → 19.104028424596976


</syntaxhighlight>
</lang>




Line 863: Line 863:
{{trans|C#}}
{{trans|C#}}
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'math;
<syntaxhighlight lang="elena">import system'math;
import system'collections;
import system'collections;
import system'routines;
import system'routines;
Line 904: Line 904:
console.printLine("The Entropy of ", input, " is ", infoC)
console.printLine("The Entropy of ", input, " is ", infoC)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 913: Line 913:
{{works with|Erlang/OTP|18}}
{{works with|Erlang/OTP|18}}
<code>:math.log2</code> was added in OTP 18.
<code>:math.log2</code> was added in OTP 18.
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def entropy(str) do
def entropy(str) do
leng = String.length(str)
leng = String.length(str)
Line 926: Line 926:
end
end


IO.inspect RC.entropy("1223334444")</lang>
IO.inspect RC.entropy("1223334444")</syntaxhighlight>


{{out}}
{{out}}
Line 934: Line 934:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(defun shannon-entropy (input)
<syntaxhighlight lang="lisp">(defun shannon-entropy (input)
(let ((freq-table (make-hash-table))
(let ((freq-table (make-hash-table))
(entropy 0)
(entropy 0)
Line 948: Line 948:
(log (/ v length) 2)))))
(log (/ v length) 2)))))
freq-table)
freq-table)
(- entropy)))</lang>
(- entropy)))</syntaxhighlight>


{{out}}
{{out}}
Line 955: Line 955:
as shown below (type ctrl-j at the end of the first line
as shown below (type ctrl-j at the end of the first line
and the output will be placed by emacs on the second line).
and the output will be placed by emacs on the second line).
<lang lisp>(shannon-entropy "1223334444")
<syntaxhighlight lang="lisp">(shannon-entropy "1223334444")
1.8464393446710154</lang>
1.8464393446710154</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( entropy ).
-module( entropy ).


Line 979: Line 979:
Frequency = How_many / String_length,
Frequency = How_many / String_length,
{String_length, Acc - (Frequency * math:log(Frequency))}.
{String_length, Acc - (Frequency * math:log(Frequency))}.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 988: Line 988:


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==
<lang EulerMathToolbox>>function entropy (s) ...
<syntaxhighlight lang="eulermathtoolbox">>function entropy (s) ...
$ v=strtochar(s);
$ v=strtochar(s);
$ m=getmultiplicities(unique(v),v);
$ m=getmultiplicities(unique(v),v);
Line 995: Line 995:
$endfunction
$endfunction
>entropy("1223334444")
>entropy("1223334444")
1.84643934467</lang>
1.84643934467</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let ld x = Math.Log x / Math.Log 2.
let ld x = Math.Log x / Math.Log 2.
Line 1,008: Line 1,008:
|> Seq.fold (fun e p -> e - p * ld p) 0.
|> Seq.fold (fun e p -> e - p * ld p) 0.


printfn "%f" (entropy "1223334444")</lang>
printfn "%f" (entropy "1223334444")</syntaxhighlight>
{{out}}
{{out}}
<pre>1.846439</pre>
<pre>1.846439</pre>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: assocs kernel math math.functions math.statistics
<syntaxhighlight lang="factor">USING: assocs kernel math math.functions math.statistics
prettyprint sequences ;
prettyprint sequences ;
IN: rosetta-code.entropy
IN: rosetta-code.entropy
Line 1,023: Line 1,023:
"1223334444" shannon-entropy .
"1223334444" shannon-entropy .
"Factor is my favorite programming language." shannon-entropy .</lang>
"Factor is my favorite programming language." shannon-entropy .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,031: Line 1,031:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: flog2 ( f -- f ) fln 2e fln f/ ;
<syntaxhighlight lang="forth">: flog2 ( f -- f ) fln 2e fln f/ ;


create freq 256 cells allot
create freq 256 cells allot
Line 1,052: Line 1,052:


s" 1223334444" entropy f. \ 1.84643934467102 ok
s" 1223334444" entropy f. \ 1.84643934467102 ok
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==


Please find the GNU/linux compilation instructions along with sample run among the comments at the start of the FORTRAN 2008 source. This program acquires input from the command line argument, thereby demonstrating the fairly new get_command_argument intrinsic subroutine. The expression of the algorithm is a rough translated of the j solution. Thank you.
Please find the GNU/linux compilation instructions along with sample run among the comments at the start of the FORTRAN 2008 source. This program acquires input from the command line argument, thereby demonstrating the fairly new get_command_argument intrinsic subroutine. The expression of the algorithm is a rough translated of the j solution. Thank you.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 21:43:12
!Compilation started at Tue May 21 21:43:12
Line 1,116: Line 1,116:


end program shannonEntropy
end program shannonEntropy
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang FreeBASIC>' version 25-06-2015
<syntaxhighlight lang="freebasic">' version 25-06-2015
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,152: Line 1,152:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>Char count
<pre>Char count
Line 1,165: Line 1,165:
Sort of hacky, but friendly interactive shell isn't really optimized for mathematic tasks (in fact, it doesn't even have associative arrays).
Sort of hacky, but friendly interactive shell isn't really optimized for mathematic tasks (in fact, it doesn't even have associative arrays).


<lang fishshell>function entropy
<syntaxhighlight lang="fishshell">function entropy
for arg in $argv
for arg in $argv
set name count_$arg
set name count_$arg
Line 1,185: Line 1,185:
echo "$entropy / l(2)" | bc -l
echo "$entropy / l(2)" | bc -l
end
end
entropy (echo 1223334444 | fold -w1)</lang>
entropy (echo 1223334444 | fold -w1)</syntaxhighlight>
{{out}}
{{out}}
<pre>1.84643934467101549345</pre>
<pre>1.84643934467101549345</pre>
Line 1,199: Line 1,199:
=={{header|Go}}==
=={{header|Go}}==
===Go: Slice version===
===Go: Slice version===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,222: Line 1,222:
}
}
return entropy
return entropy
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,229: Line 1,229:


===Go: Map version===
===Go: Map version===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,249: Line 1,249:
const l = float64(len(s))
const l = float64(len(s))
fmt.Println(math.Log2(l) - hm/l)
fmt.Println(math.Log2(l) - hm/l)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,256: Line 1,256:


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>String.metaClass.getShannonEntrophy = {
<syntaxhighlight lang="groovy">String.metaClass.getShannonEntrophy = {
-delegate.inject([:]) { map, v -> map[v] = (map[v] ?: 0) + 1; map }.values().inject(0.0) { sum, v ->
-delegate.inject([:]) { map, v -> map[v] = (map[v] ?: 0) + 1; map }.values().inject(0.0) { sum, v ->
def p = (BigDecimal)v / delegate.size()
def p = (BigDecimal)v / delegate.size()
sum + p * Math.log(p) / Math.log(2)
sum + p * Math.log(p) / Math.log(2)
}
}
}</lang>
}</syntaxhighlight>
Testing
Testing
<lang groovy>[ '1223334444': '1.846439344671',
<syntaxhighlight lang="groovy">[ '1223334444': '1.846439344671',
'1223334444555555555': '1.969811065121',
'1223334444555555555': '1.969811065121',
'122333': '1.459147917061',
'122333': '1.459147917061',
Line 1,273: Line 1,273:
println "Checking $s has a shannon entrophy of $expected"
println "Checking $s has a shannon entrophy of $expected"
assert sprintf('%.12f', s.shannonEntrophy) == expected
assert sprintf('%.12f', s.shannonEntrophy) == expected
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Checking 1223334444 has a shannon entrophy of 1.846439344671
<pre>Checking 1223334444 has a shannon entrophy of 1.846439344671
Line 1,284: Line 1,284:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List
<syntaxhighlight lang="haskell">import Data.List


main = print $ entropy "1223334444"
main = print $ entropy "1223334444"
Line 1,291: Line 1,291:
entropy = sum . map lg . fq . map genericLength . group . sort
entropy = sum . map lg . fq . map genericLength . group . sort
where lg c = -c * logBase 2 c
where lg c = -c * logBase 2 c
fq c = let sc = sum c in map (/ sc) c</lang>
fq c = let sc = sum c in map (/ sc) c</syntaxhighlight>




Or, inlining with an applicative expression (turns out to be fractionally faster):
Or, inlining with an applicative expression (turns out to be fractionally faster):


<lang haskell>import Data.List (genericLength, group, sort)
<syntaxhighlight lang="haskell">import Data.List (genericLength, group, sort)


entropy
entropy
Line 1,307: Line 1,307:


main :: IO ()
main :: IO ()
main = print $ entropy "1223334444"</lang>
main = print $ entropy "1223334444"</syntaxhighlight>


{{out}}
{{out}}
Line 1,321: Line 1,321:
description.
description.


<lang unicon>procedure main(a)
<syntaxhighlight lang="unicon">procedure main(a)
s := !a | "1223334444"
s := !a | "1223334444"
write(H(s))
write(H(s))
Line 1,331: Line 1,331:
every (h := 0.0) -:= P[c := key(P)] * log(P[c],2)
every (h := 0.0) -:= P[c := key(P)] * log(P[c],2)
return h
return h
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,341: Line 1,341:


=={{header|J}}==
=={{header|J}}==
'''Solution''':<lang j> entropy=: +/@(-@* 2&^.)@(#/.~ % #)</lang>
'''Solution''':<syntaxhighlight lang="j"> entropy=: +/@(-@* 2&^.)@(#/.~ % #)</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<lang j> entropy '1223334444'
<syntaxhighlight lang="j"> entropy '1223334444'
1.84644
1.84644
entropy i.256
entropy i.256
Line 1,352: Line 1,352:
1
1
entropy 256$0 1 2 3
entropy 256$0 1 2 3
2</lang>
2</syntaxhighlight>


So it looks like entropy is roughly the number of bits which would be needed to ''distinguish between'' each item in the argument (for example, with perfect compression). Note that in some contexts this might not be the same thing as information because the choice of the items themselves might matter. But it's good enough in contexts with a fixed set of symbols.
So it looks like entropy is roughly the number of bits which would be needed to ''distinguish between'' each item in the argument (for example, with perfect compression). Note that in some contexts this might not be the same thing as information because the choice of the items themselves might matter. But it's good enough in contexts with a fixed set of symbols.
Line 1,360: Line 1,360:
{{trans|REXX}}
{{trans|REXX}}
{{works with|Java|7+}}
{{works with|Java|7+}}
<lang java5>import java.lang.Math;
<syntaxhighlight lang="java5">import java.lang.Math;
import java.util.Map;
import java.util.Map;
import java.util.HashMap;
import java.util.HashMap;
Line 1,410: Line 1,410:
return;
return;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,425: Line 1,425:
{{works with|ECMAScript 2015}}
{{works with|ECMAScript 2015}}
Calculate the entropy of a string by determining the frequency of each character, then summing each character's probability multiplied by the log base 2 of that same probability, taking the negative of the sum.
Calculate the entropy of a string by determining the frequency of each character, then summing each character's probability multiplied by the log base 2 of that same probability, taking the negative of the sum.
<lang JavaScript>// Shannon entropy in bits per symbol.
<syntaxhighlight lang="javascript">// Shannon entropy in bits per symbol.
function entropy(str) {
function entropy(str) {
const len = str.length
const len = str.length
Line 1,443: Line 1,443:
console.log(entropy('0123')) // 2
console.log(entropy('0123')) // 2
console.log(entropy('01234567')) // 3
console.log(entropy('01234567')) // 3
console.log(entropy('0123456789abcdef')) // 4</lang>
console.log(entropy('0123456789abcdef')) // 4</syntaxhighlight>
{{out}}
{{out}}
<pre>1.8464393446710154
<pre>1.8464393446710154
Line 1,451: Line 1,451:
3
3
4</pre> =={{header|JavaScript}}==
4</pre> =={{header|JavaScript}}==
<lang JavaScript>const entropy = (s) => {
<syntaxhighlight lang="javascript">const entropy = (s) => {
const split = s.split('');
const split = s.split('');
const counter = {};
const counter = {};
Line 1,465: Line 1,465:
.map(count => count / lengthf * Math.log2(count / lengthf))
.map(count => count / lengthf * Math.log2(count / lengthf))
.reduce((a, b) => a + b);
.reduce((a, b) => a + b);
};</lang>
};</syntaxhighlight>
{{out}}
{{out}}
<pre>console.log(entropy("1223334444")); // 1.8464393446710154</pre>
<pre>console.log(entropy("1223334444")); // 1.8464393446710154</pre>
Line 1,475: Line 1,475:
The helper function, ''counter'', could be defined as an inner function of ''entropy'', but for the sake of clarity and because it is independently useful,
The helper function, ''counter'', could be defined as an inner function of ''entropy'', but for the sake of clarity and because it is independently useful,
it is defined separately.
it is defined separately.
<lang jq># Input: an array of strings.
<syntaxhighlight lang="jq"># Input: an array of strings.
# Output: an object with the strings as keys, the values of which are the corresponding frequencies.
# Output: an object with the strings as keys, the values of which are the corresponding frequencies.
def counter:
def counter:
Line 1,484: Line 1,484:
(explode | map( [.] | implode ) | counter
(explode | map( [.] | implode ) | counter
| [ .[] | . * log ] | add) as $sum
| [ .[] | . * log ] | add) as $sum
| ((length|log) - ($sum / length)) / (2|log) ;</lang>
| ((length|log) - ($sum / length)) / (2|log) ;</syntaxhighlight>


{{out|Example}}
{{out|Example}}
<lang jq>"1223334444" | entropy # => 1.8464393446710154</lang>
<syntaxhighlight lang="jq">"1223334444" | entropy # => 1.8464393446710154</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript entry.
From Javascript entry.
<lang javascript>/* Shannon entropy, in Jsish */
<syntaxhighlight lang="javascript">/* Shannon entropy, in Jsish */


function values(obj:object):array {
function values(obj:object):array {
Line 1,520: Line 1,520:
; entropy('Rosetta Code');
; entropy('Rosetta Code');
; entropy('password');
; entropy('password');
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,531: Line 1,531:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>entropy(s) = -sum(x -> x * log(2, x), count(x -> x == c, s) / length(s) for c in unique(s))
<syntaxhighlight lang="julia">entropy(s) = -sum(x -> x * log(2, x), count(x -> x == c, s) / length(s) for c in unique(s))
@show entropy("1223334444")
@show entropy("1223334444")
@show entropy([1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 3, 4, 5])</lang>
@show entropy([1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 3, 4, 5])</syntaxhighlight>


{{out}}
{{out}}
Line 1,540: Line 1,540:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun log2(d: Double) = Math.log(d) / Math.log(2.0)
fun log2(d: Double) = Math.log(d) / Math.log(2.0)
Line 1,572: Line 1,572:
println("------------------------------------ ------------------")
println("------------------------------------ ------------------")
for (sample in samples) println("${sample.padEnd(36)} -> ${"%18.16f".format(shannon(sample))}")
for (sample in samples) println("${sample.padEnd(36)} -> ${"%18.16f".format(shannon(sample))}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,588: Line 1,588:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def entropy
{def entropy


Line 1,639: Line 1,639:
-> 4.70043971814109
-> 4.70043971814109


</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: -rot rot rot ; [] '__A set : dip swap __A swap 1 compress append '__A
<syntaxhighlight lang="lang5">: -rot rot rot ; [] '__A set : dip swap __A swap 1 compress append '__A
set execute __A -1 extract nip ; : nip swap drop ; : sum '+ reduce ;
set execute __A -1 extract nip ; : nip swap drop ; : sum '+ reduce ;
: 2array 2 compress ; : comb "" split ; : lensize length nip ;
: 2array 2 compress ; : comb "" split ; : lensize length nip ;
Line 1,658: Line 1,658:
dup neg swap log * 2 log / sum ;
dup neg swap log * 2 log / sum ;


"1223334444" comb entropy . # 1.84643934467102</lang>
"1223334444" comb entropy . # 1.84643934467102</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim countOfChar( 255) ' all possible one-byte ASCII chars
dim countOfChar( 255) ' all possible one-byte ASCII chars


Line 1,694: Line 1,694:
logBase =log( x) /log( 2)
logBase =log( x) /log( 2)
end function
end function
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre> Characters used and the number of occurrences of each
<pre> Characters used and the number of occurrences of each
Line 1,705: Line 1,705:


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function log2 (x) return math.log(x) / math.log(2) end
<syntaxhighlight lang="lua">function log2 (x) return math.log(x) / math.log(2) end


function entropy (X)
function entropy (X)
Line 1,723: Line 1,723:
end
end


print(entropy("1223334444"))</lang>
print(entropy("1223334444"))</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>shE[s_String] := -Plus @@ ((# Log[2., #]) & /@ ((Length /@ Gather[#])/
<syntaxhighlight lang="mathematica">shE[s_String] := -Plus @@ ((# Log[2., #]) & /@ ((Length /@ Gather[#])/
Length[#]) &[Characters[s]])</lang>
Length[#]) &[Characters[s]])</syntaxhighlight>
{{out|Example}}<lang Mathematica> shE["1223334444"]
{{out|Example}}<syntaxhighlight lang="mathematica"> shE["1223334444"]
1.84644
1.84644
shE["Rosetta Code"]
shE["Rosetta Code"]
3.08496</lang>
3.08496</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
This version allows for any input vectors,
This version allows for any input vectors,
including strings, floats, negative integers, etc.
including strings, floats, negative integers, etc.
<lang MATLAB>function E = entropy(d)
<syntaxhighlight lang="matlab">function E = entropy(d)
if ischar(d), d=abs(d); end;
if ischar(d), d=abs(d); end;
[Y,I,J] = unique(d);
[Y,I,J] = unique(d);
Line 1,742: Line 1,742:
p = full(H(H>0))/length(d);
p = full(H(H>0))/length(d);
E = -sum(p.*log2(p));
E = -sum(p.*log2(p));
end; </lang>
end; </syntaxhighlight>
{{out|Usage}}
{{out|Usage}}
<lang MATLAB>> entropy('1223334444')
<syntaxhighlight lang="matlab">> entropy('1223334444')
ans = 1.8464</lang>
ans = 1.8464</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>entropy = function(s)
<syntaxhighlight lang="miniscript">entropy = function(s)
count = {}
count = {}
for c in s
for c in s
Line 1,761: Line 1,761:
end function
end function


print entropy("1223334444")</lang>
print entropy("1223334444")</syntaxhighlight>


{{out}}
{{out}}
Line 1,767: Line 1,767:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE Entropy;
<syntaxhighlight lang="modula2">MODULE Entropy;
FROM InOut IMPORT WriteString, WriteLn;
FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;
FROM RealInOut IMPORT WriteReal;
Line 1,802: Line 1,802:
WriteReal(entropy("1223334444"), 14);
WriteReal(entropy("1223334444"), 14);
WriteLn;
WriteLn;
END Entropy.</lang>
END Entropy.</syntaxhighlight>
{{out}}
{{out}}
<pre> 1.8464394E+00</pre>
<pre> 1.8464394E+00</pre>
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|REXX}}
{{trans|REXX}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols
options replace format comments java crossref savelog symbols


Line 1,880: Line 1,880:
end report
end report
return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,896: Line 1,896:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import tables, math
<syntaxhighlight lang="nim">import tables, math


proc entropy(s: string): float =
proc entropy(s: string): float =
Line 1,903: Line 1,903:
for x in t.values: result -= x/s.len * log2(x/s.len)
for x in t.values: result -= x/s.len * log2(x/s.len)


echo entropy("1223334444")</lang>
echo entropy("1223334444")</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==


<lang objeck>use Collection;
<syntaxhighlight lang="objeck">use Collection;


class Entropy {
class Entropy {
Line 1,954: Line 1,954:
};
};
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,968: Line 1,968:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>(* generic OCaml, using a mutable Hashtbl *)
<syntaxhighlight lang="ocaml">(* generic OCaml, using a mutable Hashtbl *)


(* pre-bake & return an inner-loop function to bin & assemble a character frequency map *)
(* pre-bake & return an inner-loop function to bin & assemble a character frequency map *)
Line 1,998: Line 1,998:


-1.0 *. List.fold_left (fun b x -> b +. calc x) 0.0 relative_probs
-1.0 *. List.fold_left (fun b x -> b +. calc x) 0.0 relative_probs
</syntaxhighlight>
</lang>


'''output:'''
'''output:'''
Line 2,006: Line 2,006:
=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: entropy(s) -- f
<syntaxhighlight lang="oforth">: entropy(s) -- f
| freq sz |
| freq sz |
s size dup ifZero: [ return ] asFloat ->sz
s size dup ifZero: [ return ] asFloat ->sz
Line 2,013: Line 2,013:
0.0 freq applyIf( #[ 0 <> ], #[ sz / dup ln * - ] ) Ln2 / ;
0.0 freq applyIf( #[ 0 <> ], #[ sz / dup ln * - ] ) Ln2 / ;
entropy("1223334444") .</lang>
entropy("1223334444") .</syntaxhighlight>


{{out}}
{{out}}
Line 2,020: Line 2,020:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
{{trans|REXX}}
{{trans|REXX}}
<lang oorexx>/* REXX */
<syntaxhighlight lang="oorexx">/* REXX */
Numeric Digits 16
Numeric Digits 16
Parse Arg s
Parse Arg s
Line 2,051: Line 2,051:
Exit
Exit


::requires 'rxmath' LIBRARY </lang>
::requires 'rxmath' LIBRARY </syntaxhighlight>
{{out}}
{{out}}
<pre>1223334444 Entropy 1.846439344671</pre>
<pre>1223334444 Entropy 1.846439344671</pre>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>entropy(s)=s=Vec(s);my(v=vecsort(s,,8));-sum(i=1,#v,(x->x*log(x))(sum(j=1,#s,v[i]==s[j])/#s))/log(2)</lang>
<syntaxhighlight lang="parigp">entropy(s)=s=Vec(s);my(v=vecsort(s,,8));-sum(i=1,#v,(x->x*log(x))(sum(j=1,#s,v[i]==s[j])/#s))/log(2)</syntaxhighlight>
<pre>>entropy("1223334444")
<pre>>entropy("1223334444")
%1 = 1.8464393446710154934341977463050452232</pre>
%1 = 1.8464393446710154934341977463050452232</pre>
Line 2,064: Line 2,064:
Free Pascal (http://freepascal.org).
Free Pascal (http://freepascal.org).


<syntaxhighlight lang="pascal">
<lang Pascal>
PROGRAM entropytest;
PROGRAM entropytest;


Line 2,115: Line 2,115:
Writeln('Entropy of "',strng,'" is ',entropy(strng):2:5, ' bits.');
Writeln('Entropy of "',strng,'" is ',entropy(strng):2:5, ' bits.');
END.
END.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,123: Line 2,123:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>sub entropy {
<syntaxhighlight lang="perl">sub entropy {
my %count; $count{$_}++ for @_;
my %count; $count{$_}++ for @_;
my $entropy = 0;
my $entropy = 0;
Line 2,133: Line 2,133:
}
}
print entropy split //, "1223334444";</lang>
print entropy split //, "1223334444";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">entropy</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">entropy</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 2,162: Line 2,162:
<span style="color: #0000FF;">?</span><span style="color: #000000;">entropy</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1223334444"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">entropy</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1223334444"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,170: Line 2,170:
=={{header|PHP}}==
=={{header|PHP}}==


<lang PHP><?php
<syntaxhighlight lang="php"><?php


function shannonEntropy($string) {
function shannonEntropy($string) {
Line 2,196: Line 2,196:
number_format(shannonEntropy($string), 6)
number_format(shannonEntropy($string), 6)
);
);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,207: Line 2,207:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
["1223334444",
["1223334444",
"Rosetta Code is the best site in the world!",
"Rosetta Code is the best site in the world!",
Line 2,221: Line 2,221:
Occ.put(E, Occ.get(E,0) + 1)
Occ.put(E, Occ.get(E,0) + 1)
end,
end,
Entropy = -sum([P2*log2(P2) : _C=P in Occ, P2 = P/Len]).</lang>
Entropy = -sum([P2*log2(P2) : _C=P in Occ, P2 = P/Len]).</syntaxhighlight>


{{out}}
{{out}}
Line 2,228: Line 2,228:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
PicoLisp only supports fixed point arithmetic, but it does have the ability to call libc transcendental functions (for log)
PicoLisp only supports fixed point arithmetic, but it does have the ability to call libc transcendental functions (for log)
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(scl 8)
(scl 8)
(load "@lib/math.l")
(load "@lib/math.l")
Line 2,255: Line 2,255:
1. LN2)))
1. LN2)))


</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,263: Line 2,263:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>*process source xref attributes or(!);
<syntaxhighlight lang="pli">*process source xref attributes or(!);
/*--------------------------------------------------------------------
/*--------------------------------------------------------------------
* 08.08.2014 Walter Pachl translated from REXX version 1
* 08.08.2014 Walter Pachl translated from REXX version 1
Line 2,296: Line 2,296:
End;
End;
Put Edit('s='''!!s!!''' Entropy=',-e)(Skip,a,f(15,12));
Put Edit('s='''!!s!!''' Entropy=',-e)(Skip,a,f(15,12));
End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>s='1223334444' Entropy= 1.846439344671</pre>
<pre>s='1223334444' Entropy= 1.846439344671</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function entropy ($string) {
function entropy ($string) {
$n = $string.Length
$n = $string.Length
Line 2,311: Line 2,311:
}
}
entropy "1223334444"
entropy "1223334444"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,323: Line 2,323:
This solution calculates the run-length encoding of the input string to get the relative frequencies of its characters.
This solution calculates the run-length encoding of the input string to get the relative frequencies of its characters.


<lang Prolog>:-module(shannon_entropy, [shannon_entropy/2]).
<syntaxhighlight lang="prolog">:-module(shannon_entropy, [shannon_entropy/2]).


%! shannon_entropy(+String, -Entropy) is det.
%! shannon_entropy(+String, -Entropy) is det.
Line 2,454: Line 2,454:
,must_be(number, B)
,must_be(number, B)
,Sum is A + B.
,Sum is A + B.
</syntaxhighlight>
</lang>


Example query:
Example query:
Line 2,464: Line 2,464:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>#TESTSTR="1223334444"
<syntaxhighlight lang="purebasic">#TESTSTR="1223334444"
NewMap uchar.i() : Define.d e
NewMap uchar.i() : Define.d e


Line 2,485: Line 2,485:
OpenConsole()
OpenConsole()
Print("Entropy of ["+#TESTSTR+"] = "+StrD(e,15))
Print("Entropy of ["+#TESTSTR+"] = "+StrD(e,15))
Input()</lang>
Input()</syntaxhighlight>
{{out}}
{{out}}
<pre>Entropy of [1223334444] = 1.846439344671015</pre>
<pre>Entropy of [1223334444] = 1.846439344671015</pre>
Line 2,491: Line 2,491:
=={{header|Python}}==
=={{header|Python}}==
===Python: Longer version===
===Python: Longer version===
<lang python>from __future__ import division
<syntaxhighlight lang="python">from __future__ import division
import math
import math


Line 2,524: Line 2,524:
print 'Length',l
print 'Length',l
print 'Entropy:', entropy(h, l)
print 'Entropy:', entropy(h, l)
printHist(h)</lang>
printHist(h)</syntaxhighlight>


{{out}}
{{out}}
Line 2,542: Line 2,542:
The <tt>Counter</tt> module is only available in Python >= 2.7.
The <tt>Counter</tt> module is only available in Python >= 2.7.


<lang python>>>> import math
<syntaxhighlight lang="python">>>> import math
>>> from collections import Counter
>>> from collections import Counter
>>>
>>>
Line 2,551: Line 2,551:
>>> entropy("1223334444")
>>> entropy("1223334444")
1.8464393446710154
1.8464393446710154
>>> </lang>
>>> </syntaxhighlight>


===Uses Python 2===
===Uses Python 2===
<lang python>def Entropy(text):
<syntaxhighlight lang="python">def Entropy(text):
import math
import math
log2=lambda x:math.log(x)/math.log(2)
log2=lambda x:math.log(x)/math.log(2)
Line 2,572: Line 2,572:


while True:
while True:
print Entropy(raw_input('>>>'))</lang>
print Entropy(raw_input('>>>'))</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==


<lang rsplus>
<syntaxhighlight lang="rsplus">
entropy <- function(str) {
entropy <- function(str) {
vec <- strsplit(str, "")[[1]]
vec <- strsplit(str, "")[[1]]
Line 2,584: Line 2,584:
-sum(p_xi * log(p_xi, 2))
-sum(p_xi * log(p_xi, 2))
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,593: Line 2,593:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(require math)
(require math)
(provide entropy hash-entropy list-entropy digital-entropy)
(provide entropy hash-entropy list-entropy digital-entropy)
Line 2,615: Line 2,615:
(check-= (entropy "xggooopppp") 1.8464393446710154 1E-8))
(check-= (entropy "xggooopppp") 1.8464393446710154 1E-8))


(module+ main (entropy "1223334444"))</lang>
(module+ main (entropy "1223334444"))</syntaxhighlight>
{{out}}
{{out}}
<pre> 1.8464393446710154</pre>
<pre> 1.8464393446710154</pre>
Line 2,622: Line 2,622:
(formerly Perl 6)
(formerly Perl 6)
{{works with|rakudo|2015-09-09}}
{{works with|rakudo|2015-09-09}}
<lang perl6>sub entropy(@a) {
<syntaxhighlight lang="raku" line>sub entropy(@a) {
[+] map -> \p { p * -log p }, bag(@a).values »/» +@a;
[+] map -> \p { p * -log p }, bag(@a).values »/» +@a;
}
}


say log(2) R/ entropy '1223334444'.comb;</lang>
say log(2) R/ entropy '1223334444'.comb;</syntaxhighlight>
{{out}}
{{out}}
<pre>1.84643934467102</pre>
<pre>1.84643934467102</pre>
Line 2,632: Line 2,632:
In case we would like to add this function to Raku's core, here is one way it could be done:
In case we would like to add this function to Raku's core, here is one way it could be done:


<lang perl6>use MONKEY-TYPING;
<syntaxhighlight lang="raku" line>use MONKEY-TYPING;
augment class Bag {
augment class Bag {
method entropy {
method entropy {
Line 2,640: Line 2,640:
}
}


say '1223334444'.comb.Bag.entropy / log 2;</lang>
say '1223334444'.comb.Bag.entropy / log 2;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===


<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* 28.02.2013 Walter Pachl
* 28.02.2013 Walter Pachl
* 12.03.2013 Walter Pachl typo in log corrected. thanx for testing
* 12.03.2013 Walter Pachl typo in log corrected. thanx for testing
Line 2,744: Line 2,744:
Numeric Digits (prec)
Numeric Digits (prec)
r=r+0
r=r+0
Return r </lang>
Return r </syntaxhighlight>


<!-- these types of comparisons are not part of this Rosetta Code task, and
<!-- these types of comparisons are not part of this Rosetta Code task, and
Line 2,750: Line 2,750:




<lang rexx>/* REXX ***************************************************************
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* Test program to compare Versions 1 and 2
* Test program to compare Versions 1 and 2
* (the latter tweaked to be acceptable by my (oo)Rexx
* (the latter tweaked to be acceptable by my (oo)Rexx
Line 2,773: Line 2,773:
Say ' '
Say ' '
Return
Return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Version 1: 1223334444 Entropy 1.846439344671
<pre>Version 1: 1223334444 Entropy 1.846439344671
Line 2,794: Line 2,794:


The &nbsp; '''LOG2''' &nbsp; subroutine is only included here for functionality, not to document how to calculate &nbsp; LOG<sub>2</sub> &nbsp; using REXX.
The &nbsp; '''LOG2''' &nbsp; subroutine is only included here for functionality, not to document how to calculate &nbsp; LOG<sub>2</sub> &nbsp; using REXX.
<lang rexx>/*REXX program calculates the information entropy for a specified character string. */
<syntaxhighlight lang="rexx">/*REXX program calculates the information entropy for a specified character string. */
numeric digits length( e() ) % 2 - length(.) /*use 1/2 of the decimal digits of E. */
numeric digits length( e() ) % 2 - length(.) /*use 1/2 of the decimal digits of E. */
parse arg $; if $='' then $= 1223334444 /*obtain the optional input from the CL*/
parse arg $; if $='' then $= 1223334444 /*obtain the optional input from the CL*/
Line 2,823: Line 2,823:
ox=izz; ii=ii+is*2**j; end /*while*/; x= x * e** -ii -1; z= 0; _= -1; p= z
ox=izz; ii=ii+is*2**j; end /*while*/; x= x * e** -ii -1; z= 0; _= -1; p= z
do k=1; _= -_ * x; z= z+_/k; if z=p then leave; p= z; end /*k*/
do k=1; _= -_ * x; z= z+_/k; if z=p then leave; p= z; end /*k*/
r= z + ii; if arg()==2 then return r; return r / log2(2, .)</lang>
r= z + ii; if arg()==2 then return r; return r / log2(2, .)</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 1223334444 </tt>}}
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 1223334444 </tt>}}
<pre>
<pre>
Line 2,842: Line 2,842:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
decimals(8)
decimals(8)
entropy = 0
entropy = 0
Line 2,875: Line 2,875:
logBase =log( x) /log( 2)
logBase =log( x) /log( 2)
return logBase
return logBase
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,889: Line 2,889:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9}}
{{works with|Ruby|1.9}}
<lang ruby>def entropy(s)
<syntaxhighlight lang="ruby">def entropy(s)
counts = Hash.new(0.0)
counts = Hash.new(0.0)
s.each_char { |c| counts[c] += 1 }
s.each_char { |c| counts[c] += 1 }
Line 2,900: Line 2,900:
end
end


p entropy("1223334444")</lang>
p entropy("1223334444")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,906: Line 2,906:
</pre>
</pre>
One-liner, same performance (or better):
One-liner, same performance (or better):
<lang ruby>def entropy2(s)
<syntaxhighlight lang="ruby">def entropy2(s)
s.each_char.group_by(&:to_s).values.map { |x| x.length / s.length.to_f }.reduce(0) { |e, x| e - x*Math.log2(x) }
s.each_char.group_by(&:to_s).values.map { |x| x.length / s.length.to_f }.reduce(0) { |e, x| e - x*Math.log2(x) }
end</lang>
end</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>dim chrCnt( 255) ' possible ASCII chars
<syntaxhighlight lang="runbasic">dim chrCnt( 255) ' possible ASCII chars


source$ = "1223334444"
source$ = "1223334444"
Line 2,936: Line 2,936:
print " Entropy of '"; source$; "' is "; entropy; " bits."
print " Entropy of '"; source$; "' is "; entropy; " bits."


end</lang><pre>
end</syntaxhighlight><pre>
Characters used and times used of each
Characters used and times used of each
'1' 1
'1' 1
Line 2,946: Line 2,946:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn entropy(s: &[u8]) -> f32 {
<syntaxhighlight lang="rust">fn entropy(s: &[u8]) -> f32 {
let mut histogram = [0u64; 256];
let mut histogram = [0u64; 256];


Line 2,965: Line 2,965:
let arg = std::env::args().nth(1).expect("Need a string.");
let arg = std::env::args().nth(1).expect("Need a string.");
println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes()));
println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes()));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ./entropy 1223334444
<pre>$ ./entropy 1223334444
Line 2,972: Line 2,972:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import scala.math._
<syntaxhighlight lang="scala">import scala.math._


def entropy( v:String ) = { v
def entropy( v:String ) = { v
Line 2,983: Line 2,983:


// Confirm that "1223334444" has an entropy of about 1.84644
// Confirm that "1223334444" has an entropy of about 1.84644
assert( math.round( entropy("1223334444") * 100000 ) * 0.00001 == 1.84644 )</lang>
assert( math.round( entropy("1223334444") * 100000 ) * 0.00001 == 1.84644 )</syntaxhighlight>


=={{header|scheme}}==
=={{header|scheme}}==
A version capable of calculating multidimensional entropy.
A version capable of calculating multidimensional entropy.
<lang scheme>
<syntaxhighlight lang="scheme">
(define (entropy input)
(define (entropy input)
(define (close? a b)
(define (close? a b)
Line 3,030: Line 3,030:
(entropy (list 1 2 2 3 3 3 4 4 4 4))
(entropy (list 1 2 2 3 3 3 4 4 4 4))
(entropy (list (list 1 1) (list 1.1 1.1) (list 1.2 1.2) (list 1.3 1.3) (list 1.5 1.5) (list 1.6 1.6)))
(entropy (list (list 1 1) (list 1.1 1.1) (list 1.2 1.2) (list 1.3 1.3) (list 1.5 1.5) (list 1.6 1.6)))
</lang>
</syntaxhighlight>


{{out}}
{{out}}
Line 3,040: Line 3,040:


=={{header|Scilab}}==
=={{header|Scilab}}==
<lang>function E = entropy(d)
<syntaxhighlight lang="text">function E = entropy(d)
d=strsplit(d);
d=strsplit(d);
n=unique(string(d));
n=unique(string(d));
Line 3,059: Line 3,059:
word ='1223334444';
word ='1223334444';
E = entropy(word);
E = entropy(word);
disp('The entropy of '+word+' is '+string(E)+'.');</lang>
disp('The entropy of '+word+' is '+string(E)+'.');</syntaxhighlight>


{{out}}
{{out}}
Line 3,065: Line 3,065:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
include "math.s7i";
include "math.s7i";
Line 3,093: Line 3,093:
begin
begin
writeln(entropy("1223334444") digits 5);
writeln(entropy("1223334444") digits 5);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,101: Line 3,101:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func entropy(s) {
<syntaxhighlight lang="ruby">func entropy(s) {
var counts = Hash.new;
var counts = Hash.new;
s.each { |c| counts{c} := 0 ++ };
s.each { |c| counts{c} := 0 ++ };
Line 3,110: Line 3,110:
}
}
 
 
say entropy("1223334444");</lang>
say entropy("1223334444");</syntaxhighlight>
{{out}}
{{out}}
<pre>1.846439344671015493434197746305045223237</pre>
<pre>1.846439344671015493434197746305045223237</pre>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang Standard ML>val Entropy = fn input =>
<syntaxhighlight lang="standard ml">val Entropy = fn input =>
let
let
val N = Real.fromInt (String.size input) ;
val N = Real.fromInt (String.size input) ;
Line 3,126: Line 3,126:
~ (Vector.foldr (fn (a,s) => if a > 0.0 then term a + s else s) 0.0 freq )
~ (Vector.foldr (fn (a,s) => if a > 0.0 then term a + s else s) 0.0 freq )


end ;</lang>
end ;</syntaxhighlight>
Entropy "1223334444" ;
Entropy "1223334444" ;
val it = 1.846439345: real
val it = 1.846439345: real
=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


func entropy(of x: String) -> Double {
func entropy(of x: String) -> Double {
Line 3,144: Line 3,144:
}
}


print(entropy(of: "1223334444"))</lang>
print(entropy(of: "1223334444"))</syntaxhighlight>


{{out}}
{{out}}
Line 3,150: Line 3,150:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc entropy {str} {
<syntaxhighlight lang="tcl">proc entropy {str} {
set log2 [expr log(2)]
set log2 [expr log(2)]
foreach char [split $str ""] {dict incr counts $char}
foreach char [split $str ""] {dict incr counts $char}
Line 3,159: Line 3,159:
}
}
return $entropy
return $entropy
}</lang>
}</syntaxhighlight>
Demonstration:
Demonstration:
<lang tcl>puts [format "entropy = %.5f" [entropy "1223334444"]]
<syntaxhighlight lang="tcl">puts [format "entropy = %.5f" [entropy "1223334444"]]
puts [format "entropy = %.5f" [entropy "Rosetta Code"]]</lang>
puts [format "entropy = %.5f" [entropy "Rosetta Code"]]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,172: Line 3,172:


===Vlang: Map version===
===Vlang: Map version===
<lang vlang>import math
<syntaxhighlight lang="vlang">import math
import arrays
import arrays


Line 3,200: Line 3,200:
e := entropy(h, input.len)
e := entropy(h, input.len)
println(e)
println(e)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,208: Line 3,208:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Go}}
{{trans|Go}}
<lang ecmascript>var s = "1223334444"
<syntaxhighlight lang="ecmascript">var s = "1223334444"
var m = {}
var m = {}
for (c in s) {
for (c in s) {
Line 3,220: Line 3,220:
}
}
var l = s.count
var l = s.count
System.print(l.log2 - hm/l)</lang>
System.print(l.log2 - hm/l)</syntaxhighlight>


{{out}}
{{out}}
Line 3,228: Line 3,228:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code real RlOut=48, Ln=54; \intrinsic routines
<syntaxhighlight lang="xpl0">code real RlOut=48, Ln=54; \intrinsic routines
string 0; \use zero-terminated strings
string 0; \use zero-terminated strings


Line 3,254: Line 3,254:
];
];


RlOut(0, Entropy("1223334444"))</lang>
RlOut(0, Entropy("1223334444"))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,261: Line 3,261:


=={{header|Zig}}==
=={{header|Zig}}==
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const std = @import("std");
const math = std.math;
const math = std.math;
Line 3,284: Line 3,284:
return h;
return h;
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,292: Line 3,292:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|D}}
{{trans|D}}
<lang zkl>fcn entropy(text){
<syntaxhighlight lang="zkl">fcn entropy(text){
text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]+=1; freq }
text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]+=1; freq }
.fp1( (0).pump(256,List,0.0).copy() )) // array[256] of 0.0
.fp1( (0).pump(256,List,0.0).copy() )) // array[256] of 0.0
Line 3,301: Line 3,301:
}
}


entropy("1223334444").println(" bits");</lang>
entropy("1223334444").println(" bits");</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,309: Line 3,309:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang zxbasic>10 LET s$="1223334444": LET base=2: LET entropy=0
<syntaxhighlight lang="zxbasic">10 LET s$="1223334444": LET base=2: LET entropy=0
20 LET sourcelen=LEN s$
20 LET sourcelen=LEN s$
30 DIM t(255)
30 DIM t(255)
Line 3,320: Line 3,320:
100 IF t(i)<>0 THEN PRINT CHR$ i;TAB (6);t(i): LET prop=t(i)/sourcelen: LET entropy=entropy-(prop*(LN prop)/(LN base))
100 IF t(i)<>0 THEN PRINT CHR$ i;TAB (6);t(i): LET prop=t(i)/sourcelen: LET entropy=entropy-(prop*(LN prop)/(LN base))
110 NEXT i
110 NEXT i
120 PRINT '"The Entropy of """;s$;""" is ";entropy</lang>
120 PRINT '"The Entropy of """;s$;""" is ";entropy</syntaxhighlight>