Statistics/Normal distribution: Difference between revisions

m
m (→‎{{header|REXX}}: changed font size to 75%.)
m (→‎{{header|Wren}}: Minor tidy)
 
(27 intermediate revisions by 17 users not shown)
Line 4:
 
;The task:
# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and stddevstandard deviation, and show thea histogram hereof the data.
# Mention any native language support for the generation of normally distributed random numbers.
 
Line 13:
 
=={{header|C}}==
<syntaxhighlight lang="c">/*
<lang C>/*
* RosettaCode example: Statistics/Normal distribution in C
*
Line 139:
}
return EXIT_FAILURE;
}</langsyntaxhighlight>
{{out}}
<pre>mean = 0.000477941, stddev = 0.999945
Line 208:
=={{header|C sharp|C#}}==
{{libheader|Math.Net}}
<langsyntaxhighlight lang="csharp">using System;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics;
Line 239:
RunNormal(10000);
}
}</langsyntaxhighlight>
{{out}}
<pre>Sample size: 100
Line 285:
=={{header|C++}}==
showing features of C++11 here
<langsyntaxhighlight lang="cpp">#include <random>
#include <map>
#include <string>
Line 315:
}
return 0 ;
}</langsyntaxhighlight>
Output:
<pre>The mean of the distribution is 1 , the standard deviation 1 !
Line 347:
=={{header|D}}==
This uses the Box-Muller method as in the Go entry, and the module from the Statistics/Basic. A ziggurat-based normal generator for the Phobos standard library is in the works.
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.math, std.range, std.algorithm,
statistics_basic;
 
Line 373:
writefln("Mean: %8.6f, SD: %8.6f\n", data.meanStdDev[]);
data.map!q{ max(0.0, min(0.9999, a / 3 + 0.5)) }.showHistogram01;
}</langsyntaxhighlight>
{{out}}
<pre>Mean: 0.000528, SD: 0.502245
Line 387:
0.8: ******
0.9: *</pre>
 
=={{header|EDSAC order code}}==
<syntaxhighlight lang="edsac">
[Normal distribution for Rosetta Code
EDSAC program, Initial Orders 2]
 
[==================================================================================
Uses an accept-reject method, which requires only logarithms (no trig functions).
Let u, v be independent uniform variates in (0, 1). Let x = -ln(u), y = -ln(v).
Accept x iff (x - 1)^2 <= 2y. If x is accepted, negate it with probability 1/2.
Then x is normally distributed with mean 0 and standard deviation 1.
The algorithm is modified for this EDSAC version:
(1) Uses EDSAC library subroutine L1 to calculate (1/32)log_2() rather than ln()
(2) Since real numbers on EDSAC are restricted to the interval [-1, 1), scales so
that the standard deviation is 1/4, and reject values >= 4 s.d. from the mean.
In the histogram, counts are divided by 16, with rounding.
On the EDSAC PC simulator, takes 2.75 EDSAC hours to find 4096 normal variates.
[=================================================================================]
 
[Arrange the storage]
T46K P70F [N parameter: library subroutine P1 to print +ve fraction]
T47K P200F [M parameter: main routine and dependent subroutines]
T49K P92F [L parameter: library subroutine L1 to calculate log_2]
T51K P130F [G parameter: generator for pseudo-random numbers]
T52K P168F [A parameter: library subroutine S2 for square root]
T54K P190F [C parameter: constants read in by library subroutine R9]
 
[Library subroutine R9, reads non-negative integers at load time.
Fractions can be read by converting to integers (multiply by 2^34).
15 locations, must be loaded at location 56.]
T56KGKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@
 
[Library subroutine M3, prints header at load time.
M3 and header are then overwritten.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*MEAN#!K0BL!!*SD#!K0M25BL@&#..PZ
 
[========================== C parameter ==========================]
[Tell R9 where to store integers read from tape]
E69K T#C ['T m D' in WWG, but this also works]
[List of integers; separated by F; end list with #TZ]
123456789F5F1549082005F11908177887F858993#TZ
[0] [seed for random number generator]
[2] [minimum argument for library subroutine L1]
[4] [1/(16*ln(2)) for accept-reject]
[6] [ln(2) for scaling standard deviation]
[8] [0.00005 for rounding in print routine]
 
[========================== M parameter ==========================]
E25K TM GK
[0] P4096F [number of data, in address field; code below assumes 4096]
[1] PF [negative count of data]
[2] PF [worlspace, low word]
[3] PF [workspace, high word]
[4] PF PF [auxiliary for accept-reject algorithm]
[6] PF PF [sum of value/count, for mean]
[8] PF PF [sum of value^2/count, for variance]
[10] PFPFPFPFPFPFPFPFPFPFPFPFPFPFPFPF [16 bins for histogram]
[26] CF [11110...0 binary, to isolate bin index; also prints colon]
[27] A10@ [A order for bin{0}]
[28] AF [A order for bin{16}]
[29] P8F [8 in address field]
[30] MF [subtract from A order to make T order; also prints dot]
[31] WF [1/8]
[32] FF [-15/16, mid value of histogram bin{0}]
[33] PF [mid value of current bin]
[Teleprinter]
[34] #F [set figures mode]
[35] PF
[36] AF [minus (in figures mode)]
[37] !F [space]
[38] @F [carriage return]
[39] &F [line feed]
[Enter with acc = 0]
[40]
S@ T1@ [store negated data count in address field]
A#C T4D [copy seed to 4D for PRNG]
[44] A44@ GG [initialize PRNG]
T6#@ T8#@ [clear sum and sum of squares]
O34@ [set teleprinter to figures]
[Start of loop to generate normal variates]
[49] TF [clear acc]
[Calculate and store logarithms of uniform variates]
[50] A50@ G176@ SD T2#@ [corresponds to x = -ln(u)]
[54] A54@ G176@ SD T4#@ [corresponds to y = -ln(v)]
[Accept or reject]
A4#C RD [acc := (1/32*ln(2))]
S2#@ [subtract x]
TD HD ND [acc := negated square]
H4#C V4#@ [add 2*(auxiliary value)]
G49@ [reject if result < 0]
[First log is accepted; multiply by 8*ln(2) so that s.d. becomes 0.25]
[Reject values outside (-1,1) (that is >= 4 s.d. from mean, unlikely)]
T6F [clear acc]
H6#C V2#@ [times ln(2)]
S31@ E49@ [if product >= 1/8 (unlikely) reject and try again]
A31@ [restore acc after test]
L2F [shift 3 left to complete scaling]
YF T2#@ [round and store back]
[Finally change sign with probability 1/2]
T6F T4D A2F T4F [pass range = 2 to PRNG]
[80] A80@ G1G [call PRNG, 0 or 1 returned in 0D]
SD E87@ [don't change sign if 0D = 0]
T6F S2#@ T2#@ [change sign, so value < 0]
[87] [Here with acc = 0.]
[To print the values, replace the following jump with a no-op (X F)]
E94@
A2#@ TD [pass abs(value) to print routine]
[90] A90@ G191@
O38@ O39@ [print CR, LF]
[94] A2#@ R1024F YF [load value, divide by count, round]
A6#@ T6#@ [update sum]
H2#@ V2#@ R1024F YF
A8#@ T8#@ [update sum of squares]
[Inc count in appropriate bin]
H26@ [mult reg := mask to isolate bin index]
C3@ [acc := top 4 bits of value]
R1024F [12 right, get bin -8..7 in address field]
A29@ [add 8 to address, bin index now 0..15]
A27@ [make A order for bin]
U113@ [plant in code]
S30@ [convert to T order]
T115@ [plant in code]
[113] AF [(planted) acc := count in bin]
A2F [inc by 1 in address field]
[115] TF [(planted) store updated bin count]
A1@ A2F U1@ [inc negative count of variates]
G49@ [loop till got required number]
[Print mean and standard deviation]
A6#@ TD [pass mean to print subroutine]
[122] A122@ G191@
O37@ O37@ O37@ [print spaces]
A8#@ H6#@
N6#@ T4D [calc variance, pass to square root s/r]
[131] A131@ GA [4D := standard deviation]
A4D U8#@ TD [pass to print subroutine]
[136] A136@ G191@ [print s.d.]
O38@ O39@ O38@ O39@ [print CR, LF twice]
[Print histogram]
A29@ LD A27@ [make A order for exclusive end bin]
T28@ [store as test for end]
A32@ T33@ [initialize mid-value of bin]
A27@ [A order for bin{0}]
[149] T158@ [loop: plant A order for current bin]
TD A33@ U1F [0D = mid-value of bin, extended to 35 bits]
A31@ T33@ [update mid-value for next time]
[155] A155@ G191@ [print mid-value]
O26@ [print colon]
[158] AF [(planted) load number of hits in address field]
A29@ [add 8 for rounding]
R4F [divide by 16]
E163@ [jump to middle of loop]
[162] O175@ [print plus sign]
[163] S2F E162@ [loop till printed enough plus signs]
O38@ O39@ [print CR, LF]
TF [clear acc]
A158@ A2F [make A order for next bin]
S28@ [compare with end order]
E174@ [exit if no more bins]
A28@ [restore acc after test]
G149@ [loop back (A order is negative)]
[174] O34@ [dummy character to flush print buffer]
[175] ZF [halt program; also serves as plus sign]
 
[Subroutine of main routine. Sets 0D := (1/32)log_2 of uniform variate]
[176] A3F T188@ [plant return link as usual]
[178] T4D [pass range = 0 to PRNG]
[179] A179@ G1G [0D := uniform variate]
AD S2#C [test for too small (unlikely)]
G189@ [jump to try again if so]
A2#C T6D [OK, pass uniform variate to logarithm subroutine]
[186] A186@ GL [0D := logarithm]
[188] ZF [(planted) return to caller]
[189] TF E178@ [if failed, clear acc and try again]
 
[Subroutine of main routine; prints signed fraction in 0D to 4 decimals.]
[Wrapper for library subroutine P1; adds sign, rounding, layout.]
[191] A3F T207@ [plant return link as usual]
AD G197@ [acc := value, jump if < 0]
O37@ E200@ [print space, jump to common code]
[197] O36@ [value < 0, print minus]
TD SD [acc := abs(valus)]
[200] A8#C TD [add 0.00005 for rounding, pass to P1 in 0D]
O35@ O30@ [print '0.']
[204] A204@ GN P4F [call P1 to print 5 decimals]
[207] ZF [(planted) jump back to caller]
 
[========================== G parameter ==========================]
[Linear congruential generator, same algorithm as Delphi 7 LCG.]
[38 storage locations.]
[Initialize: Call 0G with 35-bit seed in 4D.]
[Input: Call 1G with 35-bit range in 4D.]
[Output: if range > 0, 0D := random 35-bit integer in 0..(range - 1).]
[if range = 0, 0D := random 35-bit real in [0, 1)]
E25K TG
GKG10@G15@T2#ZPFT2ZI514DP257FT4#ZPFT4ZPDPFT6#ZPFT6ZPFRFA6#@S4#@
T6#@E25FE8ZPFT8ZPFPFA3FT14@A4DT8#@ZFA3FT37@H2#@V8#@L512FL512FL1024F
A4#@T8#@H6#@C8#@T8#@S4DG32@TDA8#@E35@H4DTDV8#@L1FTDZF
 
[==================== Library subroutines ============================]
E25K TL
[L1: Logarithm to base 2.]
[0D := (1/32)*log_2(6D), provided 6D > 2^(-32)]
[38 storage locations; working positions 4D and 8F.]
GKA3FT33@E11@IFP1024FP512FA3@LDT6DADS4@TDS3@A6DG6@T8FS5@T4D
H6DV6DS3@E34@A3@LDYFT6DA4DADTDA4DRDYFG17@EFA3@YFT6DE29@
 
E25K TN
[P1: Print non-negative fraction in 0D, without layout or rounding]
[21 storage locations.]
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
 
E25K TA
[S2: square root.]
[Closed: 22 storage locations, working position 0D.]
[Forms sqrt( C(4D)) where C(4D) > 0, and places result in 4D.]
GKA3FT20@A4DS9@A6@UDHDR1FS21@TDN4DRDA4DYFT4DVDTDVDYFG5@EFSF
 
[======================= M parameter again ======================]
E25K TM GK
E40Z [define entry point]
PF [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
MEAN (0?) SD (0.25?)
-0.0015 0.2488
 
-0.9375:
-0.8125:+
-0.6875:++
-0.5625:++++
-0.4375:+++++++++++
-0.3125:++++++++++++++++++++++
-0.1875:++++++++++++++++++++++++++++++++++++++++
-0.0625:++++++++++++++++++++++++++++++++++++++++++++++++
0.0625:++++++++++++++++++++++++++++++++++++++++++++++++++
0.1875:++++++++++++++++++++++++++++++++++++++++
0.3125:+++++++++++++++++++++++
0.4375:+++++++++++
0.5625:++++
0.6875:+
0.8125:
0.9375:
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Statistics do
def normal_distribution(n, w\\5) do
{sum, sum2, hist} = generate(n, w)
Line 418 ⟶ 663:
Enum.each([100,1000,10000], fn n ->
Statistics.normal_distribution(n)
end)</langsyntaxhighlight>
 
{{out}}
Line 518 ⟶ 763:
2.4: ==
2.6: =
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<syntaxhighlight lang="factor">USING: assocs formatting kernel math math.functions
math.statistics random sequences sorting ;
 
2,000,000 [ 0 1 normal-random-float ] replicate ! make data set
dup [ mean ] [ population-std ] bi ! calculate and show
"Mean: %f\nStdev: %f\n\n" printf ! mean and stddev
 
[ 10 * floor 10 / ] map ! map data to buckets
histogram >alist [ first ] sort-with ! create histogram sorted by bucket (key)
dup values supremum ! find maximum count
[
[ /f 100 * >integer ] keepd ! how big should this histogram bar be?
[ [ CHAR: * ] "" replicate-as ] dip ! make the bar
"% 5.2f: %s %d\n" printf ! print a line of the histogram
] curry assoc-each</syntaxhighlight>
{{out}}
<pre style="font-size:80%; height: 120ex; overflow: scroll">
Mean: 0.000798
Stdev: 1.000549
 
-4.90: 2
-4.80: 1
-4.70: 1
-4.60: 3
-4.50: 3
-4.40: 6
-4.30: 15
-4.20: 13
-4.10: 16
-4.00: 42
-3.90: 62
-3.80: 68
-3.70: 98
-3.60: 145
-3.50: 205
-3.40: 311
-3.30: 379
-3.20: 580
-3.10: 739
-3.00: * 1002
-2.90: * 1349
-2.80: ** 1893
-2.70: *** 2499
-2.60: **** 3211
-2.50: ***** 4035
-2.40: ****** 5141
-2.30: ******* 6392
-2.20: ********* 7869
-2.10: ************ 9780
-2.00: ************** 11787
-1.90: ****************** 14483
-1.80: ********************* 17183
-1.70: ************************* 20387
-1.60: ****************************** 24049
-1.50: ********************************** 27555
-1.40: **************************************** 32153
-1.30: ********************************************* 36707
-1.20: *************************************************** 40921
-1.10: ********************************************************* 45928
-1.00: *************************************************************** 50707
-0.90: ********************************************************************* 55697
-0.80: *************************************************************************** 60377
-0.70: ******************************************************************************** 64358
-0.60: ************************************************************************************ 67928
-0.50: ***************************************************************************************** 71911
-0.40: ********************************************************************************************* 75054
-0.30: ************************************************************************************************ 77073
-0.20: ************************************************************************************************** 78768
-0.10: *************************************************************************************************** 79732
0.00: **************************************************************************************************** 79952
0.10: *************************************************************************************************** 79412
0.20: ************************************************************************************************ 77511
0.30: ********************************************************************************************* 74487
0.40: ****************************************************************************************** 72250
0.50: ************************************************************************************** 68789
0.60: ******************************************************************************** 64408
0.70: *************************************************************************** 60122
0.80: ********************************************************************* 55619
0.90: *************************************************************** 50869
1.00: ********************************************************* 45883
1.10: **************************************************** 41586
1.20: ********************************************** 37145
1.30: *************************************** 31715
1.40: ********************************** 27779
1.50: ****************************** 24270
1.60: ************************* 20516
1.70: ********************* 17221
1.80: ***************** 14344
1.90: ************** 11789
2.00: ************ 9796
2.10: ********* 7922
2.20: ******* 6331
2.30: ****** 5138
2.40: ***** 4044
2.50: *** 3065
2.60: ** 2397
2.70: ** 1846
2.80: * 1462
2.90: * 1001
3.00: 765
3.10: 587
3.20: 393
3.30: 299
3.40: 197
3.50: 132
3.60: 100
3.70: 74
3.80: 59
3.90: 32
4.00: 29
4.10: 12
4.20: 15
4.30: 6
4.40: 3
4.50: 4
4.60: 3
4.70: 2
4.80: 1
</pre>
 
Line 523 ⟶ 890:
{{works with|Fortran|95 and later}}
Using the Marsaglia polar method
<langsyntaxhighlight lang="fortran">program Normal_Distribution
implicit none
 
Line 571 ⟶ 938:
end do
end program</langsyntaxhighlight>
{{out}}
<pre>
Line 646 ⟶ 1,013:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const pi As Double = 3.141592653589793
Line 732 ⟶ 1,099:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
Sample output:
{{out}}
Line 807 ⟶ 1,174:
=={{header|Go}}==
Box-Muller method shown here. Go has a normally distributed random function in the standard library, as shown in the Go [[Random numbers]] solution. It uses the ziggurat method.
<langsyntaxhighlight lang="go">package main
 
import (
Line 850 ⟶ 1,217:
fmt.Println(strings.Repeat("*", p/scale))
}
}</langsyntaxhighlight>
Output:
<pre>
Line 867 ⟶ 1,234:
*
</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Map (Map, empty, insert, findWithDefault, toList)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
Line 928 ⟶ 1,296:
main = do
runTest 1000
runTest 2000000</langsyntaxhighlight>
 
{{out}}
Line 1,100 ⟶ 1,468:
4.90: 1
</pre>
 
=={{header|J}}==
'''Solution'''
<langsyntaxhighlight lang="j">runif01=: ?@$ 0: NB. random uniform number generator
rnorm01=. (2 o. 2p1 * runif01) * [: %: _2 * ^.@runif01 NB. random normal number generator (Box-Muller)
 
mean=: +/ % # NB. mean
stddev=: (<:@# %~ +/)&.:*:@(- mean) NB. standard deviation
histogram=: <:@(#/.~)@(i.@#@[ , I.)</langsyntaxhighlight>
'''Example Usage'''
<langsyntaxhighlight lang="j"> DataSet=: rnorm01 1e5
(mean , stddev) DataSet
0.000781667 1.00154
require 'plot'
plot (5 %~ i: 25) ([;histogram) DataSet</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.Math.*;
import static java.util.Arrays.stream;
import java.util.Locale;
Line 1,195 ⟶ 1,564:
.toArray());
}
}</langsyntaxhighlight>
<pre>Mean: -0.001870, SD: 0.500539
0.0: **
Line 1,207 ⟶ 1,576:
0.8: *******
0.9: **</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Works with gojq, the Go implementation of jq''' (*)
 
Since jq does not have a built-in PRNG, this entry uses an external source
for entropy. For the sake of illustration, we will use /dev/urandom
as follows:
cat /dev/urandom | tr -cd '0-9' | fold -w 10 |
jq -nRr -f normal-distribution.jq
 
To save space, the function that generates the sample does not retain the observations, and for
simplicity, computes the sum of squared observations on the
assumption that overflow will not be an an issue, which is
reasonable as jq arithmetic uses IEEE 754 64-bit numbers.
 
(*) gojq requires an enormous amount of memory to complete the task for N=100,000,
and takes about 20 times longer.
'''Preliminaries'''
<syntaxhighlight lang="jq"># Pretty print a number to facilitate alignment of the decimal point.
# Input: a number without an exponent
# Output: a string holding the reformatted number so that there are at least `left` characters
# to the left of the decimal point, and exactly `right` characters to its right.
# Spaces are used for padding on the left, and zeros for padding on the right.
# No left-truncation occurs, so `left` can be specified as 0 to prevent left-padding.
def pp(left; right):
def lpad: tostring | (left - length) as $l | (" " * $l)[:$l] + .;
def rpad:
if (right > length) then . + ((right - length) * "0")
else .[:right]
end;
tostring as $s
| $s
| index(".") as $ix
| ((if $ix then $s[0:$ix] else $s end) | lpad) + "." +
(if $ix then $s[$ix+1:] | .[:right] else "" end | rpad) ;
 
def sigma( stream ): reduce stream as $x (0; . + $x);
 
# Input: {n, sum, ss}
# Output: augmented object with {mean, variance}
def sample_mean_and_variance:
.mean = (.sum/.n)
| .variance = ((.ss / .n) - .mean*.mean);</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="jq"># Task parameters
def parameters: {
N: 100000,
NUM_BINS: 12,
HIST_CHAR: "■",
HIST_CHAR_ALT: "-",
HIST_CHAR_SIZE: null, # null means compute dynamically
binSize: 0.1,
mu: 0.5,
sigma: 0.25 }
| .bins = [range(0; .NUM_BINS) | 0] ;
 
# input: an array of two iid rvs on [0,1]
# output: [z0, z1] as per the Box-Muller method -- see
# https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
def normal(mu; sigma):
def pi: (1|atan) * 4;
. as [$u1, $u2]
| pi as $pi
| (sigma * ((-2 * ($u1|log))|sqrt)) as $mag
| [ $mag * ((2 * $pi * $u2)|cos) + mu,
$mag * ((2 * $pi * $u2)|sin) + mu ] ;
 
# Generate a random sample as specified by ., the task object (see `parameters`).
# Output: updated task object with sample statistics and .bins for creating a histogram.
# Each call to `input` should yield a string of random decimal digits
# such that the ensemble of ("0." + input | tonumber) can be considered to be iid rv on [0,1].
def generate:
# uniformly distributed random variable on [0,1]:
def udrv: "0." + input | tonumber;
# Maybe compute the bucket size:
(.HIST_CHAR_SIZE = (.HIST_CHAR_SIZE // (.N / (.NUM_BINS * 20) | ceil))) as $p
| reduce range(0; $p.N/2) as $i ($p;
([udrv, udrv] | normal($p.mu; $p.sigma)) as $rns
| reduce (0,1) as $j (.;
$rns[$j] as $rn
| .n += 1
| .sum += $rn
| .ss += ($rn*$rn)
| (if $rn < 0 then 0
elif $rn >= 1 then ($p.NUM_BINS - 1)
else ($rn/.binSize)|floor + 1
end ) as $bn
| .bins[$bn] += 1
# to retain the observations: .samples[$i*2 + $j] = $rn
)) ;
 
# Input: an object with
# {NUM_BINS, HIST_CHAR_SIZE, HIST_CHAR, HIST_CHAR_ALT, binSize, bins}
# Output: a stream of strings
def histogram:
def tidy: pp(2;1);
range(0; .NUM_BINS) as $i
| ((.bins[$i] / .HIST_CHAR_SIZE)|floor) as $bs
| (if $i == 0 or $i == .NUM_BINS -1
then .HIST_CHAR_ALT else .HIST_CHAR end) as $char
| (if $bs == 0 then "" else $char * $bs end) as $hist
| if $i == 0
then " -∞ ..< 0.0 \($hist)" # .bins[0]
elif ($i < .NUM_BINS - 1)
then "\(.binSize * ($i-1) | tidy) ..<\(.binSize * $i|tidy) \($hist)" # .bins[$i]]
else " 1.0 .. +∞ \($hist)" # .bins[.NUM_BINS - 1]
end;
 
def task:
parameters
| generate
| sample_mean_and_variance
| (if .HIST_CHAR_SIZE == 1 then "" else "s" end) as $plural
| "Summary statistics for \(.N) observations from N(\(.mu), \(.sigma)):",
" mean: \(.mean | pp(2;4))",
" variance: \(.variance | pp(2;4))",
" unadjusted stddev: \(.variance | sqrt | pp(2;4))",
" Range Number of observations (each \(.HIST_CHAR) represents \(.HIST_CHAR_SIZE) observation\($plural))",
histogram ;
 
task</syntaxhighlight>
{{out}}
<pre>
Summary statistics for 100000 observations from N(0.5, 0.25):
mean: 0.5001
variance: 0.0622
unadjusted stddev: 0.2495
Range Number of observations (each ■ represents 417 observations)
-∞ ..< 0.0 -----
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 ■■■■■■■■
1.0 .. +∞ ------
</pre>
 
=={{header|Julia}}==
Julia has the builtin package "Distributions" to generate random numbers from a standard distribution (Normal, Chisq etc.).
<langsyntaxhighlight lang="julia">using Printf, Distributions, Gadfly
 
data = rand(Normal(0, 1), 1000)
Line 1,217 ⟶ 1,731:
@printf("range = (%2.2f, %2.2f\n)", minimum(data), maximum(data))
h = plot(x=data, Geom.histogram)
draw(PNG("norm_hist.png", 10cm, 10cm), h)</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,740:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val rand = java.util.Random()
Line 1,282 ⟶ 1,796:
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) normalStats(sampleSize)
}</langsyntaxhighlight>
 
{{out}}
Line 1,356 ⟶ 1,870:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
Line 1,417 ⟶ 1,931:
histogram(#n)
'\r\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 1,472 ⟶ 1,986:
=={{header|Liberty BASIC}}==
Uses LB Statistics/Basic
<langsyntaxhighlight lang="lb">call sample 100000
 
end
Line 1,523 ⟶ 2,037:
v =rnd( 1)
normalDist =( -2 *log( u))^0.5 *cos( 2 *3.14159265 *v)
end function</langsyntaxhighlight>
100000 data terms used.
Largest term was 4.12950792 & smallest was -4.37934139
Line 1,569 ⟶ 2,083:
=={{header|Lua}}==
Lua provides math.random() to generate uniformly distributed random numbers. The function gaussian() shown here uses math.random() to generate normally distributed random numbers with given mean and variance.
<langsyntaxhighlight Lualang="lua">function gaussian (mean, variance)
return math.sqrt(-2 * variance * math.log(math.random())) *
math.cos(2 * math.pi * math.random()) + mean
Line 1,614 ⟶ 2,128:
print("Mean:", mean(t) .. ", expected " .. average)
print("StdDev:", std(t) .. ", expected " .. math.sqrt(variance) .. "\n")
showHistogram(t)</langsyntaxhighlight>
{{out}}
<pre>Mean: 50.008328894275, expected 50
Line 1,642 ⟶ 2,156:
=={{header|Maple}}==
Maple has a built-in for sampling directly from [http://www.maplesoft.com/support/help/Maple/view.aspx?path=Statistics/Distributions/Normal Normal] distributions:
<langsyntaxhighlight lang="maple">with(Statistics):
n := 100000:
X := Sample( Normal(0,1), n );
Mean( X );
StandardDeviation( X );
Histogram( X );</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">x:= RandomReal[1]
SampleNormal[n_] := (Print[#//Length, " numbers, Mean : ", #//Mean, ", StandardDeviation : ", #//StandardDeviation];
Histogram[#, BarOrigin -> Left,Axes -> False])& [(Table[(-2*Log[x])^0.5*Cos[2*Pi*x], {n} ]]
 
Invocation:
SampleNormal[ 10000 ]
->10000 numbers, Mean : -0.0122308, StandardDeviation : 1.00646
</syntaxhighlight>
</lang>
[[File:Mma_NormalDistribution.png]]
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> N = 100000;
x = randn(N,1);
mean(x)
std(x)
[nn,xx] = hist(x,100);
bar(xx,nn);</langsyntaxhighlight>
 
=={{header|Nim}}==
In module “random”, Nim provides two procedures named <code>gauss</code> to generate random values following normal distribution and following Gauss distribution with given mean and standard deviation.
 
Here is a way to generate random values following normal distribution from random values following uniform distribution. It uses the Basic form of the Box-Muller transform.
 
<syntaxhighlight lang="nim">import math, random, sequtils, stats, strformat, strutils
 
proc drawHistogram(ns: seq[float]) =
 
# Distribute values in bins.
const NBins = 50
var minval = min(ns)
var maxval = max(ns)
var h = newSeq[int](NBins + 1)
for n in ns:
let pos = ((n - minval) * NBins / (maxval - minval)).toInt
inc h[pos]
 
# Eliminate extremes values.
const MaxWidth = 50
let mx = max(h)
var first = 0
while (h[first] / mx * MaxWidth).toInt == 0: inc first
var last = h.high
while (h[last] / mx * MaxWidth).toInt == 0: dec last
 
# Draw the histogram.
echo ""
for n in first..last:
echo repeat('+', (h[n] / mx * MaxWidth).toInt)
echo ""
 
 
const N = 100_000
 
randomize()
 
let u1, u2 = newSeqWith(N, rand(1.0))
 
var z = newSeq[float](N)
for i in 0..<N:
z[i] = sqrt(-2 * ln(u1[i])) * cos(2 * PI * u2[i])
 
echo &"μ = {z.mean:.12f} σ = {z.standardDeviation:.12f}"
z.drawHistogram()</syntaxhighlight>
 
{{out}}
<pre>μ = -0.001105836229 σ = 0.999906544722
 
+
+
++
+++
+++++
+++++++
+++++++++
++++++++++++
++++++++++++++++
+++++++++++++++++++++
++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++
+++++++++++++++++++++++++
++++++++++++++++++++
++++++++++++++++
++++++++++++
+++++++++
++++++
+++++
+++
++
+
+
</pre>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<langsyntaxhighlight lang="parigp">rnormal()={
my(u1=random(1.),u2=random(1.));
sqrt(-2*log(u1))*cos(2*Pi*u1u2)
\\ Could easily be extended with a second normal at very little cost.
};
Line 1,692 ⟶ 2,290:
for(i=1,#h,for(j=1,h[i]\sz,print1("#"));print());
};
show(10^4)</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>.
 
A PARI implementation:
<langsyntaxhighlight Clang="c">GEN
rnormal(long prec)
{
Line 1,715 ⟶ 2,313:
ret = gerepileupto(ltop, ret);
return ret;
}</langsyntaxhighlight>
Use <code>mpsincos</code> and caching to generate two values at nearly the same cost.
 
Line 1,725 ⟶ 2,323:
 
From [http://www.freepascal.org/docs-html/rtl/math/randg.html Free Pascal Docs unit math]
<langsyntaxhighlight lang="pascal">Program Example40;
{$IFDEF FPC}
{$MOde objFPC}
Line 1,856 ⟶ 2,454:
mySol := getSol(@rnorm,cMean,cStdDiv,1000000);
Histo(mySol,cHistCnt,cColLen);
end.</langsyntaxhighlight>
{{out}}<pre>
function randg
Line 1,916 ⟶ 2,514:
 
=={{header|Perl}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="perl">use constant pi => 3.14159265;
use List::Util qw(sum reduce min max);
 
Line 1,948 ⟶ 2,546:
print "$i\t$t1$t2\n";
}
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:35ex">32 ⎸
Line 1,985 ⟶ 2,583:
65 ⎸
66 ⎸</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2018.03}}
<lang perl6>sub normdist ($m, $σ) {
my $r = sqrt -2 * log rand;
my $Θ = τ * rand;
$r * cos($Θ) * $σ + $m;
}
 
sub MAIN ($size = 100000, $mean = 50, $stddev = 4) {
my @dataset = normdist($mean,$stddev) xx $size;
 
my $m = [+](@dataset) / $size;
say (:$m);
 
my $σ = sqrt [+](@dataset X** 2) / $size - $m**2;
say (:$σ);
 
(my %hash){.round}++ for @dataset;
my $scale = 180 * $stddev / $size;
constant @subbar = < ⎸ ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ >;
for %hash.keys».Int.minmax(+*) -> $i {
my $x = (%hash{$i} // 0) * $scale;
my $full = floor $x;
my $part = 8 * ($x - $full);
say $i, "\t", '█' x $full, @subbar[$part];
}
}</lang>
{{out}}
<pre>"m" => 50.006107405837142e0
"σ" => 4.0814435639885254e0
33 ⎸
34 ⎸
35 ⎸
36 ▏
37 ▎
38 ▊
39 █▋
40 ███⎸
41 █████▊
42 ██████████⎸
43 ███████████████▋
44 ███████████████████████▏
45 ████████████████████████████████▌
46 ███████████████████████████████████████████▍
47 ██████████████████████████████████████████████████████▏
48 ███████████████████████████████████████████████████████████████▏
49 █████████████████████████████████████████████████████████████████████▋
50 ███████████████████████████████████████████████████████████████████████▊
51 █████████████████████████████████████████████████████████████████████▌
52 ███████████████████████████████████████████████████████████████⎸
53 ██████████████████████████████████████████████████████▎
54 ███████████████████████████████████████████⎸
55 ████████████████████████████████▌
56 ███████████████████████▍
57 ███████████████▉
58 █████████▉
59 █████▍
60 ███▍
61 █▋
62 ▊
63 ▍
64 ▏
65 ⎸
66 ⎸
67 ⎸</pre>
 
=={{header|Phix}}==
{{trans|Liberty_BASIC}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>procedure sample(integer n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
-- show mean, standard deviation. Find max, min.
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sample</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence dat = repeat(0,n)
<span style="color: #000080;font-style:italic;">-- show mean, standard deviation. Find max, min.</span>
for i=1 to n do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">dat</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;">n</span><span style="color: #0000FF;">)</span>
dat[i] = sqrt(-2*log(rnd()))*cos(2*PI*rnd())
<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>
end for
<span style="color: #000000;">dat</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">log</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">()))*</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">())</span>
printf(1,"%d data terms used.\n",{n})
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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;">"%d data terms used.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
atom mean = sum(dat)/n,
mx = max(dat),
<span style="color: #004080;">atom</span> <span style="color: #000000;">mean</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dat</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span>
mn = min(dat),
<span style="color: #000000;">mx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dat</span><span style="color: #0000FF;">),</span>
range = mx-mn
<span style="color: #000000;">mn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dat</span><span style="color: #0000FF;">),</span>
printf(1,"Largest term was %g & smallest was %g\n",{mx,mn})
<span style="color: #000000;">range</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mx</span><span style="color: #0000FF;">-</span><span style="color: #000000;">mn</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;">"Largest term was %g & smallest was %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mn</span><span style="color: #0000FF;">})</span>
printf(1,"Stddev = %g\n",sqrt(sum(sq_mul(dat,dat))/n-mean*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>
<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;">"Stddev = %g\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dat</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dat</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;">mean</span><span style="color: #0000FF;">))</span>
-- show histogram
integer nBins = 50
<span style="color: #000080;font-style:italic;">-- show histogram</span>
sequence bins = repeat(0,nBins+1)
<span style="color: #004080;">integer</span> <span style="color: #000000;">nBins</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span>
for i=1 to n do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">bins</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;">nBins</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
bins[floor((dat[i]-mn)/range*nBins)+1] += 1
<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>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">bdx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">dat</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">mn</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">range</span><span style="color: #0000FF;">*</span><span style="color: #000000;">nBins</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
for b=1 to nBins do
<span style="color: #000000;">bins</span><span style="color: #0000FF;">[</span><span style="color: #000000;">bdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
puts(1,repeat('#',floor(nBins*bins[b]/n*30))&"\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nBins</span> <span style="color: #008080;">do</span>
end procedure
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</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;">nBins</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bins</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">30</span><span style="color: #0000FF;">))&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
sample(100000)</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">sample</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100000</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,126 ⟶ 2,662:
</pre>
{{trans|Lua}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function gaussian(atom mean, atom variance)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return sqrt(-2 * variance * log(rnd())) *
<span style="color: #008080;">function</span> <span style="color: #000000;">gaussian</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">variance</span><span style="color: #0000FF;">)</span>
cos(2 * variance * PI * rnd()) + mean
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">2</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">variance</span> <span style="color: #0000FF;">*</span> <span style="color: #7060A8;">log</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">()))</span> <span style="color: #0000FF;">*</span>
end function
<span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">variance</span> <span style="color: #0000FF;">*</span> <span style="color: #004600;">PI</span> <span style="color: #0000FF;">*</span> <span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">())</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">mean</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function mean(sequence t)
return sum(t)/length(t)
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
function std(sequence t)
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
atom squares = 0,
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
avg = mean(t)
for i=1 to length(t) do
<span style="color: #008080;">function</span> <span style="color: #000000;">std</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
squares += power(avg-t[i],2)
<span style="color: #004080;">atom</span> <span style="color: #000000;">squares</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
end for
<span style="color: #000000;">avg</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
atom variance = squares/length(t)
<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;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
return sqrt(variance)
<span style="color: #000000;">squares</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">avg</span><span style="color: #0000FF;">-</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">variance</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">squares</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
procedure showHistogram(sequence t)
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">variance</span><span style="color: #0000FF;">)</span>
for i=ceil(min(t)) to floor(max(t)) do
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
integer n = 0
for k=1 to length(t) do
<span style="color: #008080;">procedure</span> <span style="color: #000000;">showHistogram</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
n += ceil(t[k]-0.5)=i
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">ceil</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">do</span>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
integer l = floor(n/length(t)*200)
<span style="color: #008080;">for</span> <span style="color: #000000;">k</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;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"%d %s %d\n",{i,repeat('=',l),n})
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">ceil</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">i</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">200</span><span style="color: #0000FF;">)</span>
<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;">"%d %s %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</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: #000000;">l</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
sequence t = repeat(0,100000)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
integer avg = 50, variance = 10
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
for i=1 to length(t) do
t[i] = gaussian(avg, variance)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">t</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;">100000</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">avg</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">50</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">variance</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span>
printf(1,"Mean: %g, expected %g\n",{mean(t),avg})
<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;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"StdDev: %g, expected %g\n",{std(t),sqrt(variance)})
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">gaussian</span><span style="color: #0000FF;">(</span><span style="color: #000000;">avg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">variance</span><span style="color: #0000FF;">)</span>
showHistogram(t)</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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, expected %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">mean</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">),</span><span style="color: #000000;">avg</span><span style="color: #0000FF;">})</span>
<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;">"StdDev: %g, expected %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">std</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">variance</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">showHistogram</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 2,198 ⟶ 2,737:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Procedure.f randomf(resolution = 2147483647)
ProcedureReturn Random(resolution) / resolution
EndProcedure
Line 2,262 ⟶ 2,801:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>100000 data terms used.
Line 2,301 ⟶ 2,840:
=={{header|Python}}==
This uses the external [http://matplotlib.org/ matplotlib] package as well as the built-in standardlib function [http://docs.python.org/2/library/random.html?highlight=gauss#random.gauss random.gauss].
<langsyntaxhighlight lang="python">from __future__ import division
import matplotlib.pyplot as plt
import random
Line 2,315 ⟶ 2,854:
% (mn, sd, max(data), min(data), size))
 
plt.hist(data,bins=50)</langsyntaxhighlight>
 
{{out}}
Line 2,323 ⟶ 2,862:
 
=={{header|R}}==
 
R can generate random normal distributed numbers using the [https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Normal.html rnorm] command:
Generate normal random numbers from uniform random numbers, using the [https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform Box-Muller transform]. Both x and y are normally distributed, and independent.
<lang r>n = 100000;
<syntaxhighlight lang="r">n <- 100000
X = rnorm(n, mean = 0, sd = 1);
u <- sqrt(-2*log(runif(n)))
mean( X );
v <- 2*pi*runif(n)
sd( X );
x <- u*cos(v)
hist( X );</lang>
y <- v*sin(v)
hist(x)</syntaxhighlight>
 
 
R can generate random normal distributed numbers using the [https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Normal.html rnorm] function:
<syntaxhighlight lang="r">n <- 100000
x <- rnorm(n, mean=0, sd=1)
mean(x)
sd(x)
hist(x)</syntaxhighlight>
 
=={{header|Racket}}==
Line 2,334 ⟶ 2,883:
compute statistics and plot a histogram.
[[File:histogram-racket.png|thumb|right]]
<langsyntaxhighlight lang="racket">
#lang racket
(require math (planet williams/science/histogram-with-graphics))
Line 2,348 ⟶ 2,897:
(for ([x data]) (histogram-increment! h x))
(histogram-plot h "Normal distribution μ=50 σ=4")
</syntaxhighlight>
</lang>
 
The other part of the task was to produce normal distributed numbers from a unit distribution.
Line 2,354 ⟶ 2,903:
version of [http://planet.plt-scheme.org/package-source/schematics/random.plt/1/0/random.ss code]
originally written by Sebastian Egner.
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,374 ⟶ 2,923:
(set! next (* scale v2))
(+ μ (* σ scale v1))])))))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>sub normdist ($m, $σ) {
my $r = sqrt -2 * log rand;
my $Θ = τ * rand;
$r * cos($Θ) * $σ + $m;
}
 
sub MAIN ($size = 100000, $mean = 50, $stddev = 4) {
my @dataset = normdist($mean,$stddev) xx $size;
 
my $m = [+](@dataset) / $size;
say (:$m);
 
my $σ = sqrt [+](@dataset X** 2) / $size - $m**2;
say (:$σ);
 
(my %hash){.round}++ for @dataset;
my $scale = 180 * $stddev / $size;
constant @subbar = < ⎸ ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ >;
for %hash.keys».Int.minmax(+*) -> $i {
my $x = (%hash{$i} // 0) * $scale;
my $full = floor $x;
my $part = 8 * ($x - $full);
say $i, "\t", '█' x $full, @subbar[$part];
}
}</syntaxhighlight>
{{out}}
<pre>"m" => 50.006107405837142e0
"σ" => 4.0814435639885254e0
33 ⎸
34 ⎸
35 ⎸
36 ▏
37 ▎
38 ▊
39 █▋
40 ███⎸
41 █████▊
42 ██████████⎸
43 ███████████████▋
44 ███████████████████████▏
45 ████████████████████████████████▌
46 ███████████████████████████████████████████▍
47 ██████████████████████████████████████████████████████▏
48 ███████████████████████████████████████████████████████████████▏
49 █████████████████████████████████████████████████████████████████████▋
50 ███████████████████████████████████████████████████████████████████████▊
51 █████████████████████████████████████████████████████████████████████▌
52 ███████████████████████████████████████████████████████████████⎸
53 ██████████████████████████████████████████████████████▎
54 ███████████████████████████████████████████⎸
55 ████████████████████████████████▌
56 ███████████████████████▍
57 ███████████████▉
58 █████████▉
59 █████▍
60 ███▍
61 █▋
62 ▊
63 ▍
64 ▏
65 ⎸
66 ⎸
67 ⎸</pre>
 
=={{header|REXX}}==
The REXX language doesn't have any "higher math" BIF functions like &nbsp; SIN, COS, LN, LOG, SQRT, EXP, POW, etc,
<br>so we hoi polloi programmers have to roll our own.
<langsyntaxhighlight lang="rexx">/*REXX program generates 10,000 normally distributed numbers (Gaussian distribution).*/
numeric digits 20 /*use 20 twenty decimal digitsdigs for accuracy.*/
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 10000 /*Not specified? Then use the default.*/
Line 2,390 ⟶ 3,006:
mn= #.1; mx= mn; noise= n * .0005 /*calculate the noise: 1/20th % of N.*/
ss= 0
do j=1 for n; _= #.j; s=s+_; ss=ss+_*_ /*the sum, and the sum of squares. */
s= s + _; ss= ss + _ * _ /*the sum, and the sum of squares. */
mn= min(mn, _); mx= max(mx, _) /*find the minimum and the maximum. */
end /*j*/
!.= 0
say 'number of data points = ' aafmt(n )
say ' minimum = ' aafmt(mn )
say ' maximum = ' aafmt(mx )
say ' arithmetic mean = ' aafmt(s/n)
say ' standard deviation = ' aafmt(sqrt( ss/n - (s/n) **2) )
?mn= !.1; ?mx= ?mn /*define minimum & maximum value so far*/
parse value scrSize() with sd sw . /*obtain the (true) screen size of term*/ /*◄──not all REXXes have this BIF*/
sdE= sd - 4 /*the effective (useableusable) screen depth. */
swE= sw - 1 /* " " " " width.*/
$= 1 / max(1, mx-mn) * sdE /*$ is used for scaling depth of histo*/
do i=1 for n; ?= trunc( (#.i-mn) * $) /*calculate the relative line. */
!.?= !.? + 1 /*bump the counter. /*bump the counter. */
?mn= min(?mn, !.?); ?mx= max(?mx, !.?) /*find the minimum. and maximum*/
?mx= max(?mx, !.?) /* " " maximum. */
end /*i*/
f= swE/?mx /*limit graph to 1 full screen*/
do h=0 for sdE; _= !.h /*obtain a data point. */
if _>noise then say copies('─', trunc(_*f) ) /*display a bar of histogram. */
end /*h*/ /*[↑] use a hyphen for histo.*/
exit /*stick a fork in it, we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
aafmt: parse arg a@; return left('', (a@>=0) + 2 * datatype(a@, 'W'))a@ /*prepend a blank if #>=0, add 2 blanks if whole.*/
e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi
r2r: return arg(1) // (pi() * 2) /*normalize the given angle (in radians) to ±2pi.*/
rand: return random(1, 1e5) / 1e5 /*REXX generates uniform random postive integers.*/
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
.sincos: parse arg z,_,i; x= x*x; p= z; do k=2 by 2; _= -_*x/(k*(k+i)); z= z+_; if z=p then leave; p= z; end; return z
ln: procedure; parse arg x,f; call e; ig= x>1.5; is= 1 -2*(ig\==1); ii= 0; xx= x; do while ig & xx>1.5 | \ig & xx<.5
/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
ln: procedure; parse arg x,f; call_= e; ig= x>1.5;do isk= 1 -2*(ig\==1); iiiz= 0; xx=*_ x**-is; doif whilek>=0 & (ig & xx>iz<1.5 | \ig & xx<iz>.5) then leave; _= _*_; izz= iz; end; xx= izz
ii= ii +is*2**k; _end; x= x*e**-ii-1; z=0; do k_=-1; izp= xx*_ **-isz; ifdo k>=0 & (ig & iz<1 | \ig & iz>.5) then leave; _= -_*x;z=z+_/k;if izzz=p iz;then leave;p=z;end; return xx= izzz+ii
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
ii= ii +is*2**k; end; x= x*e**-ii-1; z=0; _=-1; p=z; do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii
cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi= pi*.5; numeric fuzz min(6, digits()-3); if a=pi then return -1
/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parseif arga=hpi x;| xa=r2r(x)hpi*3 then return 0; if a=abs(x);pi/3 hpi= pi*then return .5; numeric fuzz min(6, digits()-3); if a=pi *2/3 then return -.5; z= 1; _= 1
x= x*x; ifp= az; do k=hpi2 | aby 2; _=hpi*3 -_ then* returnx 0/ (k*(k-1)); if a z=pi/3 z then+ return_; .5; if az=pi*2/3p then returnleave; -.5 p= z; end; return .sinCos(1,1,-1)z
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); m.= 9; numeric digits; numeric form; h= d+6
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*/; numeric digits d; return g/1</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''scrsize''' &nbsp; REXX program (or BIF) which is used to determine the screen size of the terminal (console); &nbsp; this is to aid in maximizing the width of the horizontal histogram.
 
Line 2,439 ⟶ 3,057:
(The output shown when the screen size is 62<small>x</small>140.)
 
The graph is shown at &nbsp; <big>'''<sup>3</sup>/<sub>4</sub>''' &nbsp; size.
<pre style="font-size:75%">
number of data points = 10000
Line 2,496 ⟶ 3,114:
──
</pre>
=={{header|Ruby}}==
{{works with|Ruby|2.7}}
'''The Implementation'''
<syntaxhighlight lang="ruby"># Class to implement a Normal distribution, generated from a Uniform distribution.
# Uses the Marsaglia polar method.
 
class NormalFromUniform
# Initialize an instance.
def initialize()
@next = nil
end
# Generate and return the next Normal distribution value.
def rand()
if @next
retval, @next = @next, nil
return retval
else
u = v = s = nil
loop do
u = Random.rand(-1.0..1.0)
v = Random.rand(-1.0..1.0)
s = u**2 + v**2
break if (s > 0.0) && (s <= 1.0)
end
f = Math.sqrt(-2.0 * Math.log(s) / s)
@next = v * f
return u * f
end
end
end</syntaxhighlight>
'''The Task'''
{{libheader|enumerable-statistics}}
<syntaxhighlight lang="ruby">require('enumerable/statistics')
 
def show_stats_and_histogram(data, bins)
puts("size = #{data.length} mean = #{data.mean()} stddev = #{data.stdev()}")
hist = data.histogram(bins)
scale = 100.0 / hist.weights.max
inx_beg = nil
inx_end = nil
hist.weights.length.times do |inx|
histstars = (0.5 + (scale * hist.weights[inx])).to_i
inx_beg = inx if !inx_beg && (histstars > 0)
inx_end = inx if (histstars > 0)
end
(inx_beg..inx_end).each do |inx|
bincenter = 0.5 * (hist.edges[inx] + hist.edges[inx + 1])
histstars = (0.5 + (scale * hist.weights[inx])).to_i
puts('%6.2f: %s' % [bincenter, '*' * histstars])
end
end
 
puts
puts('Uniform random number generator:')
show_stats_and_histogram(1000000.times.map { Random.rand(-1.0..1.0) }, 20)
 
puts
puts('Normal random numbers using the Marsaglia polar method:')
gen_normal = NormalFromUniform.new
show_stats_and_histogram(100.times.map { gen_normal.rand }, 40)
show_stats_and_histogram(10000.times.map { gen_normal.rand }, 60)
show_stats_and_histogram(1000000.times.map { gen_normal.rand }, 120)</syntaxhighlight>
{{out}}
<pre style="height: 200ex; overflow: scroll">
Uniform random number generator:
size = 1000000 mean = 0.0001483724103528628 stddev = 0.5773085740222473
-0.95: ****************************************************************************************************
-0.85: ****************************************************************************************************
-0.75: ***************************************************************************************************
-0.65: ***************************************************************************************************
-0.55: ***************************************************************************************************
-0.45: ****************************************************************************************************
-0.35: ****************************************************************************************************
-0.25: ****************************************************************************************************
-0.15: ****************************************************************************************************
-0.05: ***************************************************************************************************
0.05: ****************************************************************************************************
0.15: ****************************************************************************************************
0.25: ****************************************************************************************************
0.35: ***************************************************************************************************
0.45: ***************************************************************************************************
0.55: ****************************************************************************************************
0.65: ****************************************************************************************************
0.75: ****************************************************************************************************
0.85: ****************************************************************************************************
0.95: ***************************************************************************************************
 
Normal random numbers using the Marsaglia polar method:
size = 100 mean = 0.1611961166227389 stddev = 0.9827581078952005
-2.30: **********
-2.10:
-1.90: **********
-1.70: ********************
-1.50:
-1.30: **********
-1.10: **********************************************************************
-0.90: ************************************************************
-0.70: **********************************************************************
-0.50: ************************************************************
-0.30: ********************************************************************************
-0.10: ********************
0.10: ********************************************************************************
0.30: ****************************************************************************************************
0.50: ******************************************************************************************
0.70: ********************************************************************************
0.90: ************************************************************
1.10: ******************************
1.30: **************************************************
1.50:
1.70: ********************
1.90: **************************************************
2.10: **********
2.30: ********************
size = 10000 mean = -0.004863294071004369 stddev = 0.9984395022628252
-3.30: *
-3.10: *
-2.90: **
-2.70: **
-2.50: ****
-2.30: *********
-2.10: ***********
-1.90: ****************
-1.70: ***********************
-1.50: *****************************
-1.30: *****************************************
-1.10: *************************************************
-0.90: ******************************************************************
-0.70: ******************************************************************************
-0.50: ***************************************************************************************
-0.30: *********************************************************************************************
-0.10: ***********************************************************************************************
0.10: ****************************************************************************************************
0.30: **************************************************************************************
0.50: ************************************************************************************
0.70: *******************************************************************************
0.90: ****************************************************************
1.10: ***************************************************
1.30: ********************************************
1.50: *******************************
1.70: **********************
1.90: ****************
2.10: **********
2.30: ******
2.50: *****
2.70: **
2.90: *
3.10: *
size = 1000000 mean = 0.0007049206911295587 stddev = 1.0000356747411552
-3.15: *
-3.05: *
-2.95: *
-2.85: **
-2.75: **
-2.65: ***
-2.55: ****
-2.45: *****
-2.35: ******
-2.25: ********
-2.15: **********
-2.05: ************
-1.95: ***************
-1.85: ******************
-1.75: *********************
-1.65: *************************
-1.55: ******************************
-1.45: ***********************************
-1.35: ****************************************
-1.25: *********************************************
-1.15: ***************************************************
-1.05: *********************************************************
-0.95: ***************************************************************
-0.85: *********************************************************************
-0.75: **************************************************************************
-0.65: *********************************************************************************
-0.55: *************************************************************************************
-0.45: *****************************************************************************************
-0.35: ********************************************************************************************
-0.25: ************************************************************************************************
-0.15: **************************************************************************************************
-0.05: ****************************************************************************************************
0.05: ***************************************************************************************************
0.15: **************************************************************************************************
0.25: ************************************************************************************************
0.35: *********************************************************************************************
0.45: ******************************************************************************************
0.55: *************************************************************************************
0.65: ********************************************************************************
0.75: **************************************************************************
0.85: *********************************************************************
0.95: ***************************************************************
1.05: *********************************************************
1.15: ****************************************************
1.25: **********************************************
1.35: ****************************************
1.45: **********************************
1.55: ******************************
1.65: *************************
1.75: **********************
1.85: ******************
1.95: ***************
2.05: ************
2.15: **********
2.25: ********
2.35: ******
2.45: *****
2.55: ****
2.65: ***
2.75: **
2.85: **
2.95: *
3.05: *
3.15: *
</pre>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">
s = 100000
h$ = "============================================================="
Line 2,541 ⟶ 3,372:
print using("##",b);" ";using("#####",bins(b));" ";left$(h$,(bins(b) / mb) * 90)
next b
END</langsyntaxhighlight>
{{out}}
<pre>
Line 2,586 ⟶ 3,417:
=
 
</pre>
=={{header|Rust}}==
{{libheader|math}}
{{libheader|rand}}
{{libheader|rand_distr}}
<syntaxhighlight lang="rust">//! Rust rosetta example for normal distribution
use math::{histogram::Histogram, traits::ToIterator};
use rand;
use rand_distr::{Distribution, Normal};
 
/// Returns the mean of the provided samples
///
/// ## Arguments
/// * data -- reference to float32 array
fn mean(data: &[f32]) -> Option<f32> {
let sum: f32 = data.iter().sum();
Some(sum / data.len() as f32)
}
 
/// Returns standard deviation of the provided samples
///
/// ## Arguments
/// * data -- reference to float32 array
fn standard_deviation(data: &[f32]) -> Option<f32> {
let mean = mean(data).expect("invalid mean");
let sum = data.iter().fold(0.0, |acc, &x| acc + (x - mean).powi(2));
Some((sum / data.len() as f32).sqrt())
}
 
/// Prints a histogram in the shell
///
/// ## Arguments
/// * data -- reference to float32 array
/// * maxwidth -- the maxwidth of the histogram in # of characters
/// * bincount -- number of bins in the histogram
/// * ch -- character used to plot the graph
fn print_histogram(data: &[f32], maxwidth: usize, bincount: usize, ch: char) {
let min_val = data.iter().cloned().fold(f32::NAN, f32::min);
let max_val = data.iter().cloned().fold(f32::NAN, f32::max);
let histogram = Histogram::new(Some(&data.to_vec()), bincount, min_val, max_val).unwrap();
let max_bin_value = histogram.get_counters().iter().max().unwrap();
println!();
for x in histogram.to_iter() {
let (bin_min, bin_max, freq) = x;
let bar_width = (((freq as f64) / (*max_bin_value as f64)) * (maxwidth as f64)) as u32;
let bar_as_string = (1..bar_width).fold(String::new(), |b, _| b + &ch.to_string());
println!(
"({:>6},{:>6}) |{} {:.2}%",
format!("{:.2}", bin_min),
format!("{:.2}", bin_max),
bar_as_string,
(freq as f64) * 100.0 / (data.len() as f64)
);
}
println!();
}
 
/// Runs the demo to generate normal distribution of three different sample sizes
fn main() {
let expected_mean: f32 = 0.0;
let expected_std_deviation: f32 = 4.0;
let normal = Normal::new(expected_mean, expected_std_deviation).unwrap();
 
let mut rng = rand::thread_rng();
for &number_of_samples in &[1000, 10_000, 1_000_000] {
let data: Vec<f32> = normal
.sample_iter(&mut rng)
.take(number_of_samples)
.collect();
println!("Statistics for sample size {}:", number_of_samples);
println!("\tMean: {:?}", mean(&data).expect("invalid mean"));
println!(
"\tStandard deviation: {:?}",
standard_deviation(&data).expect("invalid standard deviation")
);
print_histogram(&data, 80, 40, '-');
}
}</syntaxhighlight>
{{out}}
<pre style="height: 120ex; overflow: scroll">
Statistics for sample size 1000:
Mean: -0.11356559
Standard deviation: 4.0244555
 
(-13.81,-13.12) | 0.10%
(-13.12,-12.44) | 0.00%
(-12.44,-11.75) | 0.10%
(-11.75,-11.06) | 0.20%
(-11.06,-10.38) |- 0.30%
(-10.38, -9.69) | 0.10%
( -9.69, -9.01) |--- 0.50%
( -9.01, -8.32) |---- 0.60%
( -8.32, -7.64) |------ 0.80%
( -7.64, -6.95) |-------------- 1.60%
( -6.95, -6.27) |----------------- 1.90%
( -6.27, -5.58) |------------------------ 2.60%
( -5.58, -4.90) |----------------------- 2.50%
( -4.90, -4.21) |---------------------------------------- 4.20%
( -4.21, -3.53) |------------------------------------- 3.90%
( -3.53, -2.84) |------------------------------------------------- 5.10%
( -2.84, -2.15) |---------------------------------------------- 4.80%
( -2.15, -1.47) |------------------------------------------------------------------------ 7.40%
( -1.47, -0.78) |---------------------------------------------------------- 6.00%
( -0.78, -0.10) |----------------------------------------------------------------------- 7.30%
( -0.10, 0.59) |------------------------------------------------------------------------------- 8.10%
( 0.59, 1.27) |----------------------------------------------------------------------- 7.30%
( 1.27, 1.96) |------------------------------------------------- 5.10%
( 1.96, 2.64) |------------------------------------------------------------ 6.20%
( 2.64, 3.33) |----------------------------------------- 4.30%
( 3.33, 4.01) |----------------------------- 3.10%
( 4.01, 4.70) |------------------------------------- 3.90%
( 4.70, 5.39) |-------------------------- 2.80%
( 5.39, 6.07) |---------------------- 2.40%
( 6.07, 6.76) |---------------- 1.80%
( 6.76, 7.44) |---------------- 1.80%
( 7.44, 8.13) |--------- 1.10%
( 8.13, 8.81) |---------- 1.20%
( 8.81, 9.50) | 0.20%
( 9.50, 10.18) | 0.00%
( 10.18, 10.87) | 0.10%
( 10.87, 11.55) |- 0.30%
( 11.55, 12.24) | 0.10%
( 12.24, 12.92) | 0.10%
( 12.92, 13.61) | 0.10%
 
Statistics for sample size 10000:
Mean: 0.02012564
Standard deviation: 3.9697735
 
(-15.80,-14.99) | 0.02%
(-14.99,-14.18) | 0.04%
(-14.18,-13.37) | 0.04%
(-13.37,-12.56) | 0.04%
(-12.56,-11.75) | 0.09%
(-11.75,-10.94) | 0.08%
(-10.94,-10.13) |- 0.25%
(-10.13, -9.32) |--- 0.42%
( -9.32, -8.51) |----- 0.67%
( -8.51, -7.70) |--------- 1.10%
( -7.70, -6.89) |------------- 1.48%
( -6.89, -6.08) |------------------ 1.98%
( -6.08, -5.27) |-------------------------- 2.82%
( -5.27, -4.45) |------------------------------------ 3.80%
( -4.45, -3.64) |--------------------------------------------- 4.66%
( -3.64, -2.83) |------------------------------------------------------- 5.72%
( -2.83, -2.02) |------------------------------------------------------------------ 6.85%
( -2.02, -1.21) |---------------------------------------------------------------------------- 7.80%
( -1.21, -0.40) |---------------------------------------------------------------------------- 7.79%
( -0.40, 0.41) |------------------------------------------------------------------------------- 8.09%
( 0.41, 1.22) |----------------------------------------------------------------------------- 7.89%
( 1.22, 2.03) |--------------------------------------------------------------------------- 7.76%
( 2.03, 2.84) |-------------------------------------------------------------------- 7.06%
( 2.84, 3.65) |------------------------------------------------------- 5.74%
( 3.65, 4.46) |-------------------------------------------- 4.64%
( 4.46, 5.27) |-------------------------------------- 4.00%
( 5.27, 6.08) |---------------------------- 3.03%
( 6.08, 6.89) |------------------- 2.07%
( 6.89, 7.71) |-------------- 1.54%
( 7.71, 8.52) |-------- 0.97%
( 8.52, 9.33) |----- 0.61%
( 9.33, 10.14) |-- 0.36%
( 10.14, 10.95) |- 0.25%
( 10.95, 11.76) | 0.19%
( 11.76, 12.57) | 0.08%
( 12.57, 13.38) | 0.02%
( 13.38, 14.19) | 0.01%
( 14.19, 15.00) | 0.03%
( 15.00, 15.81) | 0.00%
( 15.81, 16.62) | 0.01%
 
Statistics for sample size 1000000:
Mean: -0.004743685
Standard deviation: 4.0006065
 
(-20.00,-19.02) | 0.00%
(-19.02,-18.04) | 0.00%
(-18.04,-17.06) | 0.00%
(-17.06,-16.07) | 0.00%
(-16.07,-15.09) | 0.00%
(-15.09,-14.11) | 0.01%
(-14.11,-13.13) | 0.03%
(-13.13,-12.15) | 0.06%
(-12.15,-11.16) | 0.14%
(-11.16,-10.18) |- 0.28%
(-10.18, -9.20) |--- 0.53%
( -9.20, -8.22) |------ 0.95%
( -8.22, -7.24) |----------- 1.51%
( -7.24, -6.25) |------------------ 2.40%
( -6.25, -5.27) |--------------------------- 3.48%
( -5.27, -4.29) |-------------------------------------- 4.82%
( -4.29, -3.31) |-------------------------------------------------- 6.27%
( -3.31, -2.32) |------------------------------------------------------------- 7.62%
( -2.32, -1.34) |----------------------------------------------------------------------- 8.77%
( -1.34, -0.36) |----------------------------------------------------------------------------- 9.58%
( -0.36, 0.62) |------------------------------------------------------------------------------- 9.74%
( 0.62, 1.60) |---------------------------------------------------------------------------- 9.39%
( 1.60, 2.59) |-------------------------------------------------------------------- 8.49%
( 2.59, 3.57) |---------------------------------------------------------- 7.30%
( 3.57, 4.55) |----------------------------------------------- 5.86%
( 4.55, 5.53) |----------------------------------- 4.45%
( 5.53, 6.51) |------------------------ 3.16%
( 6.51, 7.50) |---------------- 2.09%
( 7.50, 8.48) |--------- 1.34%
( 8.48, 9.46) |----- 0.81%
( 9.46, 10.44) |-- 0.46%
( 10.44, 11.42) | 0.23%
( 11.42, 12.41) | 0.11%
( 12.41, 13.39) | 0.06%
( 13.39, 14.37) | 0.02%
( 14.37, 15.35) | 0.01%
( 15.35, 16.34) | 0.00%
( 16.34, 17.32) | 0.00%
( 17.32, 18.30) | 0.00%
( 18.30, 19.28) | 0.00%
</pre>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data test;
n=100000;
twopi=2*constant('pi');
Line 2,616 ⟶ 3,661:
y 0.000023995 1.0019996
z 0.0012857 1.0056536
*/</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">define τ = NumberNum.tau
 
func normdist (m, σ) {
Line 2,633 ⟶ 3,678:
 
var dataset = size.of { normdist(mean, stddev) }
var m = (dataset.sum(0) / size)
say ("m: #{m}")
 
var σ = sqrt(dataset  »**» 2 -> sum(0) / size - m**2)
say ("s: #{σ}")
 
var hash = Hash()
dataset.each { |n| hash{ n.round(0) }  := 0 ++ }
 
var scale = (180 * stddev / size)
Line 2,650 ⟶ 3,695:
var part = (8 * (x - full))
say (i, "\t", '█' * full, subbar[part])
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,692 ⟶ 3,737:
 
=={{header|Stata}}==
Pairs of normal numbers are generated from pairs of uniform numbers using the polar form of [https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform Box-Muller method]. A normal density is added to the histogram for comparison. See '''[http://www.stata.com/help.cgi?histogram histogram]''' in Stata help. A [https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot Q-Q plot] is also drawn.
 
<syntaxhighlight lang ="stata">. clear all
. set obs 100000
. gen u=runiform()
. gen v=runiform()
. gen r=sqrt(-2*log(u))
. gen x=r*cos(2*_pi*v)
. gen y=r*sin(2*_pi*v)
. gen z=rnormal()
. summarizesum x y z
 
Variable | Obs Mean Std. Dev. Min Max
Line 2,709 ⟶ 3,754:
y | 100,000 .0017389 1.001586 -4.631144 4.460274
z | 100,000 .005054 .9998861 -5.134265 4.449522
. hist x, normal
. hist y, normal
. hist z, normal
. qqplot x z, msize(tiny)</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
# Uses the Box-Muller transform to compute a pair of normal random numbers
proc tcl::mathfunc::nrand {mean stddev} {
Line 2,753 ⟶ 3,798:
stats 10000
puts ""
stats 100000 20</langsyntaxhighlight>
Sample output:
<pre>
Line 2,846 ⟶ 3,891:
</pre>
The blank lines in the output are where the number of samples is too small to even merit a single unit on the histogram.
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
For i = 1 To 20000
s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
Next i
For i = -35 To 35
bins(i + 36) = i / 10
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; standard_deviation(s)
t = WorksheetFunction.Frequency(s, bins)
For i = -35 To 35
Debug.Print Format((i - 1) / 10, "0.00");
Debug.Print "-"; Format(i / 10, "0.00"),
Debug.Print String$(t(i + 36, 1) / 10, "X");
Debug.Print
Next i
End Sub</syntaxhighlight>{{out}}
<pre>sample size 20000 mean-5,26306310478751E-03 standard deviation 1,00355037427319
-3,60--3,50
-3,50--3,40
-3,40--3,30
-3,30--3,20
-3,20--3,10
-3,10--3,00
-3,00--2,90 XX
-2,90--2,80 X
-2,80--2,70 XX
-2,70--2,60 XX
-2,60--2,50 XXX
-2,50--2,40 XXXX
-2,40--2,30 XXXXX
-2,30--2,20 XXXXXXXX
-2,20--2,10 XXXXXXXX
-2,10--2,00 XXXXXXXXXXX
-2,00--1,90 XXXXXXXXXXXXX
-1,90--1,80 XXXXXXXXXXXXXXX
-1,80--1,70 XXXXXXXXXXXXXXXX
-1,70--1,60 XXXXXXXXXXXXXXXXXXXX
-1,60--1,50 XXXXXXXXXXXXXXXXXXXXXXXX
-1,50--1,40 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-1,40--1,30 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-1,30--1,20 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-1,20--1,10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-1,10--1,00 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-1,00--0,90 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,90--0,80 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,80--0,70 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,70--0,60 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,60--0,50 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,50--0,40 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,40--0,30 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,30--0,20 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,20--0,10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-0,10-0,00 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,00-0,10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,10-0,20 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,20-0,30 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,30-0,40 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,40-0,50 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,50-0,60 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,60-0,70 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,70-0,80 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,80-0,90 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0,90-1,00 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1,00-1,10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1,10-1,20 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1,20-1,30 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1,30-1,40 XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1,40-1,50 XXXXXXXXXXXXXXXXXXXXXXXXXX
1,50-1,60 XXXXXXXXXXXXXXXXXXXXXXXXX
1,60-1,70 XXXXXXXXXXXXXXXXXXXXXX
1,70-1,80 XXXXXXXXXXXXXXXXXX
1,80-1,90 XXXXXXXXXXXXXXX
1,90-2,00 XXXXXXXXXXX
2,00-2,10 XXXXXXXXXXXX
2,10-2,20 XXXXXXX
2,20-2,30 XXXXXX
2,30-2,40 XXXXX
2,40-2,50 XXX
2,50-2,60 XXXX
2,60-2,70 XX
2,70-2,80 XX
2,80-2,90 X
2,90-3,00 X
3,00-3,10 X
3,10-3,20 X
3,20-3,30
3,30-3,40
3,40-3,50 </pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<syntaxhighlight lang="wren">import "random" for Random
import "./fmt" for Fmt
import "./math" for Nums
 
var rgen = Random.new()
 
// Box-Muller method from Wikipedia
var normal = Fn.new { |mu, sigma|
var u1 = rgen.float()
var u2 = rgen.float()
var mag = sigma * (-2 * u1.log).sqrt
var z0 = mag * (2 * Num.pi * u2).cos + mu
var z1 = mag * (2 * Num.pi * u2).sin + mu
return [z0, z1]
}
 
var N = 100000
var NUM_BINS = 12
var HIST_CHAR = "■"
var HIST_CHAR_SIZE = 250
var bins = List.filled(NUM_BINS, 0)
var binSize = 0.1
var samples = List.filled(N, 0)
var mu = 0.5
var sigma = 0.25
for (i in 0...N/2) {
var rns = normal.call(mu, sigma)
for (j in 0..1) {
var rn = rns[j]
var bn
if (rn < 0) {
bn = 0
} else if (rn >= 1) {
bn = 11
} else {
bn = (rn/binSize).floor + 1
}
bins[bn] = bins[bn] + 1
samples[i*2 + j] = rn
}
}
 
Fmt.print("Normal distribution with mean $0.2f and S/D $0.2f for $,d samples:\n", mu, sigma, N)
System.print(" Range Number of samples within that range")
for (i in 0...NUM_BINS) {
var hist = HIST_CHAR * (bins[i] / HIST_CHAR_SIZE).round
if (i == 0) {
Fmt.print(" -∞ ..< 0.00 $s $,d", hist, bins[0])
} else if (i < NUM_BINS - 1) {
Fmt.print("$4.2f ..< $4.2f $s $,d", binSize * (i-1), binSize * i, hist, bins[i])
} else {
Fmt.print("1.00 ... +∞ $s $,d", hist, bins[NUM_BINS - 1])
}
}
Fmt.print("\nActual mean for these samples : $0.5f", Nums.mean(samples))
Fmt.print("Actual S/D for these samples : $0.5f", Nums.stdDev(samples))</syntaxhighlight>
 
{{out}}
Specimen run:
<pre>
Normal distribution with mean 0.50 and S/D 0.25 for 100,000 samples:
 
Range Number of samples within that range
-∞ ..< 0.00 ■■■■■■■■■ 2,243
0.00 ..< 0.10 ■■■■■■■■■■■■■ 3,250
0.10 ..< 0.20 ■■■■■■■■■■■■■■■■■■■■■■■■ 5,977
0.20 ..< 0.30 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 9,723
0.30 ..< 0.40 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 13,104
0.40 ..< 0.50 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 15,601
0.50 ..< 0.60 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 15,469
0.60 ..< 0.70 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 13,334
0.70 ..< 0.80 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ 9,659
0.80 ..< 0.90 ■■■■■■■■■■■■■■■■■■■■■■■■ 6,119
0.90 ..< 1.00 ■■■■■■■■■■■■■ 3,173
1.00 ... +∞ ■■■■■■■■■ 2,348
 
Actual mean for these samples : 0.50099
Actual S/D for these samples : 0.25051
</pre>
 
=={{header|zkl}}==
{{trans|Go}}
<langsyntaxhighlight lang="zkl">fcn norm2{ // Box-Muller
const PI2=(0.0).pi*2;;
rnd:=(0.0).random.fp(1); // random number in [0,1), using partial application
Line 2,862 ⟶ 4,082:
b:=(v + SIG)*BINS/SIG/2;
if(0<=b<BINS) h[b]+=1;
};</langsyntaxhighlight>
Partial application: rnd() --> (0.0).random(1). Basically, the fp method fixes the call parameters, which are then used when the partial thing is run.
<langsyntaxhighlight lang="zkl">foreach i in (N/2){ v1,v2:=norm2(); accum(v1); accum(v2); }
println("Samples: %,d".fmt(N));
println("Mean: ", m:=sum/N);
println("Stddev: ", (sumSq/N - m*m).sqrt());
foreach p in (h){ println("*"*(p/SCALE)) }</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits