Statistics/Basic: Difference between revisions

m
(→‎{{header|VBA}}: using the built-in Excel worksheetfunction.frequency)
m (→‎{{header|Wren}}: Minor tidy)
 
(39 intermediate revisions by 21 users not shown)
Line 35:
<br><hr>
 
=={{header|Ada11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F sd_mean(numbers)
V mean = sum(numbers) / numbers.len
V sd = (sum(numbers.map(n -> (n - @mean) ^ 2)) / numbers.len) ^ 0.5
R (sd, mean)
 
F histogram(numbers)
V h = [0] * 10
V maxwidth = 50
L(n) numbers
h[Int(n * 10)]++
V mx = max(h)
print()
L(i) h
print(‘#.1: #.’.format(L.index / 10, ‘+’ * (i * maxwidth I/ mx)))
print()
 
L(i) (1, 5)
V n = (0 .< 10 ^ i).map(j -> random:())
print("\n####\n#### #. numbers\n####".format(10 ^ i))
V (sd, mean) = sd_mean(n)
print(‘ sd: #.6, mean: #.6’.format(sd, mean))
histogram(n)</syntaxhighlight>
 
{{out}}
<pre>
 
##
## 10 numbers
##
sd: 0.180934, mean: 0.508126
 
0.0:
0.1:
0.2: +++++++++++++++++++++++++++++++++
0.3: +++++++++++++++++++++++++++++++++
0.4:
0.5: +++++++++++++++++++++++++++++++++
0.6: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.7:
0.8: ++++++++++++++++
0.9:
 
 
##
## 100000 numbers
##
sd: 0.288029, mean: 0.501473
 
0.0: +++++++++++++++++++++++++++++++++++++++++++++++
0.1: +++++++++++++++++++++++++++++++++++++++++++++++
0.2: ++++++++++++++++++++++++++++++++++++++++++++++++
0.3: ++++++++++++++++++++++++++++++++++++++++++++++++
0.4: ++++++++++++++++++++++++++++++++++++++++++++++++
0.5: ++++++++++++++++++++++++++++++++++++++++++++++++
0.6: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.7: ++++++++++++++++++++++++++++++++++++++++++++++++
0.8: +++++++++++++++++++++++++++++++++++++++++++++++
0.9: ++++++++++++++++++++++++++++++++++++++++++++++++
</pre>
 
=={{header|Action!}}==
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE SIZE="10000"
DEFINE HIST_SIZE="10"
BYTE ARRAY data(SIZE)
CARD ARRAY hist(HIST_SIZE)
 
PROC Generate()
INT i
 
FOR i=0 TO SIZE-1
DO
data(i)=Rand(0)
OD
RETURN
 
PROC CalcMean(INT count REAL POINTER mean)
REAL tmp1,tmp2,r255
INT i
 
IntToReal(0,mean)
IntToReal(255,r255)
FOR i=0 TO count-1
DO
IntToReal(data(i),tmp1)
RealDiv(tmp1,r255,tmp2)
RealAdd(mean,tmp2,tmp1)
RealAssign(tmp1,mean)
OD
IntToReal(count,tmp1)
RealDiv(mean,tmp1,tmp2)
RealAssign(tmp2,mean)
RETURN
 
PROC CalcStdDev(INT count REAL POINTER mean,sdev)
REAL tmp1,tmp2,r255
INT i
 
IntToReal(0,sdev)
IntToReal(255,r255)
FOR i=0 TO count-1
DO
IntToReal(data(i),tmp1)
RealDiv(tmp1,r255,tmp2)
RealSub(tmp2,mean,tmp1)
RealMult(tmp1,tmp1,tmp2)
RealAdd(sdev,tmp2,tmp1)
RealAssign(tmp1,sdev)
OD
IntToReal(count,tmp1)
RealDiv(sdev,tmp1,tmp2)
Sqrt(tmp2,sdev)
RETURN
 
PROC ClearHistogram()
BYTE i
 
FOR i=0 TO HIST_SIZE-1
DO
hist(i)=0
OD
RETURN
 
PROC CalcHistogram(INT count)
INT i,index
 
ClearHistogram()
FOR i=0 TO count-1
DO
index=data(i)*10/256
hist(index)==+1
OD
RETURN
 
PROC PrintHistogram()
BYTE i,j,n
INT max
REAL tmp1,tmp2,rmax,rlen
 
max=0
FOR i=0 TO HIST_SIZE-1
DO
IF hist(i)>max THEN
max=hist(i)
FI
OD
IntToReal(max,rmax)
IntToReal(25,rlen)
 
FOR i=0 TO HIST_SIZE-1
DO
PrintF("0.%Bx: ",i)
IntToReal(hist(i),tmp1)
RealMult(tmp1,rlen,tmp2)
RealDiv(tmp2,rmax,tmp1)
n=RealToInt(tmp1)
FOR j=0 TO n
DO
Put('*)
OD
PrintF(" %U",hist(i))
IF i<HIST_SIZE-1 THEN
PutE()
FI
OD
RETURN
 
PROC Test(INT count)
REAL mean,sdev
 
PrintI(count)
CalcMean(count,mean)
Print(": m=") PrintR(mean)
CalcStdDev(count,mean,sdev)
Print(" sd=") PrintRE(sdev)
CalcHistogram(count)
PrintHistogram()
RETURN
 
PROC Main()
Put(125) PutE() ;clear screen
MathInit()
Generate()
Test(100)
PutE() PutE()
Test(10000)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Statistics_basic.png Screenshot from Atari 8-bit computer]
<pre>100: m=.5372941127 sd=.2901337976
0.0x: *************** 8
0.1x: ********** 5
0.2x: ************************** 14
0.3x: ***************** 9
0.4x: ***************** 9
0.5x: ************************ 13
0.6x: *************** 8
0.7x: ************** 7
0.8x: ************************** 14
0.9x: ************************ 13
 
10000: m=.4967046205 sd=.2887503512
0.0x: *********************** 950
0.1x: ************************** 1083
0.2x: ************************* 1054
0.3x: ************************ 998
0.4x: ************************ 975
0.5x: ************************* 1042
0.6x: ************************ 984
0.7x: *********************** 960
0.8x: ************************ 979
0.9x: ************************ 975</pre>
 
=={{header|Ada}}==
===A plain solution for moderate sample sizes===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random,
Ada.Numerics.Generic_Elementary_Functions;
 
Line 101 ⟶ 319:
TIO.New_Line;
Put_Mean_Et_Al(Sample_Size => N, Val_Sum => Val_Sum, Square_Sum => Squ_Sum);
end Basic_Stat;</langsyntaxhighlight>
 
{{out}} from a few sample runs:
<pre>> ./basic_stat 1000
Line 177 ⟶ 394:
This is the modified program
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random,
Ada.Numerics.Generic_Elementary_Functions;
 
Line 253 ⟶ 470:
Put_Mean_Et_Al(Sample_Size => N,
Val_Sum => Float(Val_Sum), Square_Sum => Float(Squ_Sum));
end Long_Basic_Stat;</langsyntaxhighlight>
 
{{out}} for sample size 10^12 took one night on my PC:
Line 336 ⟶ 553:
 
The same program should still work fine for sample size 10^18, but I'll need my PC in the meantime. ;-)
 
=={{header|ALGOL 68}}==
Suitable for the moderate sample sizes millions or billions probably - not suitable for e.g.: a trillion samples (with early 21st century hardware).
<syntaxhighlight lang="algol68">
BEGIN # calculate the mean and standard deviation of some data and draw a #
# histogram of the data #
 
# return the mean of data #
OP MEAN = ( []REAL data )REAL:
IF INT len = ( UPB data - LWB data ) + 1;
len < 1
THEN 0
ELSE REAL sum := 0;
FOR i FROM LWB data TO UPB data DO
sum +:= data[ i ]
OD;
sum / len
FI # MEAN # ;
 
# returns the standard deviation of data #
OP STDDEV = ( []REAL data )REAL:
IF INT len = ( UPB data - LWB data ) + 1;
len < 1
THEN 0
ELSE REAL m = MEAN data;
REAL sum := 0;
FOR i FROM LWB data TO UPB data DO
sum +:= ( data[ i ] - m ) ^ 2
OD;
sqrt( sum / len )
FI # STDDEV # ;
 
# generates a row of n random numbers in the range [0..1) #
PROC random row = ( INT n )REF[]REAL:
BEGIN
REF[]REAL data = HEAP[ 1 : n ]REAL;
FOR i TO n DO
data[ i ] := next random
OD;
data
END # random row # ;
 
# returns s right-padded with spaces to at least w characters #
PROC right pad = ( STRING s, INT w )STRING:
IF INT len = ( UPB s - LWB s ) + 1; len >= w THEN s ELSE s + ( " " * ( w - len ) ) FI;
 
# prints a histogram of data ( assumed to be in [0..1) ) with n bars #
# scaled to fit in h scale characters #
PROC print histogram = ( []REAL data, INT n, h scale )VOID:
IF n > 0 AND h scale > 0 THEN
[ 0 : n - 1 ]INT count;
FOR i FROM LWB count TO UPB count DO count[ i ] := 0 OD;
FOR i FROM LWB data TO UPB data DO
count[ ENTIER ( data[ i ] * n ) ] +:= 1
OD;
INT max count := 0;
FOR i FROM LWB count TO UPB count DO
IF count[ i ] > max count THEN max count := count[ i ] FI
OD;
INT len = ( UPB data - LWB data ) + 1;
REAL v := 0;
REAL scale = max count / h scale;
FOR i FROM LWB count TO UPB count DO
print( ( fixed( v, -4, 2 ), ": " ) );
print( ( right pad( "=" * ROUND ( count[ i ] / scale ), h scale ) ) );
print( ( " (", whole( count[ i ], 0 ), ")", newline ) );
v +:= 1 / n
OD
FI # print histogram # ;
 
# task #
 
# generate n random data items, calculate the mean and stddev and show #
# a histogram of the data #
PROC show statistics = ( INT n )VOID:
BEGIN
[]REAL data = random row( n );
print( ( "Sample size: ", whole( n, -6 ) ) );
print( ( ", mean: ", fixed( MEAN data, -8, 4 ) ) );
print( ( ", stddev: ", fixed( STDDEV data, -8, 4 ) ) );
print( ( newline ) );
print histogram( data, 10, 32 );
print( ( newline ) )
END # show statistics # ;
 
show statistics( 100 );
show statistics( 1 000 );
show statistics( 10 000 );
show statistics( 100 000 )
 
END
</syntaxhighlight>
{{out}}
<pre>
Sample size: 100, mean: 0.5092, stddev: 0.2783
0.00: ==================== (10)
0.10: ==================== (10)
0.20: ========== (5)
0.30: ======================== (12)
0.40: ======================== (12)
0.50: ================ (8)
0.60: ================================ (16)
0.70: ================ (8)
0.80: ======================== (12)
0.90: ============== (7)
 
Sample size: 1000, mean: 0.4989, stddev: 0.2855
0.00: ========================== (92)
0.10: =============================== (110)
0.20: =========================== (97)
0.30: ============================ (100)
0.40: ============================ (102)
0.50: ========================== (94)
0.60: ================================ (115)
0.70: ========================== (92)
0.80: =========================== (98)
0.90: ============================ (100)
 
Sample size: 10000, mean: 0.5011, stddev: 0.2863
0.00: ============================= (942)
0.10: ============================== (996)
0.20: ================================ (1057)
0.30: ============================= (968)
0.40: =============================== (1028)
0.50: ============================== (1000)
0.60: =============================== (1008)
0.70: =============================== (1019)
0.80: ============================== (1003)
0.90: ============================== (979)
 
Sample size: 100000, mean: 0.4996, stddev: 0.2881
0.00: =============================== (9917)
0.10: ================================ (10136)
0.20: =============================== (9936)
0.30: =============================== (9850)
0.40: ================================ (10123)
0.50: ================================ (10139)
0.60: ================================ (10167)
0.70: =============================== (9840)
0.80: =============================== (9905)
0.90: =============================== (9987)
</pre>
 
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
#define TOTAL_BINES 10
 
algoritmo
 
/* verifica y obtiene argumento: tamaño de muestra*/
tamaño muestra=0
//obtener total argumentos
//es distinto a '2', entonces{ terminar }
//obtener parámetro numérico(2), mover a 'tamaño muestra'
/* algo menos natural, pero más claro para una mente formal: */
obtener total argumentos
si ' es distinto a( 2 ) '
terminar
sino
guardar ' parám numérico(2)' en 'tamaño muestra'
fin si
 
/* establece la escala para desplegar barras */
escala = 1.0
si ' #(tamaño muestra > 50) '
#( escala = 50.0 / tamaño muestra )
fin si
 
/* Generar muestra de tamaño "tamaño muestra" */
dimensionar con ( tamaño muestra) matriz aleatoria entera ( 10, muestra )
decimales '3'
/* Genera tabla de clases con 10 bines */
tabla de clases=0
bines(TOTAL_BINES, muestra), mover a 'tabla de clases'
/* Imprime tabla de clases */
ir a subrutina( desplegar tabla de clases)
/* Calcula promedio según tabla de clases */
promedio tabla=0, FREC=0, MC=0
ir a subrutina ( calcular promedio de tabla de clases )
/* Calcula desviación estándar y varianza */
desviación estándar=0, varianza=0
ir a subrutina ( calcular desviación estándar y varianza )
 
/* Calcula promedio de la muestra completa e imprime medidas */
ir a subrutina ( desplegar medidas y medias )
/* Construye barras */
tamaño barras=0, barras=0
ir a subrutina( construir barras para histograma ), mover a 'barras'
 
/* arma histograma de salida */
sMC=0
ir a subrutina( construir y desplegar histograma )
terminar
 
subrutinas
 
desplegar tabla de clases:
token.separador '"\t"'
imprimir '#(utf8("Tamaño de la muestra = ")), tamaño muestra,NL,NL,\
#(utf8("Números entre 0 y 10\n\n")),\
" --RANGO--\tM.DE C.\tFREC.\tF.R\t F.A.\tF.R.A.\n",\
"-----------------------------------------------------\n"'
imprimir 'justificar derecha(5,#(string(tabla de clases))), NL'
 
retornar
 
desplegar medidas y medias:
promedio muestra=0
muestra, promediar, mover a 'promedio muestra'
imprimir ' "Media de la muestra = ", promedio muestra, NL,\
"Media de la tabla = ", promedio tabla, NL,\
"Varianza = ", varianza, NL,\
#(utf8("Desviación estandar = ")), desviación estándar,NL'
retornar
 
construir barras para histograma:
#(tamaño barras = int(FREC * escala * 5))
 
dimensionar con (TOTAL_BINES) matriz rellena ("*", barras)
#(barras = replicate( barras, tamaño barras))
retornar ' barras '
 
construir y desplegar histograma:
#(sMC = string(MC))
unir columnas( sMC, sMC, justificar derecha(5,#(string(FREC))), barras )
 
/* Imprime histograma */
token.separador '" "'
imprimir ( " M.C. FREC.\n-----------\n",\
sMC,NL )
 
retornar
 
calcular promedio de tabla de clases:
//[1:filasde(tabla de clases), 3] coger (tabla de clases), mover a 'MC'
//[1:filasde(tabla de clases), 4] coger (tabla de clases), mover a 'FREC'
/* un poco menos natural, pero más claro para una mente formal: */
#basic{
MC = tabla de clases[ 1:TOTAL_BINES, 3]
FREC = tabla de clases[ 1:TOTAL_BINES, 4]
}
borrar intervalo
multiplicar(MC,FREC), calcular sumatoria, dividir entre (tamaño muestra),
mover a 'promedio tabla'
retornar
 
calcular desviación estándar y varianza:
restar( MC, promedio tabla), elevar al cuadrado, por (FREC),
calcular sumatoria, dividir entre(tamaño muestra), copiar en 'varianza'
calcular raíz, mover a 'desviación estándar'
retornar
 
</syntaxhighlight>
{{out}}
<pre>
$ hopper3 basica/estat.bas 100
Tamaño de la muestra = 100
 
Números entre 0 y 10
 
--RANGO-- M.DE C. FREC. F.R F.A. F.R.A.
-----------------------------------------------------
0 1 0.500 12 0.120 12 0.120
1 2 1.500 7 0.070 19 0.190
2 3 2.500 9 0.090 28 0.280
3 4 3.500 14 0.140 42 0.420
4 5 4.500 14 0.140 56 0.560
5 6 5.500 3 0.030 59 0.590
6 7 6.500 8 0.080 67 0.670
7 8 7.500 11 0.110 78 0.780
8 9 8.500 7 0.070 85 0.850
9 10 9.500 15 0.150 100 1.000
 
Media de la muestra = 4.540
Media de la tabla = 5.040
Varianza = 8.969
Desviación estandar = 2.995
 
M.C. FREC.
-----------
0.500 12 ******************************
1.500 7 *****************
2.500 9 **********************
3.500 14 ***********************************
4.500 14 ***********************************
5.500 3 *******
6.500 8 ********************
7.500 11 ***************************
8.500 7 *****************
9.500 15 *************************************
 
$ hopper3 basica/estat.bas 1000
Tamaño de la muestra = 1000
 
Números entre 0 y 10
 
--RANGO-- M.DE C. FREC. F.R F.A. F.R.A.
-----------------------------------------------------
0 1 0.500 87 0.087 87 0.087
1 2 1.500 94 0.094 181 0.181
2 3 2.500 109 0.109 290 0.290
3 4 3.500 109 0.109 399 0.399
4 5 4.500 95 0.095 494 0.494
5 6 5.500 99 0.099 593 0.593
6 7 6.500 91 0.091 684 0.684
7 8 7.500 100 0.100 784 0.784
8 9 8.500 106 0.106 890 0.890
9 10 9.500 110 0.110 1000 1.000
 
Media de la muestra = 4.598
Media de la tabla = 5.098
Varianza = 8.235
Desviación estandar = 2.870
 
M.C. FREC.
-----------
0.500 87 *********************
1.500 94 ***********************
2.500 109 ***************************
3.500 109 ***************************
4.500 95 ***********************
5.500 99 ************************
6.500 91 **********************
7.500 100 *************************
8.500 106 **************************
9.500 110 ***************************
 
$ hopper3 basica/estat.bas 10000
Tamaño de la muestra = 10000
 
Números entre 0 y 10
 
--RANGO-- M.DE C. FREC. F.R F.A. F.R.A.
-----------------------------------------------------
0 1 0.500 1039 0.104 1039 0.104
1 2 1.500 1014 0.101 2053 0.205
2 3 2.500 1005 0.101 3058 0.306
3 4 3.500 976 0.098 4034 0.403
4 5 4.500 949 0.095 4983 0.498
5 6 5.500 995 0.100 5978 0.598
6 7 6.500 1039 0.104 7017 0.702
7 8 7.500 1009 0.101 8026 0.803
8 9 8.500 992 0.099 9018 0.902
9 10 9.500 982 0.098 10000 1.000
 
Media de la muestra = 4.479
Media de la tabla = 4.979
Varianza = 8.310
Desviación estandar = 2.883
 
M.C. FREC.
-----------
0.500 1039 *************************
1.500 1014 *************************
2.500 1005 *************************
3.500 976 ************************
4.500 949 ***********************
5.500 995 ************************
6.500 1039 *************************
7.500 1009 *************************
8.500 992 ************************
9.500 982 ************************
 
$ hopper3 basica/estat.bas 100000
Tamaño de la muestra = 100000
 
Números entre 0 y 10
 
--RANGO-- M.DE C. FREC. F.R F.A. F.R.A.
-----------------------------------------------------
0 1 0.500 10139 0.101 10139 0.101
1 2 1.500 10025 0.100 20164 0.202
2 3 2.500 9990 0.100 30154 0.302
3 4 3.500 10021 0.100 40175 0.402
4 5 4.500 9880 0.099 50055 0.501
5 6 5.500 10054 0.101 60109 0.601
6 7 6.500 9961 0.100 70070 0.701
7 8 7.500 10144 0.101 80214 0.802
8 9 8.500 9773 0.098 89987 0.900
9 10 9.500 10013 0.100 100000 1.000
 
Media de la muestra = 4.489
Media de la tabla = 4.989
Varianza = 8.264
Desviación estandar = 2.875
 
M.C. FREC.
-----------
0.500 10139 **************************************************
1.500 10025 **************************************************
2.500 9990 *************************************************
3.500 10021 **************************************************
4.500 9880 *************************************************
5.500 10054 **************************************************
6.500 9961 *************************************************
7.500 10144 **************************************************
8.500 9773 ************************************************
9.500 10013 **************************************************
 
 
</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">100 HOME : rem 100 CLS for Chipmunk Basic, GW-BASIC and MSX BASIC
110 CLEAR : n = 100 : GOSUB 150 : rem no se requiere CLEAR
120 CLEAR : n = 1000 : GOSUB 150
130 CLEAR : n = 10000 : GOSUB 150
140 END
150 rem SUB sample(n)
160 DIM samp(n)
170 FOR i = 1 TO n
180 samp(i) = RND(1)
190 NEXT i
200 rem calculate mean, standard deviation
210 sum = 0
220 sumsq = 0
230 FOR i = 1 TO n
240 sum = sum+samp(i)
250 sumsq = sumsq+samp(i)^2
260 NEXT i
270 PRINT "Sample size ";n
280 mean = sum/n
290 PRINT
300 PRINT " Mean = ";mean
310 PRINT " Std Dev = ";(sumsq/n-mean^2)^0.5
320 PRINT
330 rem------- Show histogram
340 scal = 10
350 DIM bins(scal)
360 FOR i = 1 TO n
370 z = INT(scal*samp(i))
380 bins(z) = bins(z)+1
390 NEXT i
400 FOR b = 0 TO scal-1
410 PRINT " ";b;" : ";
420 FOR j = 1 TO INT(scal*bins(b))/n*70
430 PRINT "*";
440 NEXT j
450 PRINT
460 NEXT b
470 PRINT
480 RETURN</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
{{trans|Yabasic}}
<syntaxhighlight lang="qbasic">100 sub sample(n)
110 dim samp(n)
120 for i = 1 to n
130 samp(i) = rnd(1)
140 next i
150 rem calculate mean, standard deviation
160 sum = 0
170 sumsq = 0
180 for i = 1 to n
190 sum = sum+samp(i)
200 sumsq = sumsq+samp(i)^2
210 next i
220 print "Sample size ";n
230 mean = sum/n
240 print
250 print " Mean = ";mean
260 print " Std Dev = ";(sumsq/n-mean^2)^0.5
270 print
280 rem------- Show histogram
290 scal = 10
300 dim bins(scal)
310 for i = 1 to n
320 z = int(scal*samp(i))
330 bins(z) = bins(z)+1
340 next i
350 for b = 0 to scal-1
360 print " ";b;" : ";
370 for j = 1 to int(scal*bins(b))/n*70
380 print "*";
390 next j
400 print
410 next b
420 print
430 end sub
440 cls
450 sample(100)
460 sample(1000)
470 sample(10000)
480 end</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
 
Sub basicStats(sampleSize As Integer)
If sampleSize < 1 Then Return
Dim r(1 To sampleSize) As Double
Dim h(0 To 9) As Integer '' all zero by default
Dim sum As Double = 0.0
Dim hSum As Integer = 0
 
' Generate 'sampleSize' random numbers in the interval [0, 1)
' calculate their sum
' and in which box they will fall when drawing the histogram
For i As Integer = 1 To sampleSize
r(i) = Rnd
sum += r(i)
h(Int(r(i) * 10)) += 1
Next
 
For i As Integer = 0 To 9 : hSum += h(i) : Next
' adjust one of the h() values if necessary to ensure hSum = sampleSize
Dim adj As Integer = sampleSize - hSum
If adj <> 0 Then
For i As Integer = 0 To 9
h(i) += adj
If h(i) >= 0 Then Exit For
h(i) -= adj
Next
End If
Dim mean As Double = sum / sampleSize
 
Dim sd As Double
sum = 0.0
' Now calculate their standard deviation
For i As Integer = 1 To sampleSize
sum += (r(i) - mean) ^ 2.0
Next
sd = Sqr(sum/sampleSize)
 
' Draw a histogram of the data with interval 0.1
Dim numStars As Integer
' If sample size > 500 then normalize histogram to 500
Dim scale As Double = 1.0
If sampleSize > 500 Then scale = 500.0 / sampleSize
Print "Sample size "; sampleSize
Print
Print Using " Mean #.######"; mean;
Print Using " SD #.######"; sd
Print
For i As Integer = 0 To 9
Print Using " #.## : "; i/10.0;
Print Using "##### " ; h(i);
numStars = Int(h(i) * scale + 0.5)
Print String(numStars, "*")
Next
End Sub
basicStats 100
Print
basicStats 1000
Print
basicStats 10000
Print
basicStats 100000
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
{{out}}
<pre>Sample size 100
 
Mean 0.485580 SD 0.269003
 
0.00 : 7 *******
0.10 : 10 **********
0.20 : 12 ************
0.30 : 17 *****************
0.40 : 8 ********
0.50 : 10 **********
0.60 : 11 ***********
0.70 : 9 *********
0.80 : 9 *********
0.90 : 7 *******
 
Sample size 1000
 
Mean 0.504629 SD 0.292029
 
0.00 : 99 **************************************************
0.10 : 99 **************************************************
0.20 : 93 ***********************************************
0.30 : 108 ******************************************************
0.40 : 101 ***************************************************
0.50 : 97 *************************************************
0.60 : 90 *********************************************
0.70 : 110 *******************************************************
0.80 : 102 ***************************************************
0.90 : 101 ***************************************************
 
Sample size 10000
 
Mean 0.500027 SD 0.290618
 
0.00 : 1039 ****************************************************
0.10 : 997 **************************************************
0.20 : 978 *************************************************
0.30 : 988 *************************************************
0.40 : 998 **************************************************
0.50 : 959 ************************************************
0.60 : 1037 ****************************************************
0.70 : 1004 **************************************************
0.80 : 965 ************************************************
0.90 : 1035 ****************************************************
 
Sample size 100000
 
Mean 0.499503 SD 0.288730
 
0.00 : 10194 ***************************************************
0.10 : 9895 *************************************************
0.20 : 9875 *************************************************
0.30 : 9922 **************************************************
0.40 : 10202 ***************************************************
0.50 : 9981 **************************************************
0.60 : 10034 **************************************************
0.70 : 10012 **************************************************
0.80 : 9957 **************************************************
0.90 : 9928 **************************************************</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|MSX BASIC}}
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">100 CLS : rem 100 HOME FOR Applesoft BASIC
110 CLEAR : n = 100 : GOSUB 150
120 CLEAR : n = 1000 : GOSUB 150
130 CLEAR : n = 10000 : GOSUB 150
140 END
150 rem SUB sample(n)
160 DIM samp(n)
170 FOR i = 1 TO n
180 samp(i) = RND(1)
190 NEXT i
200 rem calculate mean, standard deviation
210 sum = 0
220 sumsq = 0
230 FOR i = 1 TO n
240 sum = sum+samp(i)
250 sumsq = sumsq+samp(i)^2
260 NEXT i
270 PRINT "Sample size ";n
280 mean = sum/n
290 PRINT
300 PRINT " Mean = ";mean
310 PRINT " Std Dev = ";(sumsq/n-mean^2)^0.5
320 PRINT
330 rem------- Show histogram
340 scal = 10
350 DIM bins(scal)
360 FOR i = 1 TO n
370 z = INT(scal*samp(i))
380 bins(z) = bins(z)+1
390 NEXT i
400 FOR b = 0 TO scal-1
410 PRINT " ";b;" : ";
420 FOR j = 1 TO INT(scal*bins(b))/n*70
430 PRINT "*";
440 NEXT j
450 PRINT
460 NEXT b
470 PRINT
480 RETURN</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
Be aware that the PRNG in LB has a SLIGHT bias.
<syntaxhighlight lang="lb">call sample 100
call sample 1000
call sample 10000
 
end
 
sub sample n
dim dat( n)
for i =1 to n
dat( i) =rnd( 1)
next i
 
'// show mean, standard deviation
sum =0
sSq =0
for i =1 to n
sum =sum +dat( i)
sSq =sSq +dat( i)^2
next i
print n; " data terms used."
 
mean =sum / n
print "Mean ="; mean
 
print "Stddev ="; ( sSq /n -mean^2)^0.5
 
'// show histogram
nBins =10
dim bins( nBins)
for i =1 to n
z =int( nBins *dat( i))
bins( z) =bins( z) +1
next i
for b =0 to nBins -1
for j =1 to int( nBins *bins( b)) /n *70)
print "#";
next j
print
next b
print
end sub</syntaxhighlight>
{{out}}
<pre> 100000 data terms used.
Mean =0.49870232
Stddev =0.28926563
######################################################################
######################################################################
######################################################################
######################################################################
#####################################################################
#####################################################################
#####################################################################
#####################################################################
######################################################################
#####################################################################</pre>
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|PureBasic}}===
{{trans|Liberty BASIC}}
Changes were made from the Liberty BASIC version to normalize the histogram as well as implement a random float function.
<syntaxhighlight lang="purebasic">Procedure.f randomf()
#RNG_max_resolution = 2147483647
ProcedureReturn Random(#RNG_max_resolution) / #RNG_max_resolution
EndProcedure
 
Procedure sample(n)
Protected i, nBins, binNumber, tickMarks, maxBinValue
Protected.f sum, sumSq, mean
Dim dat.f(n)
For i = 1 To n
dat(i) = randomf()
Next
;show mean, standard deviation
For i = 1 To n
sum + dat(i)
sumSq + dat(i) * dat(i)
Next i
PrintN(Str(n) + " data terms used.")
mean = sum / n
PrintN("Mean =" + StrF(mean))
PrintN("Stddev =" + StrF((sumSq / n) - Sqr(mean * mean)))
;show histogram
nBins = 10
Dim bins(nBins)
For i = 1 To n
binNumber = Int(nBins * dat(i))
bins(binNumber) + 1
Next
maxBinValue = 1
For i = 0 To nBins
If bins(i) > maxBinValue
maxBinValue = bins(i)
EndIf
Next
#normalizedMaxValue = 70
For binNumber = 0 To nBins
tickMarks = Int(bins(binNumber) * #normalizedMaxValue / maxBinValue)
PrintN(ReplaceString(Space(tickMarks), " ", "#"))
Next
PrintN("")
EndProcedure
 
If OpenConsole()
sample(100)
sample(1000)
sample(10000)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</syntaxhighlight>
{{out}}
<pre>100 data terms used.
Mean =0.4349198639
Stddev =-0.1744846404
#########################################################
#########################################
################################
#################################################################
################################
#####################################################
######################################################################
################
########################
################
 
 
1000 data terms used.
Mean =0.4960154891
Stddev =-0.1691310555
###############################################################
#######################################################
#############################################################
######################################################################
##########################################################
##############################################################
####################################################################
###############################################################
#############################################################
#####################################################
 
 
10000 data terms used.
Mean =0.5042046309
Stddev =-0.1668083966
##################################################################
################################################################
##################################################################
####################################################################
################################################################
######################################################################
####################################################################
###################################################################
####################################################################
####################################################################</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|Yabasic}}
<syntaxhighlight lang="qbasic">SUB sample (n)
DIM samp(n)
FOR i = 1 TO n
samp(i) = RND(1)
NEXT i
REM calculate mean, standard deviation
sum = 0
sumsq = 0
FOR i = 1 TO n
sum = sum + samp(i)
sumsq = sumsq + samp(i) ^ 2
NEXT i
PRINT "Sample size "; n
mean = sum / n
PRINT
PRINT " Mean = "; mean
PRINT " Std Dev = "; (sumsq / n - mean ^ 2) ^ .5
PRINT
REM------- Show histogram
scal = 10
DIM bins(scal)
FOR i = 1 TO n
z = INT(scal * samp(i))
bins(z) = bins(z) + 1
NEXT i
FOR b = 0 TO scal - 1
PRINT " "; b; " : ";
FOR j = 1 TO INT(scal * bins(b)) / n * 70
PRINT "*";
NEXT j
PRINT
NEXT b
PRINT
END SUB
 
CLS
sample (100)
sample (1000)
sample (10000)
END</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">call sample 100
call sample 1000
call sample 10000
end
sub sample n
dim samp(n)
for i =1 to n
samp(i) =rnd(1)
next i
' calculate mean, standard deviation
sum = 0
sumSq = 0
for i = 1 to n
sum = sum + samp(i)
sumSq = sumSq + samp(i)^2
next i
print n; " Samples used."
mean = sum / n
print "Mean = "; mean
print "Std Dev = "; (sumSq /n -mean^2)^0.5
'------- Show histogram
bins = 10
dim bins(bins)
for i = 1 to n
z = int(bins * samp(i))
bins(z) = bins(z) +1
next i
for b = 0 to bins -1
print b;" ";
for j = 1 to int(bins *bins(b)) /n *70
print "*";
next j
print
next b
print
end sub</syntaxhighlight>
<pre style="height: 40ex; overflow: scroll">
100 Samples used.
Mean = 0.514312738
Std Dev = 0.291627558
0 **************************************************************************************************
1 **********************************************************************
2 *********************
3 ***********************************
4 ***************************************************************
5 *******************************************************************************************
6 ***********************************************************************************************************************
7 **********************************************************************
8 ***************************************************************
9 **********************************************************************
 
1000 Samples used.
Mean = 0.495704208
Std Dev = 0.281389168
0 ***************************************************************
1 ********************************************************************
2 **************************************************************************
3 *******************************************************************************
4 **************************************************************************
5 **********************************************************************
6 ************************************************************************
7 **********************************************************************
8 ********************************************************
9 **********************************************************************
 
10000 Samples used.
Mean = 0.493594211
Std Dev = 0.288635912
0 ************************************************************************
1 ************************************************************************
2 **********************************************************************
3 *******************************************************************
4 **********************************************************************
5 ************************************************************************
6 ************************************************************************
7 *****************************************************************
8 **********************************************************************
9 ******************************************************************</pre>
 
==={{header|Yabasic}}===
{{trans|Run BASIC}}
<syntaxhighlight lang="vb">sample ( 100)
sample ( 1000)
sample (10000)
end
sub sample (n)
dim samp(n)
for i = 1 to n
samp(i) = ran(1)
next i
// calculate mean, standard deviation
sum = 0
sumSq = 0
for i = 1 to n
sum = sum + samp(i)
sumSq = sumSq + samp(i) ^ 2
next i
print "Sample size ", n
mean = sum / n
print "\n Mean = ", mean
print " Std Dev = ", (sumSq / n - mean ^ 2) ^ 0.5
print
//------- Show histogram
bins = 10
dim bins(bins)
for i = 1 to n
z = int(bins * samp(i))
bins(z) = bins(z) + 1
next i
for b = 0 to bins -1
print " ", b, " : ";
for j = 1 to int(bins * bins(b)) / n * 70
print "*";
next j
print
next b
print
end sub</syntaxhighlight>
 
=={{header|C}}==
Sample code.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 440 ⟶ 1,676:
}
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{libheader|Math.Net}}
<langsyntaxhighlight lang="csharp">using System;
using MathNet.Numerics.Statistics;
 
Line 475 ⟶ 1,711:
Run(10000);
}
}</langsyntaxhighlight>
{{out}}
<pre>Sample size: 100
Line 520 ⟶ 1,756:
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
#include <random>
#include <vector>
Line 567 ⟶ 1,803:
std::cout << "Standard deviation is " << stddev << " !" << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>./statistics 100
Line 583 ⟶ 1,819:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">generate_statistics = (n) ->
generate_statistics = (n) ->
hist = {}
 
Line 619 ⟶ 1,854:
for n in [100, 1000, 10000, 1000000]
[n, mean, stddev, hist] = generate_statistics n
display_statistics n, mean, stddev, hist</syntaxhighlight>
 
</lang>
 
{{out}}
<pre>> coffee stats.coffee
<pre>
> coffee stats.coffee
-- Stats for sample size 100
mean: 0.5058459933893755
Line 682 ⟶ 1,913:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.typecons,
std.range, std.exception;
 
Line 726 ⟶ 1,957:
}
}
}</langsyntaxhighlight>
Compile with "-version=statistics_basic_main" to run the main function.
{{out}}
Line 808 ⟶ 2,039:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="d">/* Import math library to get:
* 1) Square root function : Math.sqrt(x)
* 2) Power function : Math.pow(base, exponent)
Line 906 ⟶ 2,137:
print('');
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 980 ⟶ 2,211:
 
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
global list[] .
proc mklist n . .
list[] = [ ]
for i = 1 to n
list[] &= randomf
.
.
func mean .
for v in list[]
sum += v
.
return sum / len list[]
.
func stddev .
avg = mean
for v in list[]
squares += (avg - v) * (avg - v)
.
return sqrt (squares / len list[])
.
proc histo . .
len hist[] 10
for v in list[]
ind = floor (v * 10) + 1
hist[ind] += 1
.
for v in hist[]
h = floor (v / len list[] * 200 + 0.5)
s$ = substr "========================================" 1 h
print v & " " & s$
.
.
numfmt 4 5
proc stats size . .
mklist size
print "Size: " & size
print "Mean: " & mean
print "Stddev: " & stddev
histo
print ""
.
stats 100
stats 1000
stats 10000
stats 100000
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Statistics do
def basic(n) do
{sum, sum2, hist} = generate(n)
Line 1,009 ⟶ 2,289:
Enum.each([100,1000,10000], fn n ->
Statistics.basic(n)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,057 ⟶ 2,337:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs formatting grouping io kernel literals math
math.functions math.order math.statistics prettyprint random
sequences sequences.deep sequences.repeating ;
Line 1,093 ⟶ 2,373:
{ 100 1,000 10,000 } [ stats ] each ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,142 ⟶ 2,422:
{{works with|Fortran|95 and later}}
This version will handle numbers as large as 1 trillion or more if you are prepared to wait long enough
<langsyntaxhighlight lang="fortran">program basic_stats
implicit none
Line 1,177 ⟶ 2,457:
end do
end program</langsyntaxhighlight>
{{out}}
<pre>sample size = 100
sample size = 100
Mean : 0.507952672404959
Stddev : 0.290452178516586
Line 1,234 ⟶ 2,513:
0.8: =================================================
0.9: ==================================================
1.0: =================================================</pre>
</pre>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Randomize
 
Sub basicStats(sampleSize As Integer)
If sampleSize < 1 Then Return
Dim r(1 To sampleSize) As Double
Dim h(0 To 9) As Integer '' all zero by default
Dim sum As Double = 0.0
Dim hSum As Integer = 0
 
' Generate 'sampleSize' random numbers in the interval [0, 1)
' calculate their sum
' and in which box they will fall when drawing the histogram
For i As Integer = 1 To sampleSize
r(i) = Rnd
sum += r(i)
h(Int(r(i) * 10)) += 1
Next
 
For i As Integer = 0 To 9 : hSum += h(i) : Next
' adjust one of the h() values if necessary to ensure hSum = sampleSize
Dim adj As Integer = sampleSize - hSum
If adj <> 0 Then
For i As Integer = 0 To 9
h(i) += adj
If h(i) >= 0 Then Exit For
h(i) -= adj
Next
End If
Dim mean As Double = sum / sampleSize
 
Dim sd As Double
sum = 0.0
' Now calculate their standard deviation
For i As Integer = 1 To sampleSize
sum += (r(i) - mean) ^ 2.0
Next
sd = Sqr(sum/sampleSize)
 
' Draw a histogram of the data with interval 0.1
Dim numStars As Integer
' If sample size > 500 then normalize histogram to 500
Dim scale As Double = 1.0
If sampleSize > 500 Then scale = 500.0 / sampleSize
Print "Sample size "; sampleSize
Print
Print Using " Mean #.######"; mean;
Print Using " SD #.######"; sd
Print
For i As Integer = 0 To 9
Print Using " #.## : "; i/10.0;
Print Using "##### " ; h(i);
numStars = Int(h(i) * scale + 0.5)
Print String(numStars, "*")
Next
End Sub
basicStats 100
Print
basicStats 1000
Print
basicStats 10000
Print
basicStats 100000
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
Sample size 100
 
Mean 0.485580 SD 0.269003
 
0.00 : 7 *******
0.10 : 10 **********
0.20 : 12 ************
0.30 : 17 *****************
0.40 : 8 ********
0.50 : 10 **********
0.60 : 11 ***********
0.70 : 9 *********
0.80 : 9 *********
0.90 : 7 *******
 
Sample size 1000
 
Mean 0.504629 SD 0.292029
 
0.00 : 99 **************************************************
0.10 : 99 **************************************************
0.20 : 93 ***********************************************
0.30 : 108 ******************************************************
0.40 : 101 ***************************************************
0.50 : 97 *************************************************
0.60 : 90 *********************************************
0.70 : 110 *******************************************************
0.80 : 102 ***************************************************
0.90 : 101 ***************************************************
 
Sample size 10000
 
Mean 0.500027 SD 0.290618
 
0.00 : 1039 ****************************************************
0.10 : 997 **************************************************
0.20 : 978 *************************************************
0.30 : 988 *************************************************
0.40 : 998 **************************************************
0.50 : 959 ************************************************
0.60 : 1037 ****************************************************
0.70 : 1004 **************************************************
0.80 : 965 ************************************************
0.90 : 1035 ****************************************************
 
Sample size 100000
 
Mean 0.499503 SD 0.288730
 
0.00 : 10194 ***************************************************
0.10 : 9895 *************************************************
0.20 : 9875 *************************************************
0.30 : 9922 **************************************************
0.40 : 10202 ***************************************************
0.50 : 9981 **************************************************
0.60 : 10034 **************************************************
0.70 : 10012 **************************************************
0.80 : 9957 **************************************************
0.90 : 9928 **************************************************
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,412 ⟶ 2,556:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,462 ⟶ 2,606:
 
The following runs comfortably on a simulated data size of 10 million. To scale to a trillion, and to use real data, you would want to use a technique like [[Distributed_programming#Go]] to distribute work across multiple computers, and on each computer, use a technique like [[Parallel_calculations#Go]] to distribute work across multiple cores within each computer. You would tune parameters like the constant <tt>threshold</tt> in the code below to optimize cache performance.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,525 ⟶ 2,669:
}
return
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,544 ⟶ 2,688:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Foldable (foldl') --'
import System.Random (randomRs, newStdGen)
import Control.Monad (zipWithM_)
Line 1,612 ⟶ 2,756:
 
-- To avoid Wiki formatting issue
foldl'' = foldl'</langsyntaxhighlight>
{{out}}
<pre>./Statistics 100
Line 1,644 ⟶ 2,788:
=={{header|Hy}}==
 
<langsyntaxhighlight lang="lisp">(import
[numpy.random [random]]
[numpy [mean std]]
Line 1,654 ⟶ 2,798:
 
(plt.hist (random 1000))
(plt.show)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,661 ⟶ 2,805:
In this example,
 
<langsyntaxhighlight Iconlang="icon">procedure main(A)
 
W := 50 # avg width for histogram bar
Line 1,686 ⟶ 2,830:
write(right(real(i)/*H,5)," : ",repl("*",integer(*H*50./N*H[i])))
}
end</langsyntaxhighlight>
 
{{out}}
Line 1,735 ⟶ 2,879:
 
J has library routines to compute mean and standard deviation:
<langsyntaxhighlight lang="j"> require 'stats'
(mean,stddev) 1000 ?@$ 0
0.484669 0.287482
Line 1,741 ⟶ 2,885:
0.503642 0.290777
(mean,stddev) 100000 ?@$ 0
0.499677 0.288726</langsyntaxhighlight>
 
And, for a histogram:
 
<langsyntaxhighlight lang="j">histogram=: <: @ (#/.~) @ (i.@#@[ , I.)
require'plot'
plot ((% * 1 + i.)100) ([;histogram) 10000 ?@$ 0</langsyntaxhighlight>
 
but these are not quite what is being asked for here.
Line 1,753 ⟶ 2,897:
Instead:
 
<langsyntaxhighlight lang="j">histogram=: <: @ (#/.~) @ (i.@#@[ , I.)
 
meanstddevP=: 3 :0
Line 1,776 ⟶ 2,920:
smoutput (<.300*h%y) #"0 '#'
(s%y) , %:t%y
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> meanstddevP 1000
#############################
####################################
Line 1,815 ⟶ 2,959:
##############################
#############################
0.500872 0.288241</langsyntaxhighlight>
 
(That said, note that these numbers are random, so reported standard deviation will vary with the random sample being tested.)
Line 1,824 ⟶ 2,968:
Translation of [[Statistics/Basic#Python|Python]] via [[Statistics/Basic#D|D]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.Math.pow;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.joining;
Line 1,875 ⟶ 3,019:
}
}
}</langsyntaxhighlight>
<pre>10 numbers:
Mean: 0.564409, SD: 0.249601
Line 1,953 ⟶ 3,097:
0.8: **************************************************
0.9: **************************************************</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The following jq program uses a streaming approach so that only one PRN (pseudo-random number)
need be in memory at a time.
For PRNs in [0,1], as here, the program is thus essentially only limited by available CPU time.
In the example section below, we include N=100 million.
 
Since jq does not currently have a built-in PRNG, we will use an external source
of entropy; there are, however, RC entries giving PRN generators written in jq that could be used,
e.g. https://rosettacode.org/wiki/Subtractive_generator#jq
 
For the sake of illustration, we will use /dev/urandom encapsulated in a shell function:
<syntaxhighlight lang="sh"># Usage: prng N width
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w "$2" | head -n "$1"
}</syntaxhighlight>
 
'''basicStats.jq'''
<syntaxhighlight lang="jq"> # $histogram should be a JSON object, with buckets as keys and frequencies as values;
# $keys should be an array of all the potential bucket names (possibly integers)
# in the order to be used for display:
def pp($histogram; $keys):
([$histogram[]] | add) as $n # for scaling
| ($keys|length) as $length
| $keys[]
| "\(.) : \("*" * (($histogram[tostring] // 0) * 20 * $length / $n) // "" )" ;
 
# `basic_stats` computes the unadjusted standard deviation
# and assumes the sum of squares (ss) can be computed without concern for overflow.
# The histogram is based on allocation to a bucket, which is made
# using `bucketize`, e.g. `.*10|floor`
def basic_stats(stream; bucketize):
# Use
reduce stream as $x ({histogram: {}};
.count += 1
| .sum += $x
| .ss += $x * $x
| ($x | bucketize | tostring) as $bucket
| .histogram[$bucket] += 1 )
| .mean = (.sum / .count)
| .stddev = (((.ss/.count) - .mean*.mean) | sqrt) ;
 
basic_stats( "0." + inputs | tonumber; .*10|floor)
| "
 
Basic statistics for \(.count) PRNs in [0,1]:
mean: \(.mean)
stddev: \(.stddev)
Histogram dividing [0,1] into 10 equal intervals:",
pp(.histogram; [range(0;10)] )</syntaxhighlight>
'''Driver Script''' (e.g. bash)
<syntaxhighlight lang="text">for n in 100 1000 1000000 100000000; do
echo "Basic statistics for $n PRNs in [0,1]"
prng $n 10 | jq -nrR -f basicStats.jq
echo
done</syntaxhighlight>
{{out}}
<pre>
 
 
Basic statistics for 100 PRNs in [0,1]:
mean: 0.4751625517819999
stddev: 0.2875486981539608
Histogram dividing [0,1] into 10 equal intervals:
0 : **********************
1 : ****************************
2 : ******************
3 : ********************
4 : **************
5 : **********************
6 : **********************
7 : ********************
8 : ******************
9 : ****************
 
 
Basic statistics for 1000 PRNs in [0,1]:
mean: 0.4943404721135997
stddev: 0.2912864574615721
Histogram dividing [0,1] into 10 equal intervals:
0 : *********************
1 : ********************
2 : ********************
3 : ******************
4 : ********************
5 : ******************
6 : *********************
7 : ********************
8 : ****************
9 : *********************
 
 
Basic statistics for 1000000 PRNs in [0,1]:
mean: 0.5000040604203146
stddev: 0.28858826757261763
Histogram dividing [0,1] into 10 equal intervals:
0 : *******************
1 : *******************
2 : ********************
3 : ********************
4 : ********************
5 : ********************
6 : ********************
7 : *******************
8 : ********************
9 : *******************
 
 
Basic statistics for 100000000 PRNs in [0,1]:
mean: 0.4999478413866642
stddev: 0.2886986905535449
Histogram dividing [0,1] into 10 equal intervals:
0 : ********************
1 : ********************
2 : ********************
3 : *******************
4 : ********************
5 : *******************
6 : *******************
7 : *******************
8 : ********************
9 : ********************
</pre>
 
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
 
function statisticsBasic(args:array|string=void, conf:object=void) {
var options = { // Rosetta Code, Statistics/Basic
rootdir :'', // Root directory.
samples : 0 // Set sample size from options
};
var self = { };
parseOpts(self, options, conf);
 
function generateStats(n:number):object {
var i, sum = 0, sum2 = 0;
var hist = new Array(10);
hist.fill(0);
for (i = 0; i < n; i++) {
var r = Math.random();
sum += r;
sum2 += r*r;
hist[Math.floor((r*10))] += 1;
}
var mean = sum/n;
var stddev = Math.sqrt((sum2 / n) - mean*mean);
var obj = {n:n, sum:sum, mean:mean, stddev:stddev};
return {n:n, sum:sum, mean:mean, stddev:stddev, hist:hist};
}
 
function reportStats(summary:object):void {
printf("Samples: %d, mean: %f, stddev: %f\n", summary.n, summary.mean, summary.stddev);
var max = Math.max.apply(summary, summary.hist);
for (var i = 0; i < 10; i++) {
printf("%3.1f+ %-70s %5d\n", i * 0.1, 'X'.repeat(70 * summary.hist[i] / max), summary.hist[i]);
}
return;
}
function main() {
LogTest('Starting', args);
switch (typeof(args)) {
case 'string': args = [args]; break;
case 'array': break;
default: args = [];
}
if (self.rootdir === '')
self.rootdir=Info.scriptDir();
 
Math.srand(0);
if (self.samples > 0) reportStats(generateStats(self.samples));
else if (args[0] && parseInt(args[0])) reportStats(generateStats(parseInt(args[0])));
else for (var n of [100, 1000, 10000]) reportStats(generateStats(n));
 
debugger;
LogDebug('Done');
return 0;
}
return main();
}
 
provide(statisticsBasic, 1);
 
if (isMain()) {
if (!Interp.conf('unitTest'))
return runModule(statisticsBasic);
;' statisticsBasic unit-test';
; statisticsBasic();
 
}
 
 
/*
=!EXPECTSTART!=
' statisticsBasic unit-test'
statisticsBasic() ==> Samples: 100, mean: 0.534517, stddev: 0.287124
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 8
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 11
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXX 6
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 10
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 10
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 11
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 8
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 16
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 7
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 13
Samples: 1000, mean: 0.490335, stddev: 0.286562
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 98
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 122
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 85
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 106
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 105
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 101
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 93
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 106
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 98
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 86
Samples: 10000, mean: 0.499492, stddev: 0.287689
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 969
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 992
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1067
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1011
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 973
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1031
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 971
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 999
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 991
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 996
0
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u statisticsBasic.jsi
[PASS] statisticsBasic.jsi</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Printf
{{works with|Julia|0.6}}
 
<lang julia>function hist(numbers)
maxwidth = 50
h = fill(0, 10)
Line 1,974 ⟶ 3,361:
@printf("μ: %8.6f; σ: %8.6f\n", mean(n), std(n))
hist(n)
end</langsyntaxhighlight>
 
{{out}}
Line 2,065 ⟶ 3,452:
Using the "mu" (mean) and "sd" (standard deviation) functions from the
Klong statistics library:
<syntaxhighlight lang="k">
<lang K>
.l("nstat.kg")
bar::{x{x;.d("*")}:*0;.p("")}
Line 2,075 ⟶ 3,462:
plot(1000)
plot(10000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,123 ⟶ 3,510:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val rand = java.util.Random()
Line 2,171 ⟶ 3,558:
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) basicStats(sampleSize)
}</langsyntaxhighlight>
Sample run:
{{out}}
Line 2,237 ⟶ 3,624:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
Line 2,287 ⟶ 3,674:
histogram(#n)
'\r\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 2,356 ⟶ 3,743:
0.9: ++++++++++++++++++++++++++++++++++++++++++++++++++
1.0: ++++++++++++++++++++++++</pre>
 
=={{header|Liberty BASIC}}==
Be aware that the PRNG in LB has a SLIGHT bias.
<lang lb>
call sample 100
call sample 1000
call sample 10000
 
end
 
sub sample n
dim dat( n)
for i =1 to n
dat( i) =rnd( 1)
next i
 
'// show mean, standard deviation
sum =0
sSq =0
for i =1 to n
sum =sum +dat( i)
sSq =sSq +dat( i)^2
next i
print n; " data terms used."
 
mean =sum / n
print "Mean ="; mean
 
print "Stddev ="; ( sSq /n -mean^2)^0.5
 
'// show histogram
nBins =10
dim bins( nBins)
for i =1 to n
z =int( nBins *dat( i))
bins( z) =bins( z) +1
next i
for b =0 to nBins -1
for j =1 to int( nBins *bins( b)) /n *70)
print "#";
next j
print
next b
print
end sub
</lang>
100000 data terms used.
Mean =0.49870232
Stddev =0.28926563
######################################################################
######################################################################
######################################################################
######################################################################
#####################################################################
#####################################################################
#####################################################################
#####################################################################
######################################################################
#####################################################################
 
=={{header|Lua}}==
The standard deviation seems to converge to around 0.28. I expect there's a good reason for this, though it's entirely beyond me.
<langsyntaxhighlight lang="lua">
math.randomseed(os.time())
 
Line 2,475 ⟶ 3,803:
showStats(10 ^ power)
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
The following samples 100 uniformly distributed numbers between 0 and 1:
<langsyntaxhighlight lang="maple">with(Statistics):
X_100 := Sample( Uniform(0,1), 100 );
Mean( X_100 );
StandardDeviation( X_100 );
Histogram( X_100 );</langsyntaxhighlight>
It is also possible to make a procedure that outputs the mean, standard deviation, and a histogram for a given number of random uniformly distributed numbers:
<langsyntaxhighlight lang="maple">sample := proc( n )
local data;
data := Sample( Uniform(0,1), n );
Line 2,493 ⟶ 3,821:
return Statistics:-Histogram( data );
end proc:
sample( 1000 );</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Sample[n_]:= (Print[#//Length," numbers, Mean : ",#//Mean,", StandardDeviation : ",#//StandardDeviation ];
BarChart[BinCounts[#,{0,1,.1}], Axes->False, BarOrigin->Left])&[(RandomReal[1,#])&[ n ]]
Sample/@{100,1 000,10 000,1 000 000} </syntaxhighlight>
 
Sample/@{100,1 000,10 000,1 000 000} </lang>
{{out}}
<pre>100 numbers, Mean : 0.478899, StandardDeviation : 0.322265
Line 2,508 ⟶ 3,835:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> % Initialize
N = 0; S=0; S2 = 0;
binlist = 0:.1:1;
Line 2,527 ⟶ 3,854:
m = S/N; % mean
sd = sqrt(S2/N-mean*mean); % standard deviation
bar(binlist,h)</langsyntaxhighlight>
 
=={{header|NimMiniScript}}==
A little Stats class is defined that can calculate mean and standard deviation for a stream of numbers (of arbitrary size, so yes, this would work for a trillion numbers just as well as for one).
<lang nim>import math, strutils
<syntaxhighlight lang="miniscript">Stats = {}
randomize()
Stats.count = 0
Stats.sum = 0
Stats.sumOfSquares = 0
Stats.histo = null
 
Stats.add = function(x)
self.count = self.count + 1
self.sum = self.sum + x
self.sumOfSquares = self.sumOfSquares + x*x
bin = floor(x*10)
if not self.histo then self.histo = [0]*10
self.histo[bin] = self.histo[bin] + 1
end function
 
Stats.mean = function()
proc sd(ns): auto =
return self.sum / self.count
var sx, sxx = 0.0
end function
for x in ns:
 
sx += x
Stats.stddev = function()
sxx += x * x
m = self.sum / self.count
let sd = if ns.len > 0: sqrt(float(ns.len) * sxx - sx * sx) / float(ns.len)
return sqrt(self.sumOfSquares / self.count - m*m)
else: 0
end function
(sd, sx / float(ns.len))
 
Stats.histogram = function()
for i in self.histo.indexes
print "0." + i + ": " + "=" * (self.histo[i]/self.count * 200)
end for
end function
 
for sampleSize in [100, 1000, 10000]
print "Samples: " + sampleSize
st = new Stats
for i in range(sampleSize)
st.add rnd
end for
print "Mean: " + st.mean + " Standard Deviation: " + st.stddev
st.histogram
end for</syntaxhighlight>
{{out}}
<pre>Samples: 100
Mean: 0.484705 Standard Deviation: 0.276974
0.0: ===================
0.1: =======================
0.2: =================
0.3: =================
0.4: =====================
0.5: ===================
0.6: =========================
0.7: =================
0.8: =====================
0.9: =============
Samples: 1000
Mean: 0.509347 Standard Deviation: 0.298134
0.0: ======================
0.1: =================
0.2: ====================
0.3: =====================
0.4: ===============
0.5: ==================
0.6: =================
0.7: ====================
0.8: =======================
0.9: =====================
Samples: 10000
Mean: 0.499573 Standard Deviation: 0.288983
0.0: ===================
0.1: ====================
0.2: ====================
0.3: ====================
0.4: ===================
0.5: ===================
0.6: ====================
0.7: ====================
0.8: ===================
0.9: ===================</pre>
 
=={{header|Nim}}==
The standard module “stats” provides procedures to compute the statistical moments. It is possible to compute them either on a list of values or incrementally using an object <code>RunningStat</code>. In the following program, we use the first method for the 100 numbers samples and we draw the histogram. For the 1_000, 10_000, 100_000 and 1_000_000 samples, we use the second method which avoids to store the values (but don’t draw the histogram).
<syntaxhighlight lang="nim">import random, sequtils, stats, strutils, strformat
 
proc histogramdrawHistogram(ns: seq[float]) =
var h = newSeq[int](1011)
for n in ns:
let pos = int(n * 10).toInt
inc h[pos]
 
Line 2,551 ⟶ 3,948:
let mx = max(h)
echo ""
for n, icount in h:
echo n.toFloat / 10, ": ",repeatChar repeat('+', int(icount / mx * maxWidth), '+')
echo ""
 
randomize()
for i in [10, 100, 1_000, 10_000, 100_000]:
 
var n = newSeq[float](i)
# First part: compute directly from a sequence of values.
for x in 0..n.high: n[x] = random(1.0)
echo "\n##\n##For ",i,"100 numbers\n##:"
let ns = newSeqWith(100, rand(1.0))
let (sd, mean) = sd(n)
echo &"μ = {ns.mean:.12f} σ = {ns.standardDeviation:.12f}"
echo "sd: ",sd,", mean: ",mean
ns.drawHistogram()
histogram(n)</lang>
 
# Second part: compute incrementally using "RunningStat".
for count in [1_000, 10_000, 100_000, 1_000_000]:
echo &"For {count} numbers:"
var rs: RunningStat
for _ in 1..count:
let n = rand(1.0)
rs.push(n)
echo &"μ = {rs.mean:.12f} σ = {rs.standardDeviation:.12f}"
echo()</syntaxhighlight>
{{out}}
<pre>##For 100 numbers:
μ = 0.481116458247 σ = 0.282937480658
## 10 numbers
##
sd: 0.2738118959385979, mean: 0.4717111448227304
 
0.0: +++++++++++++++++++++++++
0.1: ++++++++++++++++++++++++++
0.2: ++++++++++++++++++++
0.2:
0.3: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.4: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.5: ++++++++++++++++++++++++++++++++
0.5:
0.6: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.7: +++++++++++++++++++++++++++++
0.8: ++++++++++++++++++++++++++++++++
0.8:
0.9: +++++++++++++++++++++++++
1.0: +++++++++++
 
For 1000 numbers:
[...]
μ = 0.502885271083 σ = 0.293185154479
 
For 10000 numbers:
##
μ = 0.496057426121 σ = 0.290222037633
## 100000 numbers
##
sd: 0.2884329643843962, mean: 0.4997598571602153
 
For 100000 numbers:
0.0: ++++++++++++++++++++++++++++++++++++++++++++++++
μ = 0.500358171646 σ = 0.287736290437
0.1: +++++++++++++++++++++++++++++++++++++++++++++++++
 
0.2: ++++++++++++++++++++++++++++++++++++++++++++++++
For 1000000 numbers:
0.3: +++++++++++++++++++++++++++++++++++++++++++++++++
μ = 0.499972729013 σ = 0.288699343364</pre>
0.4: ++++++++++++++++++++++++++++++++++++++++++++++++
0.5: ++++++++++++++++++++++++++++++++++++++++++++++++
0.6: ++++++++++++++++++++++++++++++++++++++++++++++++++
0.7: +++++++++++++++++++++++++++++++++++++++++++++++++
0.8: +++++++++++++++++++++++++++++++++++++++++++++++++
0.9: ++++++++++++++++++++++++++++++++++++++++++++++++</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: main(n)
| l m std i nb |
 
Line 2,613 ⟶ 4,013:
i 0.1 + <<wjp(3, JUSTIFY_RIGHT, 2) " - " <<
StringBuffer new "*" <<n(nb) << cr
] ;</langsyntaxhighlight>
 
{{out}}
Line 2,687 ⟶ 4,087:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<langsyntaxhighlight lang="parigp">mean(v)={
sumvecsum(i=1,#v,v[i])/#v
};
stdev(v,mu="")={
Line 2,707 ⟶ 4,107:
show(100);
show(1000);
show(10000);</langsyntaxhighlight>
 
For versions before 2.4.3, define
<langsyntaxhighlight lang="parigp">rreal()={
my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296))); \\ Current precision
random(2^pr)*1.>>pr
};</langsyntaxhighlight>
and use <code>rreal()</code> in place of <code>random(1.)</code>.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @histogram = (0) x 10;
my $sum = 0;
my $sum_squares = 0;
Line 2,740 ⟶ 4,140:
print "*" x (30 * $histogram[$i] * @histogram/$n); # 30 stars expected per row
print "\n";
}</langsyntaxhighlight>
 
Usage: <pre>perl rand_statistics.pl (number of values)</pre>
Line 2,803 ⟶ 4,203:
0.8 - 0.9 : *******************************
0.9 - 1.0 : *******************************</pre>
 
=={{header|Perl 6}}==
{{Works with|rakudo|2018.03}}
<lang perl6>for 100, 1_000, 10_000 -> $N {
say "size: $N";
my @data = rand xx $N;
printf "mean: %f\n", my $mean = $N R/ [+] @data;
printf "stddev: %f\n", sqrt
$mean**2 R- $N R/ [+] @data »**» 2;
printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N)
for sort @data.classify: (10 * *).Int / 10;
say '';
}</lang>
{{out}}
<pre>size: 100
mean: 0.52518699464629726
stddev: 0.28484207464779548
0.0 ==============================
0.1 ======================================================================
0.2 ===================================
0.3 ==================================================
0.4 ============================================================
0.5 =============================================
0.6 ====================
0.7 ===========================================================================
0.8 ======================================================================
0.9 =============================================
 
size: 1000
mean: 0.51043974182914975
stddev: 0.29146336553431618
0.0 ==============================================
0.1 ==================================================
0.2 ===========================================
0.3 ========================================================
0.4 ===================================================
0.5 =======================================
0.6 ===========================================================
0.7 ====================================================
0.8 ==============================================
0.9 ========================================================
 
size: 10000
mean: 0.50371817503544458
stddev: 0.2900716333092252
0.0 ===================================================
0.1 =================================================
0.2 =============================================
0.3 ====================================================
0.4 ==============================================
0.5 ====================================================
0.6 ================================================
0.7 ===================================================
0.8 ====================================================
0.9 ==================================================</pre>
 
=={{header|Phix}}==
{{trans|CoffeeScript}}
To do a trillion samples, I would change the existing generate loop into an inner 100_000_000 loop that still uses the fast native types, with everything outside that changed to bigatom, and of course add an outer loop which sums into them.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function generate_statistics(integer n)
<span style="color: #008080;">function</span> <span style="color: #000000;">generate_statistics</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence hist = repeat(0,10)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">hist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
atom sum_r = 0,
<span style="color: #004080;">atom</span> <span style="color: #000000;">sum_r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
sum_squares = 0.0
<span style="color: #000000;">sum_squares</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0.0</span>
for i=1 to n do
<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: #000000;">n</span> <span style="color: #008080;">do</span>
atom r = rnd()
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">()</span>
sum_r += r
<span style="color: #000000;">sum_r</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">r</span>
sum_squares += r*r
<span style="color: #000000;">sum_squares</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span>
hist[floor(10*r)+1] += 1
<span style="color: #000000;">hist</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
atom mean = sum_r / n
<span style="color: #004080;">atom</span> <span style="color: #000000;">mean</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sum_r</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">n</span>
atom stddev = sqrt((sum_squares / n) - mean*mean)
<span style="color: #004080;">atom</span> <span style="color: #000000;">stddev</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">((</span><span style="color: #000000;">sum_squares</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">-</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">*</span><span style="color: #000000;">mean</span><span style="color: #0000FF;">)</span>
return {n, mean, stddev, hist}
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">stddev</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hist</span><span style="color: #0000FF;">}</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
procedure display_statistics(sequence x)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">display_statistics</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
atom n, mean, stddev
<span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">stddev</span>
sequence hist
<span style="color: #004080;">sequence</span> <span style="color: #000000;">hist</span>
{n, mean, stddev, hist} = x
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">stddev</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hist</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span>
printf(1,"-- Stats for sample size %d\n",{n})
<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;">"-- Stats for sample size %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
printf(1,"mean: %g\n",{mean})
<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;">"mean: %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mean</span><span style="color: #0000FF;">})</span>
printf(1,"sdev: %g\n",{stddev})
<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;">"sdev: %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">stddev</span><span style="color: #0000FF;">})</span>
for i=1 to length(hist) do
<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;">hist</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer cnt = hist[i]
<span style="color: #004080;">integer</span> <span style="color: #000000;">cnt</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hist</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
string bars = repeat('=',floor(cnt*300/n))
<span style="color: #004080;">string</span> <span style="color: #000000;">bars</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'='</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cnt</span><span style="color: #0000FF;">*</span><span style="color: #000000;">300</span><span style="color: #0000FF;">/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span>
printf(1,"%.1f: %s %d\n",{i/10,bars,cnt})
<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;">"%.1f: %s %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bars</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cnt</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
for n=2 to 5 do
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
display_statistics(generate_statistics(power(10,n+(n=5))))
<span style="color: #000000;">display_statistics</span><span style="color: #0000FF;">(</span><span style="color: #000000;">generate_statistics</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span><span style="color: #0000FF;">))))</span>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre style="float:left; font-size: 10px9px">
-- Stats for sample size 100
mean: 0.530925
Line 2,912 ⟶ 4,259:
1.0: ========================================== 14
</pre>
<pre style="float:left; font-size: 10px9px">
-- Stats for sample size 1000
mean: 0.50576
Line 2,927 ⟶ 4,274:
1.0: ============================== 101
</pre>
<pre style="float:left; font-size: 10px9px">
-- Stats for sample size 10000
mean: 0.498831
Line 2,942 ⟶ 4,289:
1.0: ============================= 999
</pre>
<pre style="font-size: 10px9px">
-- Stats for sample size 1000000
mean: 0.499937
Line 2,960 ⟶ 4,307:
=={{header|PicoLisp}}==
The following has no limit on the number of samples. The 'statistics' function accepts an executable body 'Prg', which it calls repeatedly to get the samples.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(seed (time))
 
Line 2,989 ⟶ 4,336:
(rand 0 (dec 1.0)) )
(prinl) )
</syntaxhighlight>
</lang>
{{out}}
<pre>100 numbers
Line 3,034 ⟶ 4,381:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> stat: procedure options (main); /* 21 May 2014 */
 
stats: procedure (values, mean, standard_deviation);
Line 3,072 ⟶ 4,419:
end;
 
end stat;</langsyntaxhighlight>
{{out}}
<pre>Histogram for 100 values:
<pre>
Histogram for 100 values:
.......
..............
Line 3,089 ⟶ 4,435:
1000 values: mean= 4.97079E-0001 stddev= 1.07871E-0005
10000 values: mean= 4.99119E-0001 stddev= 8.35870E-0005
100000 values: mean= 5.00280E-0001 stddev= 7.88976E-0004 </pre>
</pre>
 
=={{header|PureBasic}}==
{{trans|Liberty BASIC}}
Changes were made from the Liberty BASIC version to normalize the histogram as well as implement a random float function.
<lang purebasic>Procedure.f randomf()
#RNG_max_resolution = 2147483647
ProcedureReturn Random(#RNG_max_resolution) / #RNG_max_resolution
EndProcedure
 
Procedure sample(n)
Protected i, nBins, binNumber, tickMarks, maxBinValue
Protected.f sum, sumSq, mean
Dim dat.f(n)
For i = 1 To n
dat(i) = randomf()
Next
;show mean, standard deviation
For i = 1 To n
sum + dat(i)
sumSq + dat(i) * dat(i)
Next i
PrintN(Str(n) + " data terms used.")
mean = sum / n
PrintN("Mean =" + StrF(mean))
PrintN("Stddev =" + StrF((sumSq / n) - Sqr(mean * mean)))
;show histogram
nBins = 10
Dim bins(nBins)
For i = 1 To n
binNumber = Int(nBins * dat(i))
bins(binNumber) + 1
Next
maxBinValue = 1
For i = 0 To nBins
If bins(i) > maxBinValue
maxBinValue = bins(i)
EndIf
Next
#normalizedMaxValue = 70
For binNumber = 0 To nBins
tickMarks = Int(bins(binNumber) * #normalizedMaxValue / maxBinValue)
PrintN(ReplaceString(Space(tickMarks), " ", "#"))
Next
PrintN("")
EndProcedure
 
If OpenConsole()
sample(100)
sample(1000)
sample(10000)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</lang>
{{out}}
<pre>100 data terms used.
Mean =0.4349198639
Stddev =-0.1744846404
#########################################################
#########################################
################################
#################################################################
################################
#####################################################
######################################################################
################
########################
################
 
 
1000 data terms used.
Mean =0.4960154891
Stddev =-0.1691310555
###############################################################
#######################################################
#############################################################
######################################################################
##########################################################
##############################################################
####################################################################
###############################################################
#############################################################
#####################################################
 
 
10000 data terms used.
Mean =0.5042046309
Stddev =-0.1668083966
##################################################################
################################################################
##################################################################
####################################################################
################################################################
######################################################################
####################################################################
###################################################################
####################################################################
####################################################################</pre>
 
=={{header|Python}}==
The second function, sd2 only needs to go once through the numbers and so can more efficiently handle large streams of numbers.
<langsyntaxhighlight lang="python">def sd1(numbers):
if numbers:
mean = sum(numbers) / len(numbers)
Line 3,236 ⟶ 4,477:
print(' Naive method: sd: %8.6f, mean: %8.6f' % sd1(n))
print(' Second method: sd: %8.6f, mean: %8.6f' % sd2(n))
histogram(n)</langsyntaxhighlight>
 
{{out}}
Line 3,280 ⟶ 4,521:
=={{header|R}}==
The challenge of processing a trillion numbers is generating them in the first place. As the errors below show, allocating 7.5 TB for such a vector is simply impractical. The workaround is to generate them, process individual data points and then discard them. The downside in this case is the time.
<syntaxhighlight lang="r">
<lang R>
#Generate the sets
a = runif(10,min=0,max=1)
Line 3,307 ⟶ 4,548:
cat("Mean of a trillion random values in the range [0,1] : ",mean(runif(10^12,min=0,max=1)))
cat("Standard Deviation of a trillion random values in the range [0,1] : ", sd(runif(10^12,min=0,max=1)))
</syntaxhighlight>
</lang>
Output
<pre>
Line 3,328 ⟶ 4,569:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math (only-in srfi/27 random-real))
Line 3,350 ⟶ 4,591:
(task 1000)
(task 10000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,395 ⟶ 4,636:
0.9- 1: *******************
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" line>for 100, 1_000, 10_000 -> $N {
say "size: $N";
my @data = rand xx $N;
printf "mean: %f\n", my $mean = $N R/ [+] @data;
printf "stddev: %f\n", sqrt
$mean**2 R- $N R/ [+] @data »**» 2;
printf "%.1f %s\n", .key, '=' x (500 * .value.elems / $N)
for sort @data.classify: (10 * *).Int / 10;
say '';
}</syntaxhighlight>
{{out}}
<pre>size: 100
mean: 0.52518699464629726
stddev: 0.28484207464779548
0.0 ==============================
0.1 ======================================================================
0.2 ===================================
0.3 ==================================================
0.4 ============================================================
0.5 =============================================
0.6 ====================
0.7 ===========================================================================
0.8 ======================================================================
0.9 =============================================
 
size: 1000
mean: 0.51043974182914975
stddev: 0.29146336553431618
0.0 ==============================================
0.1 ==================================================
0.2 ===========================================
0.3 ========================================================
0.4 ===================================================
0.5 =======================================
0.6 ===========================================================
0.7 ====================================================
0.8 ==============================================
0.9 ========================================================
 
size: 10000
mean: 0.50371817503544458
stddev: 0.2900716333092252
0.0 ===================================================
0.1 =================================================
0.2 =============================================
0.3 ====================================================
0.4 ==============================================
0.5 ====================================================
0.6 ================================================
0.7 ===================================================
0.8 ====================================================
0.9 ==================================================</pre>
 
=={{header|REXX}}==
Twenty decimal digits are used for the calculations, but only half that (ten digits) are displayed in the output.
<langsyntaxhighlight lang="rexx">/*REXX program generates some random numbers, shows bin histogram, finds mean & stdDev. */
numeric digits 20 /*use twenty decimal digits precision, */
showDigs=digits()%2 /* ··· but only show ten decimal digits*/
Line 3,429 ⟶ 4,726:
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 100 </tt>}}
<pre>
Line 3,522 ⟶ 4,819:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Statistics/Basic
 
Line 3,561 ⟶ 4,858:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,629 ⟶ 4,926:
9
*********************************************************************
</pre>
 
=={{header|RPL}}==
Built-in statistics functions in RPL relies on a specific array named <code>∑DAT</code>, which is automatically generated when the first record is created by the word <code>∑+</code>.
{{works with|Halcyon Calc|4.2.8}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ → n
≪ CL∑ 1 n '''START''' RAND ∑+ '''NEXT'''
MEAN SDEV
{ 10 } 0 CON
1 n '''FOR''' j
∑DAT j { 1 } + GET
10 * 1 + FLOOR DUP2 GET 1 + PUT
'''NEXT'''
{ } 1 10 '''FOR''' j
OVER j GET 3 PICK RNRM / 20 *
"0." j 1 - →STR + "= " + 1 ROT '''START''' "*" + '''NEXT''' +
'''NEXT'''
≫ ≫ ‘<span style="color:blue">TASK</span>’ STO
|
<span style="color:blue">TASK</span> ''( #samples → statistics... ) ''
Generate and store samples in the statistics database
The easy part of the task
Create a 10-cell vector
Scan the database
Read the nth record
Increment the related cell
Generate histogramme
RNRM returns the max value of the 10-cell vector
|}
1000 <span style="color:blue">TASK</span>
{{out}}
<pre>
4: 0.492756012687
3: 0.29333176137
2: [ 120 100 90 86 112 113 90 87 97 105 ]
1: { "0.0= ********************"
"0.1= ****************"
"0.2= ***************"
"0.3= **************"
"0.4= ******************"
"0.5= ******************"
"0.6= ***************"
"0.7= **************"
"0.8= ****************"
"0.9= *****************" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def generate_statistics(n)
sum = sum2 = 0.0
hist = Array.new(10, 0)
Line 3,651 ⟶ 5,002:
end
 
[100, 1000, 10000].each {|n| generate_statistics n}</langsyntaxhighlight>
 
{{out}}
<pre style="height: 40ex; overflow: scroll">size: 100
size: 100
mean: 0.5565132836634081
stddev: 0.30678831716883026
Line 3,695 ⟶ 5,044:
0.7:===================================================================
0.8:===================================================================
0.9:=================================================================</pre>
</pre>
 
 
=={{header|Run BASIC}}==
<lang runbasic>call sample 100
call sample 1000
call sample 10000
end
sub sample n
dim samp(n)
for i =1 to n
samp(i) =rnd(1)
next i
' calculate mean, standard deviation
sum = 0
sumSq = 0
for i = 1 to n
sum = sum + samp(i)
sumSq = sumSq + samp(i)^2
next i
print n; " Samples used."
mean = sum / n
print "Mean = "; mean
print "Std Dev = "; (sumSq /n -mean^2)^0.5
'------- Show histogram
bins = 10
dim bins(bins)
for i = 1 to n
z = int(bins * samp(i))
bins(z) = bins(z) +1
next i
for b = 0 to bins -1
print b;" ";
for j = 1 to int(bins *bins(b)) /n *70
print "*";
next j
print
next b
print
end sub</lang>
<pre style="height: 40ex; overflow: scroll">
100 Samples used.
Mean = 0.514312738
Std Dev = 0.291627558
0 **************************************************************************************************
1 **********************************************************************
2 *********************
3 ***********************************
4 ***************************************************************
5 *******************************************************************************************
6 ***********************************************************************************************************************
7 **********************************************************************
8 ***************************************************************
9 **********************************************************************
 
1000 Samples used.
Mean = 0.495704208
Std Dev = 0.281389168
0 ***************************************************************
1 ********************************************************************
2 **************************************************************************
3 *******************************************************************************
4 **************************************************************************
5 **********************************************************************
6 ************************************************************************
7 **********************************************************************
8 ********************************************************
9 **********************************************************************
 
10000 Samples used.
Mean = 0.493594211
Std Dev = 0.288635912
0 ************************************************************************
1 ************************************************************************
2 **********************************************************************
3 *******************************************************************
4 **********************************************************************
5 ************************************************************************
6 ************************************************************************
7 *****************************************************************
8 **********************************************************************
9 ******************************************************************
</pre>
 
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">#![feature(iter_arith)]
extern crate rand;
 
Line 3,857 ⟶ 5,117:
print_histogram(40, &data);
}
}</langsyntaxhighlight>
{{out}}
<pre> Statistics for sample size 1000
Line 3,903 ⟶ 5,163:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def mean(a:Array[Double])=a.sum / a.size
def stddev(a:Array[Double])={
val sum = a.fold(0.0)((a, b) => a + math.pow(b,2))
Line 3,923 ⟶ 5,183:
printHist(a)
println
}</langsyntaxhighlight>
{{out}}
<pre>100 numbers
Line 3,972 ⟶ 5,232:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func generate_statistics(n) {
var(sum=0, sum2=0);
var hist = 10.of(0);
 
 
n.times {
var r = 1.rand;
sum += r;
sum2 += r**2;
hist[10*r] += 1;
}
 
 
var mean = sum/n;
var stddev = Math.sqrt(sum2/n - mean**2);
 
 
say "size: #{n}";
say "mean: #{mean}";
say "stddev: #{stddev}";
 
 
var max = hist.max;
for i in ^hist.range.each {|i|
printf("%.1f:%s\n", 0.1*i, "=" * 70*hist[i]/max);
}
print "\n";
}
 
 
[100, 1000, 10000].each {|n| generate_statistics(n) }</langsyntaxhighlight>
{{out}}
<pre style="height: 40ex; overflow: scroll">
size: 100
mean: 0.539719181395696620109634051345884432579835159541
mean: 0.4585051431752446588
stddev: 0.283883840711089795862044996985935095942987013707
stddev: 0.2870559459562831101619581273667538623484
0.0:=================================================================
0.1:==================================================
0.2:======================================================================
0.3:======================================================================
0.4:==========================================================
0.5:======================================================================
0.6:==================================================
0.7:======================================================================
0.8:======================================================================
0.9:================================================================
 
size: 1000
mean: 0.509607463325018405029035982604757578351179500375
mean: 0.51292239343467439552
stddev: 0.291051486526422985516729469185300756396357843712
stddev: 0.2832968595790956540009121237087699143503
0.0:==========================================================
0.1:========================================================
0.2:================================================================
0.3:========================================================
0.4:======================================================================
0.5:=====================================================================
0.6:===============================================================
0.7:===========================================================
0.8:==========================================================
0.9:======================================================================
 
size: 10000
mean: 0.501370967820671948202377775772729161752514666335
mean: 0.49883638025449614521145
stddev: 0.288601021921015908441703525737039264149088197141
stddev: 0.2898083000452161646017460189689302069547
0.0:====================================================================
0.1:====================================================================
0.2:======================================================================
0.3:=================================================================
0.4:======================================================================
0.5:=================================================================
0.6:===============================================================
0.7:===================================================================
0.8:==================================================================
0.9:====================================================================
</pre>
 
Line 4,047 ⟶ 5,307:
For a uniform distribution on [0,1], the mean is 1/2 and the variance is 1/12 (hence the standard deviation is 0.28867513). With a large sample, one can check the convergence to these values.
 
<langsyntaxhighlight lang="stata">. clear all
. set obs 100000
number of observations (_N) was 0, now 100,000
Line 4,056 ⟶ 5,316:
-------------+---------------------------------------------------------
x | 100,000 .4991874 .2885253 1.18e-06 .9999939
. hist x</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc stats {size} {
set sum 0.0
Line 4,085 ⟶ 5,345:
stats 1000
puts ""
stats 10000</langsyntaxhighlight>
{{out}}
<pre>
Line 4,133 ⟶ 5,393:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Base 1
Private Function mean(s() As Variant) As Double
mean = WorksheetFunction.Average(s)
Line 4,157 ⟶ 5,417:
Debug.Print
Next e
End Sub</langsyntaxhighlight>{{out}}
<pre>sample size 100 mean 0,472405961751938 standard deviation 0,260463885857138
0,00-0,10 XXXXXX
Line 4,193 ⟶ 5,453:
0,80-0,90 XXXXXXXXXX
0,90-1,00 XXXXXXXXXX</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import rand
import math
 
fn main() {
sample(100)
sample(1000)
sample(10000)
}
fn sample(n int) {
// generate data
mut d := []f64{len: n}
for i in 0.. d.len {
d[i] = rand.f64()
}
// show mean, standard deviation
mut sum, mut ssq := f64(0), f64(0)
for s in d {
sum += s
ssq += s * s
}
println("$n numbers")
m := sum / f64(n)
println("Mean: $m")
println("Stddev: ${math.sqrt(ssq/f64(n)-m*m)}")
// show histogram
mut h := []int{len: 10}
for s in d {
h[int(s*10)]++
}
for c in h {
println("*".repeat(c*205/int(n)))
}
println('')
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
100 numbers
Mean: 0.4673526451482236
Stddev: 0.27590441169077806
****************
********************************
********************
********************
************
******************************
************
**********************************
**********
**************
 
1000 numbers
Mean: 0.4906097518067266
Stddev: 0.28686496927912264
********************
*********************
**********************
*********************
********************
*****************
*******************
*********************
********************
******************
 
10000 numbers
Mean: 0.5012521647492316
Stddev: 0.2883488134311142
********************
********************
*********************
******************
*********************
*********************
********************
********************
********************
********************
</pre>
Or use standard math.stats module
<syntaxhighlight lang="text">import rand
import math.stats
 
fn main() {
sample(100)
sample(1000)
sample(10000)
}
fn sample(n int) {
// generate data
mut d := []f64{len: n}
for i in 0.. d.len {
d[i] = rand.f64()
}
// show mean, standard deviation
println("$n numbers")
m := stats.mean<f64>(d)//sum / f64(n)
println("Mean: $m")
println("Stddev: ${stats.sample_stddev<f64>(d)}")
// show histogram
mut h := []int{len: 10}
for s in d {
h[int(s*10)]++
}
for c in h {
println("*".repeat(c*205/int(n)))
}
println('')
}</syntaxhighlight>
{{out}}
Similar to above
 
=={{header|Wren}}==
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "random" for Random
import "./math" for Nums
 
var r = Random.new()
for (i in [100, 1000, 10000]) {
var a = List.filled(i, 0)
for (j in 0...i) a[j] = r.float()
System.print("For %(i) random numbers:")
System.print(" mean = %(Nums.mean(a))")
System.print(" std/dev = %(Nums.popStdDev(a))")
var scale = i / 100
System.print(" scale = %(scale) per asterisk")
var sums = List.filled(10, 0)
for (e in a) {
var f = (e*10).floor
sums[f] = sums[f] + 1
}
for (j in 0..8) {
sums[j] = (sums[j] / scale).round
System.print(" 0.%(j) - 0.%(j+1): %("*" * sums[j])")
}
sums[9] = 100 - Nums.sum(sums[0..8])
System.print(" 0.9 - 1.0: %("*" * sums[9])\n")
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
For 100 random numbers:
mean = 0.51850420177277
std/dev = 0.28837198153139
scale = 1 per asterisk
0.0 - 0.1: ***********
0.1 - 0.2: ******
0.2 - 0.3: **********
0.3 - 0.4: *********
0.4 - 0.5: *********
0.5 - 0.6: ***********
0.6 - 0.7: ************
0.7 - 0.8: ***********
0.8 - 0.9: ********
0.9 - 1.0: *************
 
For 1000 random numbers:
mean = 0.50563060529132
std/dev = 0.28829500547546
scale = 10 per asterisk
0.0 - 0.1: *********
0.1 - 0.2: **********
0.2 - 0.3: **********
0.3 - 0.4: **********
0.4 - 0.5: ********
0.5 - 0.6: ***********
0.6 - 0.7: ***********
0.7 - 0.8: *********
0.8 - 0.9: *********
0.9 - 1.0: *************
 
For 10000 random numbers:
mean = 0.5037035497178
std/dev = 0.28753708198548
scale = 100 per asterisk
0.0 - 0.1: **********
0.1 - 0.2: **********
0.2 - 0.3: **********
0.3 - 0.4: **********
0.4 - 0.5: **********
0.5 - 0.6: **********
0.6 - 0.7: **********
0.7 - 0.8: **********
0.8 - 0.9: **********
0.9 - 1.0: **********
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
func real Mean(X, N);
real X; int N;
real Sum; int I;
[Sum:= 0.;
for I:= 0 to N-1 do
Sum:= Sum + X(I);
return Sum/float(N);
];
 
func real StdDev(X, N, Mean);
real X; int N; real Mean;
real Sum; int I;
[Sum:= 0.;
for I:= 0 to N-1 do
Sum:= Sum + sq(X(I) - Mean);
return sqrt(Sum/float(N));
];
 
int Size, J, K, Sums(10), Scale;
real A, M;
[Size:= 100;
repeat A:= RlRes(Size);
for J:= 0 to Size-1 do
A(J):= float(Ran(1_000_000)) / 1e6;
Print("For %d random numbers:\n", Size);
M:= Mean(A, Size);
Print(" mean = %1.9f\n", M);
Print(" stddev = %1.9f\n", StdDev(A, Size, M));
Scale:= Size / 100;
Print(" scale = %d per asterisk\n", Scale);
for J:= 0 to 10-1 do Sums(J):= 0;
for J:= 0 to Size-1 do
[K:= fix(Floor(A(J)*10.));
Sums(K):= Sums(K)+1;
];
for J:= 0 to 8 do
[Sums(J):= Sums(J) / Scale;
Print(" 0.%d - 0.%d: ", J, J+1);
for K:= 1 to Sums(J) do ChOut(0, ^*);
CrLf(0);
];
Print(" 0.9 - 1.0: ");
for K:= 1 to Sums(9)/Scale do ChOut(0, ^*);
CrLf(0); CrLf(0);
Size:= Size * 10;
until Size > 10_000;
]</syntaxhighlight>
{{out}}
<pre>
For 100 random numbers:
mean = 0.516471700
stddev = 0.286590092
scale = 1 per asterisk
0.0 - 0.1: *********
0.1 - 0.2: ***********
0.2 - 0.3: ********
0.3 - 0.4: ********
0.4 - 0.5: **************
0.5 - 0.6: ***
0.6 - 0.7: **********
0.7 - 0.8: ******************
0.8 - 0.9: *********
0.9 - 1.0: **********
 
For 1000 random numbers:
mean = 0.485343800
stddev = 0.287769421
scale = 10 per asterisk
0.0 - 0.1: **********
0.1 - 0.2: ***********
0.2 - 0.3: *********
0.3 - 0.4: ***********
0.4 - 0.5: *********
0.5 - 0.6: ***********
0.6 - 0.7: ********
0.7 - 0.8: *********
0.8 - 0.9: ********
0.9 - 1.0: **********
 
For 10000 random numbers:
mean = 0.501502304
stddev = 0.288991280
scale = 100 per asterisk
0.0 - 0.1: *********
0.1 - 0.2: **********
0.2 - 0.3: **********
0.3 - 0.4: *********
0.4 - 0.5: *********
0.5 - 0.6: *********
0.6 - 0.7: **********
0.7 - 0.8: **********
0.8 - 0.9: **********
0.9 - 1.0: **********
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn mean(ns) { ns.sum(0.0)/ns.len() }
fcn stdDev(ns){
m:=mean(ns); (ns.reduce('wrap(p,n){ x:=(n-m); p+x*x },0.0)/ns.len()).sqrt()
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">reg ns;
foreach n in (T(100,1000,10000)){
ns=(0).pump(n,List,(0.0).random.fp(1.0));
Line 4,206 ⟶ 5,759:
n:=ns.filter('wrap(x){ r<=x<(r+0.1) }).len();
println("%.2f..%.2f:%4d%s".fmt(r,r+0.1,n,"*"*(n/20)));
}</langsyntaxhighlight>
(0.0).random(1.0) generates a [uniform] random number between 0 (inclusive) and 1 (exclusive).
{{out}}
Line 4,225 ⟶ 5,778:
</pre>
For the extra credit, pretend we have a device that spews random numbers in the range [0..1) forever. We connect this device to a measuring device that calculates mean and std deviation, printing results on a regular basis.
<langsyntaxhighlight lang="zkl">var pipe=Thread.Pipe(); // used to connect the two threads
fcn{ while(1){ pipe.write((0.0).random(1.0)) } }.launch(); // generator
fcn{ // consumer/calculator
Line 4,237 ⟶ 5,790:
}.launch();
 
Atomic.sleep(60*60); // wait because exiting the VM kills the threads</langsyntaxhighlight>
{{out}}
<pre>
9,477

edits