Diversity prediction theorem: Difference between revisions

Added Easylang
m (→‎{{header|R}}: Syntax highlighting.)
(Added Easylang)
 
(23 intermediate revisions by 13 users not shown)
Line 43:
=={{header|11l}}==
{{trans|C++}}
<langsyntaxhighlight lang="11l">F average_square_diff(a, predictions)
R sum(predictions.map(x -> (x - @a) ^ 2)) / predictions.len
 
Line 53:
 
diversity_theorem(49.0, [Float(48), 47, 51])
diversity_theorem(49.0, [Float(48), 47, 51, 42])</langsyntaxhighlight>
{{out}}
<pre>
Line 63:
diversity: 10.5
</pre>
 
=={{header|Ada}}==
{{trans|C}}
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Command_Line;
 
procedure Diversity_Prediction is
 
type Real is new Float;
type Real_Array is array (Positive range <>) of Real;
 
package Real_IO is new Ada.Text_Io.Float_IO (Real);
use Ada.Text_IO, Ada.Command_Line, Real_IO;
 
function Mean (Data : Real_Array) return Real is
Sum : Real := 0.0;
begin
for V of Data loop
Sum := Sum + V;
end loop;
return Sum / Real (Data'Length);
end Mean;
 
function Variance (Reference : Real; Data : Real_Array) return Real is
Res : Real_Array (Data'Range);
begin
for A in Data'Range loop
Res (A) := (Reference - Data (A)) ** 2;
end loop;
return Mean (Res);
end Variance;
 
procedure Diversity (Truth : Real; Estimates : Real_Array)
is
Average : constant Real := Mean (Estimates);
Average_Error : constant Real := Variance (Truth, Estimates);
Crowd_Error : constant Real := (Truth - Average) ** 2;
Diversity : constant Real := Variance (Average, Estimates);
begin
Real_IO.Default_Exp := 0;
Real_IO.Default_Aft := 5;
Put ("average-error : "); Put (Average_Error); New_Line;
Put ("crowd-error : "); Put (Crowd_Error); New_Line;
Put ("diversity : "); Put (Diversity); New_Line;
end Diversity;
 
begin
if Argument_Count <= 1 then
Put_Line ("Usage: diversity_prediction <truth> <data_1> <data_2> ...");
return;
end if;
 
declare
Truth : constant Real := Real'Value (Argument (1));
Estimates : Real_Array (2 .. Argument_Count);
begin
for A in 2 .. Argument_Count loop
Estimates (A) := Real'Value (Argument (A));
end loop;
 
Diversity (Truth, Estimates);
end;
end Diversity_Prediction;</syntaxhighlight>
{{out}}
<pre>
% ./diversity_prediction 49 48 47 51
average-error : 3.00000
crowd-error : 0.11111
diversity : 2.88889
% ./diversity_prediction 49 48 47 51 42
average-error : 14.50000
crowd-error : 4.00000
diversity : 10.50000
</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Phix}}
<syntaxhighlight lang="algol68">
BEGIN # Diversity Prediction Theorem #
 
# utility operators #
OP LENGTH = ( []REAL a )INT: ( UPB a - LWB a ) + 1;
OP LENGTH = ( STRING a )INT: ( UPB a - LWB a ) + 1;
OP SUM = ( []REAL a )REAL:
BEGIN
REAL result := 0;
FOR i FROM LWB a TO UPB a DO result +:= a[ i ] OD;
result
END # SUM # ;
PRIO PAD = 9;
OP PAD = ( INT width, STRING v )STRING: # left blank pad v to width #
IF LENGTH v >= width THEN v ELSE ( " " * ( width - LENGTH v ) ) + v FI;
OP - = ( []REAL a, REAL v )[]REAL: # return a with elements - v #
BEGIN
[ LWB a : UPB a ]REAL result;
FOR i FROM LWB a TO UPB a DO result[ i ] := v - a[ i ] OD;
result
END # - # ;
OP ^ = ( []REAL a, INT p )[]REAL: # return a with elements raised to p #
BEGIN
[ LWB a : UPB a ]REAL result;
FOR i FROM LWB a TO UPB a DO result[ i ] := a[ i ] ^ p OD;
result
END # |^ # ;
PRIO FMT = 1;
OP FMT = ( REAL v, INT d )STRING: # formats v with up to d decimals #
BEGIN
STRING result := fixed( v, -0, d );
IF result[ LWB result ] = "." THEN "0" +=: result FI;
WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD;
IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI;
" " + result
END # FMT # ;
 
# task #
 
MODE NAMEDVALUE = STRUCT( STRING name, REAL value );
 
PROC mean = ( []REAL s )REAL: SUM s / LENGTH s;
PROC variance = ( []REAL s, REAL d )REAL: mean( ( s - d ) ^ 2 );
PROC diversity theorem = ( REAL reference, []REAL observations )[]NAMEDVALUE:
BEGIN
REAL average = mean( observations );
( ( "average_error", variance( observations, reference ) )
, ( "crowd_error", ( reference - average ) ^ 2 )
, ( "diversity", variance( observations, average ) )
)
END # diversity theorem # ;
PROC test = ( REAL reference, []REAL observations )VOID:
BEGIN
[]NAMEDVALUE res = diversity theorem( reference, observations );
FOR i FROM LWB res TO UPB res DO
print( ( 14 PAD name OF res[ i ], " : ", value OF res[ i ] FMT 6, newline ) )
OD
END # test # ;
 
test( 49, ( 48, 47, 51 ) );
test( 49, ( 48, 47, 51, 42 ) )
 
END
</syntaxhighlight>
{{out}}
<pre>
average_error : 3
crowd_error : 0.111111
diversity : 2.888889
average_error : 14.5
crowd_error : 4
diversity : 10.5
</pre>
 
=={{header|BASIC}}==
==={{header|ANSI BASIC}}===
{{trans|QuickBASIC}}
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">
100 PROGRAM DiversityPredictionTheorem
110 OPTION BASE 0
120 DIM Estimates(1, 4)
130 FOR I = 0 TO 1
140 LET J = 0
150 READ Estimates(I, J)
160 DO WHILE Estimates(I, J) <> 0
170 LET J = J + 1
180 READ Estimates(I, J)
190 LOOP
200 NEXT I
210 DATA 48.0, 47.0, 51.0, 0.0
220 DATA 48.0, 47.0, 51.0, 42.0, 0.0
230 LET TrueVal = 49
240 FOR I = 0 TO 1
250 LET Sum = 0
260 LET J = 0
270 DO WHILE Estimates(I, J) <> 0
280 LET Sum = Sum + (Estimates(I, J) - TrueVal) ^ 2
290 LET J = J + 1
300 LOOP
310 LET AvgErr = Sum / J
320 PRINT USING "Average error : ##.###": AvgErr
330 LET Sum = 0
340 LET J = 0
350 DO WHILE Estimates(I, J) <> 0
360 LET Sum = Sum + Estimates(I, J)
370 LET J = J + 1
380 LOOP
390 LET Avg = Sum / J
400 LET CrowdErr = (TrueVal - Avg) ^ 2
410 PRINT USING "Crowd error : ##.###": CrowdErr
420 PRINT USING "Diversity : ##.###": AvgErr - CrowdErr
430 PRINT
440 NEXT I
450 END
</syntaxhighlight>
{{out}}
<pre>
Average error : 3.000
Crowd error : .111
Diversity : 2.889
 
Average error : 14.500
Crowd error : 4.000
Diversity : 10.500
</pre>
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">dim test = {{48.0, 47.0, 51.0, 0.0}, {48.0, 47.0, 51.0, 42.0, 0.0}}
TrueVal = 49.0
 
for i = 0 to 1
Vari = 0.0
Sum = 0.0
c = 0
while test[i,c] <> 0
Vari += (test[i,c] - TrueVal) ^2
Sum += test[i,c]
c += 1
end while
AvgErr = Vari / c
RefAvg = Sum / c
CrowdErr = (TrueVal - RefAvg) ^2
 
print "Average error : "; AvgErr
print " Crowd error : "; CrowdErr
print " Diversity : "; AvgErr - CrowdErr
print
next i</syntaxhighlight>
 
==={{header|FreeBASIC}}===
{{trans|XPL0}}
<syntaxhighlight lang="vb">Dim As Double test(0 To 1, 0 To 4) => {_
{48.0, 47.0, 51.0}, _
{48.0, 47.0, 51.0, 42.0}}
Dim As Double TrueVal = 49
Dim As Double AvgErr, CrowdErr, RefAvg, Vari, Sum
Dim As Integer i, c
 
For i = 0 To 1
Vari = 0
Sum = 0
c = 0
While test(i,c) <> 0
Vari += (test(i,c) - TrueVal) ^2
Sum += test(i,c)
c += 1
Wend
AvgErr = Vari / c
RefAvg = Sum / c
CrowdErr = (TrueVal - RefAvg) ^2
Print Using "Average error : ###.###"; AvgErr
Print Using " Crowd error : ###.###"; CrowdErr
Print Using " Diversity : ###.###"; AvgErr - CrowdErr
Print
 
Sleep</syntaxhighlight>
{{out}}
<pre>Average error : 3.000
Crowd error : 0.111
Diversity : 2.889
 
Average error : 14.500
Crowd error : 4.000
Diversity : 10.500</pre>
 
==={{header|Nascom BASIC}}===
{{trans|QuickBASIC}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Diversity prediction theorem
20 DIM EST(1,4):REM Estimates
30 FOR I=0 TO 1
40 J=0:READ EST(I,J)
50 IF EST(I,J)=0 THEN 80
60 J=J+1:READ EST(I,J)
70 GOTO 50
80 NEXT I
90 DATA 48.0,47.0,51.0,0.0
100 DATA 48.0,47.0,51.0,42.0,0.0
110 TV=49:REM True value
120 FOR I=0 TO 1
130 SUM=0:J=0
140 IF EST(I,J)=0 THEN 170
150 SUM=SUM+(EST(I,J)-TV)^2:J=J+1
160 GOTO 140
170 AER=SUM/J
180 PRINT "Average error :";AER
190 SUM=0:J=0
200 IF EST(I,J)=0 THEN 230
210 SUM=SUM+EST(I,J):J=J+1
220 GOTO 200
230 AVG=SUM/J
240 CER=(TV-AVG)^2
250 PRINT "Crowd error :";CER
260 PRINT "Diversity :";AER-CER
270 PRINT
280 NEXT I
290 END
</syntaxhighlight>
{{out}}
<pre>
Average error : 3
Crowd error : .11111
Diversity : 2.88889
 
Average error : 14.5
Crowd error : 4
Diversity : 10.5
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Define.f ref=49.0, mea
NewList argV.f()
 
Macro put
Print(~"\n["+StrF(ref)+"]"+#TAB$)
ForEach argV() : Print(StrF(argV())+#TAB$) : Next
PrintN(~"\nAverage Error : "+StrF(vari(argV(),ref),5))
PrintN("Crowd Error : "+StrF((ref-mea)*(ref-mea),5))
PrintN("Diversity : "+StrF(vari(argV(),mea),5))
EndMacro
 
Macro LetArgV(v)
AddElement(argV()) : argV()=v
EndMacro
 
Procedure.f mean(List x.f())
Define.f m
ForEach x() : m+x() : Next
ProcedureReturn m/ListSize(x())
EndProcedure
 
Procedure.f vari(List x.f(),r.f)
NewList nx.f()
ForEach x() : AddElement(nx()) : nx()=(r-x())*(r-x()) : Next
ProcedureReturn mean(nx())
EndProcedure
 
If OpenConsole()=0 : End 1 : EndIf
Gosub SetA : ClearList(argV())
Gosub SetB : Input()
End
 
SetA:
LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0)
mea=mean(argV()) : put
Return
 
SetB:
LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0) : LetArgV(42.0)
mea=mean(argV()) : put
Return</syntaxhighlight>
{{out}}
<pre>[49] 48 47 51
Average Error : 3.00000
Crowd Error : 0.11111
Diversity : 2.88889
 
[49] 48 47 51 42
Average Error : 14.50000
Crowd Error : 4.00000
Diversity : 10.50000</pre>
 
==={{header|QuickBASIC}}===
{{trans|XPL0}}
<syntaxhighlight lang="qbasic">
REM Diversity prediction theorem
DIM Estimates(1, 4)
FOR I% = 0 TO 1
J% = 0
READ Estimates(I%, J%)
WHILE Estimates(I%, J%) <> 0!
J% = J% + 1
READ Estimates(I%, J%)
WEND
NEXT I%
DATA 48.0, 47.0, 51.0, 0.0
DATA 48.0, 47.0, 51.0, 42.0, 0.0
TrueVal = 49!
FOR I% = 0 TO 1
Sum = 0!: J% = 0
WHILE Estimates(I%, J%) <> 0!
Sum = Sum + (Estimates(I%, J%) - TrueVal) ^ 2: J% = J% + 1
WEND
AvgErr = Sum / J%
PRINT USING "Average error : ##.###"; AvgErr
Sum = 0!: J% = 0
WHILE Estimates(I%, J%) <> 0!
Sum = Sum + Estimates(I%, J%): J% = J% + 1
WEND
Avg = Sum / J%
CrowdErr = (TrueVal - Avg) ^ 2
PRINT USING "Crowd error : ##.###"; CrowdErr
PRINT USING "Diversity : ##.###"; AvgErr - CrowdErr
PRINT
NEXT I%
END
</syntaxhighlight>
{{out}}
<pre>
Average error : 3.000
Crowd error : 0.111
Diversity : 2.889
 
Average error : 14.500
Crowd error : 4.000
Diversity : 10.500
 
</pre>
 
==={{header|Visual Basic .NET}}===
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Function Square(x As Double) As Double
Return x * x
End Function
 
Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double
Return predictions.Select(Function(x) Square(x - a)).Average()
End Function
 
Sub DiversityTheorem(truth As Double, predictions As IEnumerable(Of Double))
Dim average = predictions.Average()
Console.WriteLine("average-error: {0}", AverageSquareDiff(truth, predictions))
Console.WriteLine("crowd-error: {0}", Square(truth - average))
Console.WriteLine("diversity: {0}", AverageSquareDiff(average, predictions))
End Sub
 
Sub Main()
DiversityTheorem(49.0, {48.0, 47.0, 51.0})
DiversityTheorem(49.0, {48.0, 47.0, 51.0, 42.0})
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>average-error: 3
crowd-error: 0.111111111111113
diversity: 2.88888888888889
average-error: 14.5
crowd-error: 4
diversity: 10.5</pre>
 
=={{header|C}}==
Accepts inputs from command line, prints out usage on incorrect invocation.
<syntaxhighlight lang="c">
<lang C>
 
#include<string.h>
Line 137 ⟶ 582:
return 0;
}
</syntaxhighlight>
</lang>
Invocation and Output :
<pre>
Line 151 ⟶ 596:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Linq;
Line 174 ⟶ 619:
DiversityTheorem(49, new []{48d,47,51,42});
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 186 ⟶ 631:
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">
<lang Cpp>
#include <iostream>
#include <vector>
Line 228 ⟶ 673:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 241 ⟶ 686:
=={{header|Clojure}}==
John Lawrence Aspden's code posted on [http://www.learningclojure.com/2013/08/diversity-prediction-theorem.html Diversity Prediction Theorem].
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn diversity-theorem [truth predictions]
(let [square (fn[x] (* x x))
Line 252 ⟶ 697:
(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 258 ⟶ 703:
{:average-error 29/2, :crowd-error 4, :diversity 21/2}
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls,Math}}
Delphi math libraries make this easier.
 
<syntaxhighlight lang="Delphi">
function AveSqrDiff(TrueVal: double; Data: array of double): double;
var I: integer;
begin
Result:=0;
for I:=0 to High(Data) do Result:=Result+Sqr(Data[I]-TrueVal);
Result:=Result/Length(Data);
end;
 
procedure DoDiversityPrediction(Memo: TMemo; TrueValue: double; Crowd: array of double);
var AveError,AvePredict,Diversity: double;
var S: string;
begin
AveError:=AveSqrDiff(Truevalue,Crowd);
AvePredict:=Mean(Crowd);
Diversity:=AveSqrDiff(AvePredict,Crowd);
S:='Ave Error: '+FloatToStrF(AveError,ffFixed,18,2)+#$0D#$0A;
S:=S+'Crowd Error: '+FloatToStrF(Sqr(TrueValue - AvePredict),ffFixed,18,2)+#$0D#$0A;
S:=S+'Diversity: '+FloatToStrF(Diversity,ffFixed,18,2)+#$0D#$0A;
Memo.Lines.Add(S);
end;
 
procedure ShowDiversityPrediction(Memo: TMemo);
begin
DoDiversityPrediction(Memo,49,[48,47,51]);
DoDiversityPrediction(Memo,49,[48,47,51,42]);
end;
 
</syntaxhighlight>
{{out}}
<pre>
Ave Error: 3.00
Crowd Error: 0.11
Diversity: 2.89
 
Ave Error: 14.50
Crowd Error: 4.00
Diversity: 10.50
 
 
</pre>
 
 
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.stdio;
 
Line 281 ⟶ 774:
diversityTheorem(49.0, [48.0, 47.0, 51.0]);
diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0]);
}</langsyntaxhighlight>
{{out}}
<pre>average-error: 3
Line 290 ⟶ 783:
crowd-error: 4
diversity: 10.5</pre>
 
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
proc calc TrueVal test[] . .
for test in test[]
h = (test - TrueVal)
Vari += h * h
Sum += test
c += 1
.
AvgErr = Vari / c
RefAvg = Sum / c
h = (TrueVal - RefAvg)
CrowdErr = h * h
print "Average error : " & AvgErr
print " Crowd error : " & CrowdErr
print " Diversity : " & AvgErr - CrowdErr
print ""
.
calc 49 [ 48 47 51 ]
calc 49 [ 48 47 51 42 ]
</syntaxhighlight>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: kernel math math.statistics math.vectors prettyprint ;
 
TUPLE: div avg-err crowd-err diversity ;
Line 302 ⟶ 818:
 
49 { 48 47 51 } diversity .
49 { 48 47 51 42 } diversity .</langsyntaxhighlight>
{{out}}
<pre>T{ div { avg-err 3 } { crowd-err 1/9 } { diversity 2+8/9 } }
<pre>
T{ div { avg-err 314+1/2 } { crowd-err 1/94 } { diversity 210+81/92 } }</pre>
T{ div { avg-err 14+1/2 } { crowd-err 4 } { diversity 10+1/2 } }
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Diversity_prediction_theorem}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
[[File:Fōrmulæ - Diversity prediction theorem 01.png]]
 
'''Test case 1.''' A true value of 49 with crowd estimates of 48, 47 and 51
 
[[File:Fōrmulæ - Diversity prediction theorem 02.png]]
 
[[File:Fōrmulæ - Diversity prediction theorem 03.png]]
 
'''Test case 2.''' A true value of 49 with crowd estimates of 48, 47, 51 and 42
 
[[File:Fōrmulæ - Diversity prediction theorem 04.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Diversity prediction theorem 05.png]]
In '''[https://formulae.org/?example=Diversity_prediction_theorem this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 351 ⟶ 877:
fmt.Printf("Diversity : %6.3f\n\n", div)
}
}</langsyntaxhighlight>
 
{{out}}
Line 366 ⟶ 892:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class DiversityPredictionTheorem {
private static double square(double d) {
return d * d
Line 389 ⟶ 915:
println(diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0] as double[]))
}
}</langsyntaxhighlight>
{{out}}
<pre>average-error : 3.000
Line 401 ⟶ 927:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">mean :: (Fractional a, Foldable t) => t a -> a
mean lst = sum lst / fromIntegral (length lst)
 
Line 416 ⟶ 942:
putStrLn $ "CrowdError:\t" ++ show crowderr
let diversity = meanSq avg estimates
putStrLn $ "Diversity:\t" ++ show diversity</langsyntaxhighlight>
 
<pre>λ> diversityPrediction 49 [48,47,51]
Line 435 ⟶ 961:
Accepts inputs from command line, prints out usage on incorrect invocation.
Were this compressed adaptation from C the content of file <tt>d.ijs</tt>
<syntaxhighlight lang="c">
<lang C>
echo 'Use: ' , (;:inv 2 {. ARGV) , ' <reference value> <observations>'
 
Line 452 ⟶ 978:
 
exit 0
</syntaxhighlight>
</lang>
example uses follow
<pre>
Line 495 ⟶ 1,021:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.util.Arrays;
 
public class DiversityPredictionTheorem {
Line 522 ⟶ 1,048:
System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0}));
}
}</langsyntaxhighlight>
{{out}}
<pre>average-error : 3.000
Line 534 ⟶ 1,060:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">'use strict';
 
function sum(array) {
Line 567 ⟶ 1,093:
console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42]))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 577 ⟶ 1,103:
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 648 ⟶ 1,174:
// MAIN ---
return main()
})();</langsyntaxhighlight>
{{Out}}
<pre>[
Line 665 ⟶ 1,191:
=={{header|Jsish}}==
From Typescript entry.
<langsyntaxhighlight lang="javascript">/* Diverisity Prediction Theorem, in Jsish */
"use strict";
 
Line 701 ⟶ 1,227:
diversityTheorem(49, [48,47,51,42]) ==> { "average-error":14.5, "crowd-error":4, diversity:10.5 }
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 711 ⟶ 1,237:
 
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq">def diversitytheorem($actual; $predicted):
def mean: add/length;
 
Line 717 ⟶ 1,243:
| { avgerr: ($predicted | map(. - $actual) | map(pow(.; 2)) | mean),
crderr: pow($mean - $actual; 2),
divers: ($predicted | map(. - $mean) | map(pow(.;2)) | mean) } ;</langsyntaxhighlight><syntaxhighlight lang ="jq"># The task:
([49, [48, 47, 51]],
[49, [48, 47, 51, 42]
])
| . as [$actual, $predicted]
| diversitytheorem($actual; $predicted)</langsyntaxhighlight>
 
{{out}}
Line 739 ⟶ 1,265:
=={{header|Julia}}==
{{works with|Julia|1.2}}
<langsyntaxhighlight lang="julia">import Statistics: mean
 
function diversitytheorem(truth::T, pred::Vector{T}) where T<:Number
Line 757 ⟶ 1,283:
diversity : $divers
""")
end</langsyntaxhighlight>
 
{{out}}
Line 771 ⟶ 1,297:
=={{header|Kotlin}}==
{{trans|TypeScript}}
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
fun square(d: Double) = d * d
Line 789 ⟶ 1,315:
println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0)))
println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0, 42.0)))
}</langsyntaxhighlight>
 
{{out}}
Line 804 ⟶ 1,330:
=={{header|Lua}}==
{{trans|C++}}
<langsyntaxhighlight lang="lua">function square(x)
return x * x
end
Line 838 ⟶ 1,364:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>average-error: 3
Line 848 ⟶ 1,374:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[DiversityPredictionTheorem]
DiversityPredictionTheorem[trueval_?NumericQ, estimates_List] :=
Module[{avg, avgerr, crowderr, diversity},
Line 864 ⟶ 1,390:
]
DiversityPredictionTheorem[49, {48, 47, 51}] // Dataset
DiversityPredictionTheorem[49, {48, 47, 51, 42}] // Dataset</langsyntaxhighlight>
{{out}}
<pre>TrueValue 49
Line 879 ⟶ 1,405:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strutils, math, stats
 
func meanSquareDiff(refValue: float; estimates: seq[float]): float =
Line 899 ⟶ 1,425:
echo "Crowd error: ", (m - trueValue)^2
echo "Prediction diversity: ", meanSquareDiff(m, estimates)
echo ""</langsyntaxhighlight>
 
{{out}}
Line 915 ⟶ 1,441:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub diversity {
my($truth, @pred) = @_;
my($ae,$ce,$cp,$pd,$stats);
Line 938 ⟶ 1,464:
 
print diversity(49, qw<48 47 51>) . "\n";
print diversity(49, qw<48 47 51 42>);</langsyntaxhighlight>
{{out}}
<pre>average-error: 3.000
Line 949 ⟶ 1,475:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function mean(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return sum(s)/length(s)
<span style="color: #008080;">function</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function variance(sequence s, atom d)
return mean(sq_power(sq_sub(s,d),2))
<span style="color: #008080;">function</span> <span style="color: #000000;">variance</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: #004080;">atom</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">),</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function diversity_theorem(atom reference, sequence observations)
atom average_error = variance(observations,reference),
<span style="color: #008080;">function</span> <span style="color: #000000;">diversity_theorem</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">reference</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">observations</span><span style="color: #0000FF;">)</span>
average = mean(observations),
<span style="color: #004080;">atom</span> <span style="color: #000000;">average_error</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">variance</span><span style="color: #0000FF;">(</span><span style="color: #000000;">observations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">reference</span><span style="color: #0000FF;">),</span>
crowd_error = power(reference-average,2),
<span style="color: #000000;">average</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">observations</span><span style="color: #0000FF;">),</span>
diversity = variance(observations,average)
<span style="color: #000000;">crowd_error</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">reference</span><span style="color: #0000FF;">-</span><span style="color: #000000;">average</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
return {{"average_error",average_error},
<span style="color: #000000;">diversity</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">variance</span><span style="color: #0000FF;">(</span><span style="color: #000000;">observations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">average</span><span style="color: #0000FF;">)</span>
{"crowd_error",crowd_error},
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">"average_error"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">average_error</span><span style="color: #0000FF;">},</span>
{"diversity",diversity}}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"crowd_error"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">crowd_error</span><span style="color: #0000FF;">},</span>
end function
<span style="color: #0000FF;">{</span><span style="color: #008000;">"diversity"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">diversity</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
procedure test(atom reference, sequence observations)
sequence res = diversity_theorem(reference, observations)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">reference</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">observations</span><span style="color: #0000FF;">)</span>
for i=1 to length(res) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">diversity_theorem</span><span style="color: #0000FF;">(</span><span style="color: #000000;">reference</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">observations</span><span style="color: #0000FF;">)</span>
printf(1," %14s : %g\n",res[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %14s : %g\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
test(49, {48, 47, 51})
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
test(49, {48, 47, 51, 42})</lang>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">49</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">48</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">47</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">51</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">49</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">48</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">47</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">51</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">42</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 984 ⟶ 1,513:
diversity : 10.5
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Define.f ref=49.0, mea
NewList argV.f()
 
Macro put
Print(~"\n["+StrF(ref)+"]"+#TAB$)
ForEach argV() : Print(StrF(argV())+#TAB$) : Next
PrintN(~"\nAverage Error : "+StrF(vari(argV(),ref),5))
PrintN("Crowd Error : "+StrF((ref-mea)*(ref-mea),5))
PrintN("Diversity : "+StrF(vari(argV(),mea),5))
EndMacro
 
Macro LetArgV(v)
AddElement(argV()) : argV()=v
EndMacro
 
Procedure.f mean(List x.f())
Define.f m
ForEach x() : m+x() : Next
ProcedureReturn m/ListSize(x())
EndProcedure
 
Procedure.f vari(List x.f(),r.f)
NewList nx.f()
ForEach x() : AddElement(nx()) : nx()=(r-x())*(r-x()) : Next
ProcedureReturn mean(nx())
EndProcedure
 
If OpenConsole()=0 : End 1 : EndIf
Gosub SetA : ClearList(argV())
Gosub SetB : Input()
End
 
SetA:
LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0)
mea=mean(argV()) : put
Return
 
SetB:
LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0) : LetArgV(42.0)
mea=mean(argV()) : put
Return</lang>
{{out}}
<pre>[49] 48 47 51
Average Error : 3.00000
Crowd Error : 0.11111
Diversity : 2.88889
 
[49] 48 47 51 42
Average Error : 14.50000
Crowd Error : 4.00000
Diversity : 10.50000</pre>
 
=={{header|Python}}==
By composition of pure functions:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Diversity prediction theorem'''
 
