Statistics/Normal distribution: Difference between revisions

m
m (→‎{{header|Phix}}: syntax coloured)
m (→‎{{header|Wren}}: Minor tidy)
 
(3 intermediate revisions by 3 users not shown)
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 522 ⟶ 767:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: assocs formatting kernel math math.functions
math.statistics random sequences sorting ;
 
Line 536 ⟶ 781:
[ [ CHAR: * ] "" replicate-as ] dip ! make the bar
"% 5.2f: %s %d\n" printf ! print a line of the histogram
] curry assoc-each</langsyntaxhighlight>
{{out}}
<pre style="font-size:80%; height: 120ex; overflow: scroll">
Line 645 ⟶ 890:
{{works with|Fortran|95 and later}}
Using the Marsaglia polar method
<langsyntaxhighlight lang="fortran">program Normal_Distribution
implicit none
 
Line 693 ⟶ 938:
end do
end program</langsyntaxhighlight>
{{out}}
<pre>
Line 768 ⟶ 1,013:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const pi As Double = 3.141592653589793
Line 854 ⟶ 1,099:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
Sample output:
{{out}}
Line 929 ⟶ 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 972 ⟶ 1,217:
fmt.Println(strings.Repeat("*", p/scale))
}
}</langsyntaxhighlight>
Output:
<pre>
Line 991 ⟶ 1,236:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Map (Map, empty, insert, findWithDefault, toList)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
Line 1,051 ⟶ 1,296:
main = do
runTest 1000
runTest 2000000</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,471:
=={{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,319 ⟶ 1,564:
.toArray());
}
}</langsyntaxhighlight>
<pre>Mean: -0.001870, SD: 0.500539
0.0: **
Line 1,353 ⟶ 1,598:
'''Preliminaries'''
<langsyntaxhighlight 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
Line 1,377 ⟶ 1,622:
def sample_mean_and_variance:
.mean = (.sum/.n)
| .variance = ((.ss / .n) - .mean*.mean);</langsyntaxhighlight>
'''The Task'''
<langsyntaxhighlight lang="jq"># Task parameters
def parameters: {
N: 100000,
Line 1,455 ⟶ 1,700:
histogram ;
 
task</langsyntaxhighlight>
{{out}}
<pre>
Line 1,479 ⟶ 1,724:
=={{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,486 ⟶ 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,495 ⟶ 1,740:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val rand = java.util.Random()
Line 1,551 ⟶ 1,796:
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) normalStats(sampleSize)
}</langsyntaxhighlight>
 
{{out}}
Line 1,625 ⟶ 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,686 ⟶ 1,931:
histogram(#n)
'\r\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 1,741 ⟶ 1,986:
=={{header|Liberty BASIC}}==
Uses LB Statistics/Basic
<langsyntaxhighlight lang="lb">call sample 100000
 
end
Line 1,792 ⟶ 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,838 ⟶ 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,883 ⟶ 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,911 ⟶ 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} ]]
Line 1,925 ⟶ 2,170:
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}}==
Line 1,941 ⟶ 2,186:
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.
 
<langsyntaxhighlight Nimlang="nim">import math, random, sequtils, stats, strformat, strutils
 
proc drawHistogram(ns: seq[float]) =
Line 1,980 ⟶ 2,225:
 
echo &"μ = {z.mean:.12f} σ = {z.standardDeviation:.12f}"
z.drawHistogram()</langsyntaxhighlight>
 
{{out}}
Line 2,023 ⟶ 2,268:
=={{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 2,045 ⟶ 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 2,068 ⟶ 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 2,078 ⟶ 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 2,209 ⟶ 2,454:
mySol := getSol(@rnorm,cMean,cStdDiv,1000000);
Histo(mySol,cHistCnt,cColLen);
end.</langsyntaxhighlight>
{{out}}<pre>
function randg
Line 2,270 ⟶ 2,515:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use constant pi => 3.14159265;
use List::Util qw(sum reduce min max);
 
Line 2,301 ⟶ 2,546:
print "$i\t$t1$t2\n";
}
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:35ex">32 ⎸
Line 2,341 ⟶ 2,586:
=={{header|Phix}}==
{{trans|Liberty_BASIC}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,372 ⟶ 2,617:
<span style="color: #000000;">sample</span><span style="color: #0000FF;">(</span><span style="color: #000000;">100000</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 2,417 ⟶ 2,662:
</pre>
{{trans|Lua}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 2,457 ⟶ 2,702:
<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>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 2,492 ⟶ 2,737:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Procedure.f randomf(resolution = 2147483647)
ProcedureReturn Random(resolution) / resolution
EndProcedure
Line 2,556 ⟶ 2,801:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>100000 data terms used.
Line 2,595 ⟶ 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,609 ⟶ 2,854:
% (mn, sd, max(data), min(data), size))
 
plt.hist(data,bins=50)</langsyntaxhighlight>
 
{{out}}
Line 2,619 ⟶ 2,864:
 
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.
<langsyntaxhighlight lang="r">n <- 100000
u <- sqrt(-2*log(runif(n)))
v <- 2*pi*runif(n)
x <- u*cos(v)
y <- v*sin(v)
hist(x)</langsyntaxhighlight>
 
 
R can generate random normal distributed numbers using the [https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Normal.html rnorm] function:
<langsyntaxhighlight lang="r">n <- 100000
x <- rnorm(n, mean=0, sd=1)
mean(x)
sd(x)
hist(x)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,638 ⟶ 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,652 ⟶ 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,658 ⟶ 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,678 ⟶ 2,923:
(set! next (* scale v2))
(+ μ (* σ scale v1))])))))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>sub normdist ($m, $σ) {
my $r = sqrt -2 * log rand;
my $Θ = τ * rand;
Line 2,707 ⟶ 2,952:
say $i, "\t", '█' x $full, @subbar[$part];
}
}</langsyntaxhighlight>
{{out}}
<pre>"m" => 50.006107405837142e0
Line 2,750 ⟶ 2,995:
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 twenty decimal digs for accuracy.*/
parse arg n seed . /*obtain optional arguments from the CL*/
Line 2,803 ⟶ 3,048:
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,873 ⟶ 3,118:
{{works with|Ruby|2.7}}
'''The Implementation'''
<langsyntaxhighlight lang="ruby"># Class to implement a Normal distribution, generated from a Uniform distribution.
# Uses the Marsaglia polar method.
 
Line 2,899 ⟶ 3,144:
end
end
end</langsyntaxhighlight>
'''The Task'''
{{libheader|enumerable-statistics}}
<langsyntaxhighlight lang="ruby">require('enumerable/statistics')
 
def show_stats_and_histogram(data, bins)
Line 2,931 ⟶ 3,176:
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)</langsyntaxhighlight>
{{out}}
<pre style="height: 200ex; overflow: scroll">
Line 3,085 ⟶ 3,330:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">
s = 100000
h$ = "============================================================="
Line 3,127 ⟶ 3,372:
print using("##",b);" ";using("#####",bins(b));" ";left$(h$,(bins(b) / mb) * 90)
next b
END</langsyntaxhighlight>
{{out}}
<pre>
Line 3,177 ⟶ 3,422:
{{libheader|rand}}
{{libheader|rand_distr}}
<langsyntaxhighlight lang="rust">//! Rust rosetta example for normal distribution
use math::{histogram::Histogram, traits::ToIterator};
use rand;
Line 3,249 ⟶ 3,494:
print_histogram(&data, 80, 40, '-');
}
}</langsyntaxhighlight>
{{out}}
<pre style="height: 120ex; overflow: scroll">
Line 3,389 ⟶ 3,634:
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">data test;
n=100000;
twopi=2*constant('pi');
Line 3,416 ⟶ 3,661:
y 0.000023995 1.0019996
z 0.0012857 1.0056536
*/</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">define τ = Num.tau
 
func normdist (m, σ) {
Line 3,450 ⟶ 3,695:
var part = (8 * (x - full))
say (i, "\t", '█' * full, subbar[part])
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,494 ⟶ 3,739:
Pairs of normal numbers are generated from pairs of uniform numbers using the [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.
 
<langsyntaxhighlight lang="stata">clear all
set obs 100000
gen u=runiform()
Line 3,512 ⟶ 3,757:
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 3,553 ⟶ 3,798:
stats 10000
puts ""
stats 100000 20</langsyntaxhighlight>
Sample output:
<pre>
Line 3,648 ⟶ 3,893:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
Line 3,665 ⟶ 3,910:
Debug.Print
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre>sample size 20000 mean-5,26306310478751E-03 standard deviation 1,00355037427319
-3,60--3,50
Line 3,742 ⟶ 3,987:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
import "./math" for Nums
 
var rgen = Random.new()
Line 3,797 ⟶ 4,042:
}
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))</langsyntaxhighlight>
 
{{out}}
Line 3,824 ⟶ 4,069:
=={{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 3,837 ⟶ 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