from itertools import chain
Line 1,299 ⟶ 1,775:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,328 ⟶ 1,804:
=={{header|R}}==
R's vectorisation shines here. The hardest part of this task was giving each estimate its own numbered column, which is little more than a printing luxury. The actual mathematics was trivial, with each part done in essentially one line.
<langsyntaxhighlight lang="rsplus">diversityStats <- function(trueValue, estimates)
{
collectivePrediction <- mean(estimates)
data.frame("True Value" = trueValue,
as.list(setNames(estimates, paste("Guess", seq_along(estimates)))), #Guesses, each with a title and column.
"Average Error" = mean((trueValue - estimates)^2),
"Crowd Error" = (trueValue - collectivePrediction)^2,
"Prediction Diversity" = mean((estimates - collectivePrediction)^2))
}
diversityStats(49, c(48, 47, 51))
diversityStats(49, c(48, 47, 51, 42))</langsyntaxhighlight>
{{out}}
<pre>> diversityStats(49, c(48, 47, 51))
Line 1,347 ⟶ 1,823:
True.Value Guess.1 Guess.2 Guess.3 Guess.4 Average.Error Crowd.Error Prediction.Diversity
1 49 48 47 51 42 14.5 4 10.5</pre>
 
=={{header|Racket}}==
 
{{trans|Clojure}}
 
<syntaxhighlight lang="racket">#lang racket
 
(define (mean l)
(/ (apply + l) (length l)))
 
(define (diversity-theorem truth predictions)
(define μ (mean predictions))
(define (avg-sq-diff a)
(mean (map (λ (p) (sqr (- p a))) predictions)))
(hash 'average-error (avg-sq-diff truth)
'crowd-error (sqr (- truth μ))
'diversity (avg-sq-diff μ)))
(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42)))</syntaxhighlight>
 
{{out}}
 
<pre>'#hash((average-error . 3) (crowd-error . 1/9) (diversity . 2 8/9))
'#hash((average-error . 14 1/2) (crowd-error . 4) (diversity . 10 1/2))</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub diversity-calc($truth, @pred) {
my $ae = avg-error($truth, @pred); # average individual error
my $cp = ([+] @pred)/+@pred; # collective prediction
Line 1,369 ⟶ 1,870:
 
.say for diversity-format diversity-calc(49, <48 47 51>);
.say for diversity-format diversity-calc(49, <48 47 51 42>);</langsyntaxhighlight>
 
{{out}}
Line 1,382 ⟶ 1,883:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX */
Numeric Digits 20
Call diversityTheorem 49,'48 47 51'
Line 1,412 ⟶ 1,913:
res=res+(x-a)**2 /* accumulate square of differences */
End
Return res/words(list) /* return the average */</langsyntaxhighlight>
{{out}}
<pre>average-error=3
Line 1,425 ⟶ 1,926:
Uses greater precision, but rounds the output to six decimal digits past the decimal
point &nbsp; (see the last comment in the program).
<langsyntaxhighlight lang="rexx">/*REXX program calculates the average error, crowd error, and prediction diversity. */
numeric digits 50 /*use precision of fifty decimal digits*/
call diversity 49, 48 47 51 /*true value and the crowd predictions.*/
Line 1,439 ⟶ 1,940:
say ' the crowd error: ' format( (true-a) **2, , 6) / 1
say 'prediction diversity: ' format( avgSD(a) , , 6) / 1; say; say
return /* └─── show 6 dec. digs.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,452 ⟶ 1,953:
the crowd error: 4
prediction diversity: 10.5
</pre>
 
=={{header|RPL}}==
{{works with|HP|48G}}
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
« → pivot
« 1 « pivot - SQ » DOLIST
∑LIST LASTARG SIZE /
» » '<span style="color:blue">SQDIF</span>' STO
« → preds truth
« preds truth <span style="color:blue">SQDIF</span> "avg_err" →TAG
preds ∑LIST LASTARG SIZE /
DUP truth - SQ "cwd_err" →TAG
preds ROT <span style="color:blue">SQDIF</span> "pred_div" →TAG
3 →LIST
» » '<span style="color:blue">CROWD</span>' STO
|
<span style="color:blue">SQDIF</span> ( { values } pivot → average((value-pivot)²) )
get (value-pivot)²
get average
<span style="color:blue">CROWD</span> ( { preds } truth → { report } )
avg_err = mean((pred-truth)²)
average = ∑preds / number of preds
cwd_err = (average-truth)²
prd_div = mean((pred-cwd_err)²)
put them all into a list
|}
{ 48 47 51 } 49 <span style="color:blue">CROWD</span>
{ 48 47 51 42 } 49 <span style="color:blue">CROWD</span>
{{out}}
<pre>
2: { avg_err:3 cwd_err:0.111111111111 pred_div:2.88888888889 }
1: { avg_err:14.5 cwd_err:4 pred_div:10.5 }
</pre>
 
=={{header|Ruby}}==
{{trans|D}}
<langsyntaxhighlight lang="ruby">def mean(a) = a.sum(0.0) / a.size
def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })
Line 1,468 ⟶ 2,010:
diversity_theorem(49.0, [48.0, 47.0, 51.0])
diversity_theorem(49.0, [48.0, 47.0, 51.0, 42.0])</langsyntaxhighlight>
{{out}}
<pre>truth: 49.0, predictions [48.0, 47.0, 51.0]
Line 1,482 ⟶ 2,024:
=={{header|Scala}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="scala">object DiversityPredictionTheorem {
def square(d: Double): Double
= d * d
Line 1,503 ⟶ 2,045:
println(diversityTheorem(49.0, Array(48.0, 47.0, 51.0, 42.0)))
}
}</langsyntaxhighlight>
{{out}}
<pre>average-error : 3.000
Line 1,515 ⟶ 2,057:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func avg_error(m, v) {
v.map { (_ - m)**2 }.sum / v.len
}
Line 1,536 ⟶ 2,078:
 
diversity_format(diversity_calc(49, [48, 47, 51])).each{.say}
diversity_format(diversity_calc(49, [48, 47, 51, 42])).each{.say}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,548 ⟶ 2,090:
 
=={{header|TypeScript}}==
<syntaxhighlight lang="typescript">
<lang TypeScript>
function sum(array: Array<number>): number {
return array.reduce((a, b) => a + b)
Line 1,576 ⟶ 2,118:
console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42]))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,584 ⟶ 2,126:
{ 'average-error': 14.5, 'crowd-error': 4, diversity: 10.5 }
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<lang vbnet>Module Module1
 
Function Square(x As Double) As Double
Return x * x
End Function
 
Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double
Return predictions.Select(Function(x) Square(x - a)).Average()
End Function
 
Sub DiversityTheorem(truth As Double, predictions As IEnumerable(Of Double))
Dim average = predictions.Average()
Console.WriteLine("average-error: {0}", AverageSquareDiff(truth, predictions))
Console.WriteLine("crowd-error: {0}", Square(truth - average))
Console.WriteLine("diversity: {0}", AverageSquareDiff(average, predictions))
End Sub
 
Sub Main()
DiversityTheorem(49.0, {48.0, 47.0, 51.0})
DiversityTheorem(49.0, {48.0, 47.0, 51.0, 42.0})
End Sub
 
End Module</lang>
{{out}}
<pre>average-error: 3
crowd-error: 0.111111111111113
diversity: 2.88888888888889
average-error: 14.5
crowd-error: 4
diversity: 10.5</pre>
 
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var averageSquareDiff = Fn.new { |f, preds|
Line 1,643 ⟶ 2,152:
Fmt.print("Crowd-error : $6.3f", res[1])
Fmt.print("Diversity : $6.3f\n", res[2])
}</langsyntaxhighlight>
 
{{out}}
Line 1,654 ⟶ 2,163:
Crowd-error : 4.000
Diversity : 10.500
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">real Estimates, TrueVal, AvgErr, CrowdErr, Sum, Avg;
int I, J;
[Estimates:= [ [48., 47., 51., 0.], [48., 47., 51., 42., 0.] ];
TrueVal:= 49.;
Format(2, 3);
for I:= 0 to 1 do
[Sum:= 0.; J:= 0;
while Estimates(I,J) # 0. do
[Sum:= Sum + sq(Estimates(I,J) - TrueVal); J:= J+1];
AvgErr:= Sum/float(J);
Text(0, "Average error : "); RlOut(0, AvgErr); CrLf(0);
 
Sum:= 0.; J:= 0;
while Estimates(I,J) # 0. do
[Sum:= Sum + Estimates(I,J); J:= J+1];
Avg:= Sum/float(J);
CrowdErr:= sq(TrueVal-Avg);
Text(0, "Crowd error : "); RlOut(0, CrowdErr); CrLf(0);
 
Text(0, "Diversity : "); RlOut(0, AvgErr-CrowdErr); CrLf(0);
CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
Average error : 3.000
Crowd error : 0.111
Diversity : 2.889
 
Average error : 14.500
Crowd error : 4.000
Diversity : 10.500
 
</pre>
 
=={{header|zkl}}==
{{trans|Sidef}}
<langsyntaxhighlight lang="zkl">fcn avgError(m,v){ v.apply('wrap(n){ (n - m).pow(2) }).sum(0.0)/v.len() }
fcn diversityCalc(truth,pred){ //(Float,List of Float)
Line 1,669 ⟶ 2,214:
T("average-error","crowd-error","diversity").zip(stats)
.pump(String,Void.Xplode,"%13s :%7.3f\n".fmt)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">diversityCalc(49.0, T(48.0,47.0,51.0)) : diversityFormat(_).println();
diversityCalc(49.0, T(48.0,47.0,51.0,42.0)) : diversityFormat(_).println();</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits