Random numbers: Difference between revisions

→‎{{header|BASIC}}: Added ANSI BASIC.
(Added PowerShell)
(→‎{{header|BASIC}}: Added ANSI BASIC.)
(131 intermediate revisions by 53 users not shown)
Line 1:
{{task|Basic language learning}}
[[Category:Probability and statistics]] [[Category:Randomness]]
[[Category:Randomness]]
{{omit from|GUISS}}
{{omit from|UNIX Shell|From the shell, we simply invoke the awk solution}}
 
;Task:
The goal of this task is to generate a collection filled with
Generate a collection filled with   '''1000'''   normally distributed random (or pseudorandompseudo-random) numbers
with a mean of   '''1.0'''   and a   [[wp:Standard_deviation|standard deviation]]   of   '''0.5'''
 
Many libraries only generate uniformly distributed random numbers. If so, you may use [[wp:Normal_distribution#Generating_values_from_normal_distribution|one of these algorithms]].
 
;Related task:
If so, use [[wp:Normal_distribution#Generating_values_from_normal_distribution|this formula]] to convert them to a normal distribution.
*   [[Standard deviation]]
 
<br><br>
;See also:
* [[Standard deviation]]
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 38:
Distribution (I) := Normal_Distribution (Seed);
end loop;
end Normal_Random;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|C}}
Line 46 ⟶ 47:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">PROC random normal = REAL: # normal distribution, centered on 0, std dev 1 #
(
sqrt(-2*log(random)) * cos(2*pi*random)
Line 58 ⟶ 59:
INT limit=10;
printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit]))
)</langsyntaxhighlight>
{{out}}
<pre>
( 0.693461, 0.948424, 0.482261, 1.045939, 0.890818, 1.467935, 0.604153, 0.804811, 0.690227, 0.83462 ... )
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">rnd: function []-> (random 0 10000)//10000
 
rands: map 1..1000 'x [
1 + (sqrt neg 2 * ln rnd) * (cos 2 * pi * rnd)
]
 
print rands</syntaxhighlight>
 
{{out}}
 
<pre>0.6219537961087694 1.279396486161406 1.619019280815647 2.119538294228789 -0.1598383851981044 2.67797211803156 0.9304703037226587 1.629254364659528 -0.4171704717398712 0.9082342931486092 -0.5929704390625219 2.117000897984871 -0.1981633787460266 0.01132471973856153 2.102359263212924 0.2408823232884222 2.046195035792376 0.6374831627030295 0.000839808324124558 1.117061838266626 0.7413355299469649 0.4485598815755762 2.999434800016997 2.560580541932842 1.703197984879731 2.889159248353575 -1.800157205708138 1.756810020187321 0.7136708180852145 0.5929151678321705 0.332519993787973 2.660212054362758 0.5835660585480075 0.8527946892567934 1.640573993747053 0.09471843345263908 1.051402997891346 1.116149156137905 -0.7400139019343499 1.782572831979232 2.531779039786426 0.5240268064639871 0.07099232630526586 -0.854892656700071 1.54381929430469 -0.4416899008614745 0.4274356035015117 0.7350027625573482 2.153583935076981 1.461215281535983 -1.041723064151266 2.338060763553139 -0.1492967916030414 0.3799517724040202 0.4577924541353815 0.673317567666373 -2.27731583876462 1.28480355806061 -0.6925811023772748 -0.2642224122781984 0.6590513830891744 2.55537133425143 1.67933335469247 0.8659013395355968 -1.211026941441126 0.9524579534222226 -0.1931750631835656 -0.5119479869237693 0.1814749003063878 3.03139579963414 ...</pre>
 
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk
[http://www.autohotkey.com/forum/post-276261.html#276261 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop 40
R .= RandN(1,0.5) "`n" ; mean = 1.0, standard deviation = 0.5
MsgBox %R%
Line 81 ⟶ 96:
}
Return Y
}</syntaxhighlight>
}</lang>
 
=={{header|Avail}}==
<syntaxhighlight lang="avail">Method "U(_,_)" is
[
lower : number,
upper : number
|
divisor ::= ((1<<32)) ÷ (upper - lower)→double;
map a pRNG through [i : integer | (i ÷ divisor) + lower]
];
 
Method "a Marsaglia polar sampler" is
[
generator for
[
yield : [double]→⊤
|
source ::= U(-1, 1);
Repeat [
x ::= take 1 from source[1];
y ::= take 1 from source[1];
s ::= x^2 + y^2;
If 0 < s < 1 then
[
factor ::= ((-2 × ln s) ÷ s) ^ 0.5;
yield(x × factor);
yield(y × factor);
];
]
]
];
 
// the default distribution has mean 0 and std dev 1.0, so we scale the values
sampler ::= map a Marsaglia polar sampler through [d : double | d ÷ 2.0 + 1.0];
values ::= take 1000 from sampler;</syntaxhighlight>
 
=={{header|AWK}}==
'''One-liner:'''
<langsyntaxhighlight lang="awk">$ awk 'func r(){return sqrt(-2*log(rand()))*cos(6.2831853*rand())}BEGIN{for(i=0;i<1000;i++)s=s" "1+0.5*r();print s}'</langsyntaxhighlight>
 
'''Readable version:'''
<langsyntaxhighlight lang="awk">
function r() {
return sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() )
Line 101 ⟶ 151:
print s
}
</syntaxhighlight>
</lang>
{{out}} first few values only
<pre>
Line 108 ⟶ 158:
 
=={{header|BASIC}}==
==={{header|ANSI BASIC}}===
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
RANDOMIZE TIMER 'seeds random number generator with the system time
{{works with|Decimal BASIC}}
pi = 3.141592653589793#
<syntaxhighlight lang="basic">
DIM a(1 TO 1000) AS DOUBLE
100 REM Random numbers
CLS
110 RANDOMIZE
FOR i = 1 TO 1000
120 DEF a(i)RandomNormal = 1 + SQRCOS(-2 * LOG(PI * RND)) * COSSQR(-2 * pi * LOG(RND))
130 DIM R(0 TO 999)
NEXT i
140 LET Sum = 0
150 FOR I = 0 TO 999
160 LET R(I) = 1 + RandomNormal / 2
170 LET Sum = Sum + R(I)
180 NEXT I
190 LET Mean = Sum / 1000
200 LET Sum = 0
210 FOR I = 0 TO 999
220 LET Sum = Sum + (R(I) - Mean) ^ 2
230 NEXT I
240 LET SD = SQR(Sum / 1000)
250 PRINT "Mean is "; Mean
260 PRINT "Standard Deviation is"; SD
270 PRINT
280 END
</syntaxhighlight>
{{out}} Two runs.
<pre>
Mean is 1.00216454061435
Standard Deviation is .504515904812839
</pre>
<pre>
Mean is .995781408878628
Standard Deviation is .499307289407576
</pre>
 
==={{header|BBCApplesoft BASIC}}===
The [[Random_numbers#Commodore_BASIC|Commodore BASIC]] code works in Applesoft BASIC.
<lang bbcbasic> DIM array(999)
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256"># Generates normally distributed random numbers with mean 0 and standard deviation 1
function randomNormal()
return cos(2.0 * pi * rand) * sqr(-2.0 * log(rand))
end function
 
dim r(1000)
sum = 0.0
# Generate 1000 normally distributed random numbers
# with mean 1 and standard deviation 0.5
# and calculate their sum
for i = 0 to 999
r[i] = 1.0 + randomNormal() / 2.0
sum += r[i]
next i
 
mean = sum / 1000.0
sum = 0.0
# Now calculate their standard deviation
for i = 0 to 999
sum += (r[i] - mean) ^ 2.0
next i
sd = sqr(sum/1000.0)
 
print "Mean is "; mean
print "Standard Deviation is "; sd
end</syntaxhighlight>
{{out}}
<pre>Mean is 1.002092
Standard Deviation is 0.4838570687</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> DIM array(999)
FOR number% = 0 TO 999
array(number%) = 1.0 + 0.5 * SQR(-2*LN(RND(1))) * COS(2*PI*RND(1))
Line 128 ⟶ 238:
PRINT "Mean = " ; mean
PRINT "Standard deviation = " ; stdev</langsyntaxhighlight>
{{out}}
<pre>Mean = 1.01848064
Standard deviation = 0.503551814</pre>
 
==={{header|Chipmunk Basic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic">
10 ' Random numbers
20 randomize timer
30 dim r(999)
40 sum = 0
50 for i = 0 to 999
60 r(i) = 1+randomnormal()/2
70 sum = sum+r(i)
80 next
90 mean = sum/1000
100 sum = 0
110 for i = 0 to 999
120 sum = sum+(r(i)-mean)^2
130 next
140 sd = sqr(sum/1000)
150 print "Mean is ";mean
160 print "Standard Deviation is ";sd
170 print
180 end
 
500 sub randomnormal()
510 randomnormal = cos(2*pi*rnd(1))*sqr(-2*log(rnd(1)))
520 end sub
</syntaxhighlight>
{{out}}
Two runs.
<pre>
Mean is 1.007087
Standard Deviation is 0.496848
</pre>
<pre>
Mean is 0.9781
Standard Deviation is 0.508147
</pre>
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="bbcbasic">
10 DIM AR(999): DIM DE(999)
20 FOR N = 0 TO 999
30 AR(N)= 0 + SQR(-1.3*LOG(RND(1))) * COS(1.2*PI*RND(1))
40 NEXT N
50 :
60 REM SUM
70 LET SU = 0
80 FOR N = 0 TO 999
90 LET SU = SU + AR(N)
100 NEXT N
110 :
120 REM MEAN
130 LET ME= 0
140 LET ME = SU/1000
150 :
160 REM DEVIATION
170 FOR N = 0 TO 999
180 T = AR(N)-ME: REM SUBTRACT MEAN FROM NUMBER
190 T = T * T: REM SQUARE THE RESULT
200 DE(N) = T : REM STORE IN DEVIATION ARRAY
210 NEXT N
220 LET DS=0: REM SUM OF DEVIATION ARRAY
230 FOR N = 0 TO 999
240 LET DS = DS + DE(N)
250 NEXT N
260 LET DM=0: REM MEAN OF DEVIATION ARRAY
270 LET DM = DS / 1000
280 LET DE = 0:
290 LET DE = SQR(DM)
300 :
310 PRINT "MEAN = "ME
320 PRINT "STANDARD DEVIATION ="DE
330 END
</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const pi As Double = 3.141592653589793
Randomize
 
' Generates normally distributed random numbers with mean 0 and standard deviation 1
Function randomNormal() As Double
Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd))
End Function
 
Dim r(0 To 999) As Double
Dim sum As Double = 0.0
 
' Generate 1000 normally distributed random numbers
' with mean 1 and standard deviation 0.5
' and calculate their sum
For i As Integer = 0 To 999
r(i) = 1.0 + randomNormal/2.0
sum += r(i)
Next
 
Dim mean As Double = sum / 1000.0
 
Dim sd As Double
sum = 0.0
' Now calculate their standard deviation
For i As Integer = 0 To 999
sum += (r(i) - mean) ^ 2.0
Next
sd = Sqr(sum/1000.0)
 
Print "Mean is "; mean
Print "Standard Deviation is"; sd
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
Sample result:
{{out}}
<pre>
Mean is 1.000763573902885
Standard Deviation is 0.500653063426955
</pre>
 
==={{header|FutureBasic}}===
Note: To generate the random number, rather than using FB's native "rnd" function, this code wraps C code into the RandomZeroToOne function.
<syntaxhighlight lang="futurebasic">window 1
 
local fn RandomZeroToOne as double
double result
cln result = (double)( (rand() % 100000 ) * 0.00001 );
end fn = result
 
local fn RandomGaussian as double
double r = fn RandomZeroToOne
end fn = 1 + .5 * ( sqr( -2 * log(r) ) * cos( 2 * pi * r ) )
 
long i
double mean, std, a(1000)
 
for i = 1 to 1000
a(i) = fn RandomGaussian
mean += a(i)
next
mean = mean / 1000
 
for i = 1 to 1000
std += ( a(i) - mean )^2
next
std = std / 1000
 
print " Average: "; mean
print "Standard Deviation: "; std
 
HandleEvents</syntaxhighlight>
{{output}}
<pre>
Average: 1.053724951604593
Standard Deviation: 0.2897370762627166
</pre>
 
==={{header|GW-BASIC}}===
The [[Random_numbers#Commodore_BASIC|Commodore BASIC]] code works in GW-BASIC.
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000 ' throw 1000 normal variates
a( i) =mean +sd *( sqr( -2 * log( rnd( 0))) * cos( 2 * pi * rnd( 0)))
next i</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic">
10 REM Random numbers
20 LET P = 4*ATN(1)
30 RANDOMIZE
40 DEF FNN = COS(2*P*RND)*SQR(-2*LOG(RND))
50 DIM R(999)
60 LET S = 0
70 FOR I = 0 TO 999
80 LET R(I) = 1+FNN/2
90 LET S = S+R(I)
100 NEXT I
110 LET M = S/1000
120 LET S = 0
130 FOR I = 0 TO 999
140 LET S = S+(R(I)-M)^2
150 NEXT I
160 LET D = SQR(S/1000)
170 PRINT "Mean is "; M
180 PRINT "Standard Deviation is"; D
190 PRINT
200 END
</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.f RandomNormal()
; This procedure can return any real number.
Protected.f x1, x2
 
; random numbers from the open interval ]0, 1[
x1 = (Random(999998)+1) / 1000000 ; must be > 0 because of Log(x1)
x2 = (Random(999998)+1) / 1000000
 
ProcedureReturn Sqr(-2*Log(x1)) * Cos(2*#PI*x2)
EndProcedure
 
Define i, n=1000
 
Dim a.q(n-1)
For i = 0 To n-1
a(i) = 1 + 0.5 * RandomNormal()
Next</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">
RANDOMIZE TIMER 'seeds random number generator with the system time
pi = 3.141592653589793#
DIM a(1 TO 1000) AS DOUBLE
CLS
FOR i = 1 TO 1000
a(i) = 1 + SQR(-2 * LOG(RND)) * COS(2 * pi * RND)
NEXT i
</syntaxhighlight>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">dim a(1000)
pi = 22/7
for i = 1 to 1000
a( i) = 1 + .5 * (sqr(-2 * log(rnd(0))) * cos(2 * pi * rnd(0)))
next i</syntaxhighlight>
 
==={{header|TI-83 BASIC}}===
Built-in function: randNorm()
randNorm(1,.5)
 
Or by a program:
 
Calculator symbol translations:
 
"STO" arrow: &#8594;
 
Square root sign: &#8730;
 
ClrList L<sub>1</sub>
Radian
For(A,1,1000)
√(-2*ln(rand))*cos(2*π*A)→L<sub>1</sub>(A)
End
 
==={{header|ZX Spectrum Basic}}===
Here we have converted the QBasic code to suit the ZX Spectrum:
<syntaxhighlight lang="zxbasic">10 RANDOMIZE 0 : REM seeds random number generator based on uptime
20 DIM a(1000)
30 CLS
40 FOR i = 1 TO 1000
50 LET a(i) = 1 + SQR(-2 * LN(RND)) * COS(2 * PI * RND)
60 NEXT i</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <math.h>
#ifndef M_PI
Line 155 ⟶ 521:
rands[i] = 1.0 + 0.5*random_normal();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="csharp">
private static double randomNormal()
{
return Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble()));
}
</syntaxhighlight>
</lang>
 
Then the methods in [[Random numbers#Metafont]] are used to calculate the average and the Standard Deviation:
<langsyntaxhighlight lang="csharp">
static Random tRand = new Random();
 
Line 195 ⟶ 561:
Console.ReadLine();
}
</syntaxhighlight>
</lang>
 
An example result:
Line 208 ⟶ 574:
The new C++ standard looks very similar to the Boost library example below.
 
<langsyntaxhighlight lang="cpp">#include <random>
#include <functional>
#include <vector>
Line 224 ⟶ 590:
generate(v.begin(), v.end(), rnd);
return 0;
}</langsyntaxhighlight>
 
{{works with|C++03}}
<langsyntaxhighlight lang="cpp">#include <cstdlib> // for rand
#include <cmath> // for atan, sqrt, log, cos
#include <algorithm> // for generate_n
Line 253 ⟶ 619:
std::generate_n(array, 1000, normal_distribution(1.0, 0.5));
return 0;
}</langsyntaxhighlight>
 
{{libheader|Boost}}
Line 259 ⟶ 625:
This example used Mersenne Twister generator. It can be changed by changing the typedef.
 
<langsyntaxhighlight lang="cpp">
#include <vector>
#include "boost/random.hpp"
Line 280 ⟶ 646:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(import '(java.util Random))
(def normals
(let [r (Random.)]
(take 1000 (repeatedly #(-> r .nextGaussian (* 0.5) (+ 1.0))))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. RANDOM.
AUTHOR. Bill Gunshannon
INSTALLATION. Home.
DATE-WRITTEN. 14 January 2022.
************************************************************
** Program Abstract:
** Able to get the Mean to be really close to 1.0 but
** couldn't get the Standard Deviation any closer than
** .3 to .4.
************************************************************
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Sample-Size PIC 9(5) VALUE 1000.
01 Total PIC 9(10)V9(5) VALUE 0.0.
01 Arith-Mean PIC 999V999 VALUE 0.0.
01 Std-Dev PIC 999V999 VALUE 0.0.
01 Seed PIC 999V999.
01 TI PIC 9(8).
 
01 Idx PIC 99999 VALUE 0.
01 Intermediate PIC 9(10)V9(5) VALUE 0.0.
01 Rnd-Work.
05 Rnd-Tbl
OCCURS 1 TO 99999 TIMES DEPENDING ON Sample-Size.
10 Rnd PIC 9V9999999 VALUE 0.0.
PROCEDURE DIVISION.
Main-Program.
ACCEPT TI FROM TIME.
MOVE FUNCTION RANDOM(TI) TO Seed.
PERFORM WITH TEST AFTER VARYING Idx
FROM 1 BY 1
UNTIL Idx = Sample-Size
COMPUTE Intermediate =
(FUNCTION RANDOM() * 2.01)
MOVE Intermediate TO Rnd(Idx)
END-PERFORM.
PERFORM WITH TEST AFTER VARYING Idx
FROM 1 BY 1
UNTIL Idx = Sample-Size
COMPUTE Total = Total + Rnd(Idx)
END-PERFORM.
 
 
COMPUTE Arith-Mean = Total / Sample-Size.
DISPLAY "Mean: " Arith-Mean.
 
 
PERFORM WITH TEST AFTER VARYING Idx
FROM 1 BY 1
UNTIL Idx = Sample-Size
COMPUTE Intermediate =
Intermediate + (Rnd(Idx) - Arith-Mean) ** 2
END-PERFORM.
COMPUTE Std-Dev = Intermediate / Sample-Size.
 
 
DISPLAY "Std-Dev: " Std-Dev.
 
STOP RUN.
END PROGRAM RANDOM.
 
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(loop for i from 1 to 1000
collect (1+ (* (sqrt (* -2 (log (random 1.0)))) (cos (* 2 pi (random 1.0))) 0.5)))</langsyntaxhighlight>
 
=={{header|Crystal}}==
{{trans|Phix}}
<syntaxhighlight lang="ruby">n, mean, sd, tau = 1000, 1, 0.5, (2 * Math::PI)
array = Array.new(n) { mean + sd * Math.sqrt(-2 * Math.log(rand)) * Math.cos(tau * rand) }
 
mean = array.sum / array.size
standev = Math.sqrt( array.sum{ |x| (x - mean) ** 2 } / array.size )
puts "mean = #{mean}, standard deviation = #{standev}"</syntaxhighlight>
{{out}}
<pre>mean = 1.0093442539237896, standard deviation = 0.504694489463623</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.math;
 
struct NormalRandom {
Line 316 ⟶ 765:
//x = nRnd;
x = nRnd();
}</langsyntaxhighlight>
 
===Alternative Version===
Line 322 ⟶ 771:
{{libheader|tango}}
 
<langsyntaxhighlight lang="d">import tango.math.random.Random;
 
void main() {
Line 331 ⟶ 780:
l = 1.0 + 0.5 * l;
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 337 ⟶ 786:
Delphi has RandG function which generates random numbers with normal distribution using Marsaglia-Bray algorithm:
 
<langsyntaxhighlight Delphilang="delphi">program Randoms;
 
{$APPTYPE CONSOLE}
Line 355 ⟶ 804:
Writeln('Std Deviation = ', StdDev(Values):6:4);
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Mean = 1.0098
Line 361 ⟶ 810:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">var values : array [0..999] of Float;
var i : Integer;
 
for i := values.Low to values.High do
values[i] := RandG(1, 0.5);</langsyntaxhighlight>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">accum [] for _ in 1..1000 { _.with(entropy.nextGaussian()) }</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
numfmt 5 0
e = 2.7182818284590452354
for i = 1 to 1000
a[] &= 1 + 0.5 * sqrt (-2 * log10 randomf / log10 e) * cos (360 * randomf)
.
for v in a[]
avg += v / len a[]
.
print "Average: " & avg
for v in a[]
s += pow (v - avg) 2
.
s = sqrt (s / len a[])
print "Std deviation: " & s
 
</syntaxhighlight>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 467 ⟶ 936:
end
end
</syntaxhighlight>
</lang>
 
Example Result
Line 473 ⟶ 942:
Average: 1.0079398405028137
Standard Deviation: 0.49042787564453988
</pre>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 6.x :
<syntaxhighlight lang="elena">import extensions;
import extensions'math;
randomNormal()
{
^ cos(2 * Pi_value * randomGenerator.nextReal())
* sqrt(-2 * ln(randomGenerator.nextReal()))
}
public program()
{
real[] a := new real[](1000);
real tAvg := 0;
for (int x := 0; x < a.Length; x += 1)
{
a[x] := (randomNormal()) / 2 + 1;
tAvg += a[x]
};
tAvg /= a.Length;
console.printLine("Average: ", tAvg);
real s := 0;
for (int x := 0; x < a.Length; x += 1)
{
s += power(a[x] - tAvg, 2)
};
s := sqrt(s / 1000);
console.printLine("Standard Deviation: ", s);
console.readChar()
}</syntaxhighlight>
{{out}}
<pre>
Average: 0.9842420481571
Standard Deviation: 0.5109070975558
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Random do
<lang elixir>
defmodule Random do
def init() do
:random.seed(:erlang.now())
end
def normal(mean, sd) do
{a, b} = {:randomrand.uniform(), :randomrand.uniform()}
mean + sd * (:math.sqrt(-2 * :math.log(a)) * :math.cos(2 * :math.pi * b))
end
end
 
std_dev = fn (list) ->
Random.init()
mean = Enum.sum(list) / length(list)
sd = Enum.reduce(list, 0, fn x,acc -> acc + (x-mean)*(x-mean) end) / length(list)
|> :math.sqrt
IO.puts "Mean: #{mean},\tStdDev: #{sd}"
end
 
xs = for _ <- 1..1000, do: Random.normal(1.0, 0.5)
std_dev.(xs)</syntaxhighlight>
</lang>
{{out}}
<pre>
Mean: 1.009079383094275, StdDev: 0.4991894476975088
</pre>
 
used Erlang function <code>:rand.normal</code>
<syntaxhighlight lang="elixir">xs = for _ <- 1..1000, do: 1.0 + :rand.normal * 0.5
std_dev.(xs)</syntaxhighlight>
{{out}}
<pre>
Mean: 0.9955701150615597, StdDev: 0.5036412260426065
</pre>
 
=={{header|Erlang}}==
{{works with|Erlang}}
 
<langsyntaxhighlight lang="erlang">
mean(Values) ->
mean(tl(Values), hd(Values), 1).
Line 526 ⟶ 1,053:
io:format("mean = ~w\n", [mean(X)]),
io:format("stddev = ~w\n", [stddev(X)]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 534 ⟶ 1,061:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM DISTRIBUTION
 
Line 570 ⟶ 1,097:
 
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>v=normal(1,1000)*0.5+1;
>mean(v), dev(v)
1.00291801071
0.498226876528
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{trans|PureBasic}}
<langsyntaxhighlight lang="euphoria">include misc.e
 
function RandomNormal()
Line 597 ⟶ 1,124:
for i = 1 to n do
s[i] = 1 + 0.5 * RandomNormal()
end for</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let n = MathNet.Numerics.Distributions.Normal(1.0,0.5)
List.init 1000 (fun _->n.Sample())
</syntaxhighlight>
{{out}}
<pre>
[0.734433576; 1.54225304; 0.4407528678; 1.177675412; 0.4318617021;
0.6026656337; 0.769764924; 1.104693934; 0.6297500925; 0.9594598077;
1.684736389; 1.160376323; 0.883354356; 0.9513968363; 0.9727698268;
0.5315570949; 0.9599239266; 1.564976755; 0.7232002879; 1.084139442;
1.220914517; 0.3553085946; 1.112549824; 1.989443553; 0.5752307543;
1.156682549; 0.7886670467; 0.02050745923; 1.532060208; 1.18789591;
1.408946777; 1.038812004; 1.724679503; 1.671565045; 1.266831442;
1.363611654; 1.705819067; 0.5772366328; 0.4503488498; 1.496891481;
0.9831877282; 0.3845460366; 0.8253240671; 1.298969969; 0.4265904553;
0.9303696876; 0.445003361; 0.753175816; 0.6143534043; 1.059982235;
0.7143206784; 0.2233328038; 1.005178481; 0.7697392436; 0.5904948577;
0.5127953044; 0.6467346747; 0.7929387604; -0.1501790761; 0.8750780903;
0.941704369; 1.37941579; 0.4739006145; 1.998886344; 1.219428519;
0.06270791476; 1.097739804; 0.7584232803; 1.042177217; 1.166561247;
1.502357164; 1.171525776; 0.1528807432; 0.2289389756; 1.36208422;
0.3714421124; 1.299571092; 1.171553369; 1.317807265; 1.616662281;
1.724223246; 1.059580642; 1.270520918; -0.1827677907; 1.938593232;
1.420362143; 1.888357595; 0.7851629936; 0.7080554899; 0.7747215818;
1.403719877; 0.5765950249; 1.275206565; 0.6292054813; 1.525562798;
0.6224640457; 0.8524078517; 0.7646595627; 0.6799834691; 0.773111053; ...]
</pre> =={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let gaussianRand count =
let o = new System.Random()
let pi = System.Math.PI
let gaussrnd =
(fun _ -> 1. + 0.5 * sqrt(-2. * log(o.NextDouble())) * cos(2. * pi * o.NextDouble()))
[ for i in {0 .. (int count)} -> gaussrnd() ]</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang ="factor">1000USING: [ 1.0 0.5 normal-random-float ] replicate</lang>;
1000 [ 1.0 0.5 normal-random-float ] replicate</syntaxhighlight>
 
=={{header|Falcon|}}==
<langsyntaxhighlight lang="falcon">a = []
for i in [0:1000] : a+= norm_rand_num()
 
Line 609 ⟶ 1,172:
pi = 2*acos(0)
return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2
end</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 615 ⟶ 1,178:
Two solutions. The first uses Fantom's random-number generator, which produces a uniform distribution. So, convert to a normal distribution using a formula:
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 633 ⟶ 1,196:
}
}
</syntaxhighlight>
</lang>
 
The second calls out to Java's Gaussian random-number generator:
 
<langsyntaxhighlight lang="fantom">
using [java] java.util::Random
 
Line 658 ⟶ 1,221:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
 
<langsyntaxhighlight lang="forth">require random.fs
here to seed
 
Line 678 ⟶ 1,241:
0 do frnd-normal 0.5e f* 1e f+ f, loop ;
 
create rnd-array 1000 ,normals</langsyntaxhighlight>
 
For newer versions of gforth (tested on 0.7.3), it seems you need to use <tt>HERE SEED !</tt> instead of <tt>HERE TO SEED</tt>, because <tt>SEED</tt> has been made a variable instead of a value.
 
<syntaxhighlight lang="text">rnd rnd dabs d>f</syntaxhighlight> is necessary, but surprising and definitely not well documented / perhaps not compliant.
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM Random
 
INTEGER, PARAMETER :: n = 1000
Line 705 ⟶ 1,272:
WRITE(*, "(A,F8.6)") "Standard Deviation = ", sd
 
END PROGRAM Random</langsyntaxhighlight>
 
{{out}}
Line 716 ⟶ 1,283:
Free Pascal provides the '''randg''' function in the RTL math unit that produces Gaussian-distributed random numbers with the Box-Müller algorithm.
 
<langsyntaxhighlight lang="pascal">
function randg(mean,stddev: float): float;
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#Frink}}==
<syntaxhighlight lang="frink">a = new array[[1000], {|x| randomGaussian[1, 0.5]}]</syntaxhighlight>
<lang fsharp>let gaussianRand count =
let o = new System.Random()
let pi = System.Math.PI
let gaussrnd =
(fun _ -> 1. + 0.5 * sqrt(-2. * log(o.NextDouble())) * cos(2. * pi * o.NextDouble()))
[ for i in {0 .. (int count)} -> gaussrnd() ]</lang>
 
=={{header|Go}}==
This solution uses math/rand package in the standard library. See also though the subrepository rand package at https://godoc.org/golang.org/x/exp/rand, which also has a NormFloat64 and has a rand source with a number of advantages over the one in standard library.
<lang go>package main
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
Line 738 ⟶ 1,304:
const mean = 1.0
const stdv = .5
const n = 1000
 
func main() {
var list [1000n]float64
rand.Seed(time.Now().UnixNano())
for i := range list {
list[i] = mean + stdv*rand.NormFloat64()
}
// show computed mean and stdv of list
}</lang>
var s, sq float64
for _, v := range list {
s += v
}
cm := s / n
for _, v := range list {
d := v - cm
sq += d * d
}
fmt.Printf("mean %.3f, stdv %.3f\n", cm, math.Sqrt(sq/(n-1)))
// show histogram by hdiv divisions per stdv over +/-hrange stdv
const hdiv = 3
const hrange = 2
var h [1 + 2*hrange*hdiv]int
for _, v := range list {
bin := hrange*hdiv + int(math.Floor((v-mean)/stdv*hdiv+.5))
if bin >= 0 && bin < len(h) {
h[bin]++
}
}
const hscale = 10
for _, c := range h {
fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
}
}</syntaxhighlight>
{{out}}
<pre>
mean 0.995, stdv 0.503
**
****
******
********
************
************
*************
************
**********
********
*****
***
**
</pre>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">rnd = new Random()
result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import System.Random
 
pairs :: [a] -> [(a,a)]
Line 766 ⟶ 1,375:
 
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g</langsyntaxhighlight>
 
Or using Data.Random from random-fu package:
<syntaxhighlight lang="haskell">replicateM 1000 $ normal 1 0.5</syntaxhighlight>
To print them:
<syntaxhighlight lang="haskell">import Data.Random
import Control.Monad
 
thousandRandomNumbers :: RVar [Double]
thousandRandomNumbers = replicateM 1000 $ normal 1 0.5
 
main = do
x <- sample thousandRandomNumbers
print x</syntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=1000, m=1, s=0.5, array(n)
 
pi = 4 * ATAN(1)
array = s * (-2*LOG(RAN(1)))^0.5 * COS(2*pi*RAN(1)) + m </langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 778 ⟶ 1,400:
 
Note that Unicon randomly seeds it's generator.
<langsyntaxhighlight lang="icon">
procedure main()
local L
Line 786 ⟶ 1,408:
every write(!L)
end
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">result = 1.0 + 0.5*randomn(seed,1000)</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">urand=: ?@$ 0:
zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand
 
1 + 0.5 * zrand 100</langsyntaxhighlight>
 
'''Alternative Solution:'''<br>
Using the normal script from the [[j:Addons/stats/distribs|stats/distribs addon]].
<langsyntaxhighlight lang="j"> require 'stats/distribs/normal'
1 0.5 rnorm 1000
1.44868803 1.21548637 0.812460657 1.54295452 1.2470606 ...</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">double[] list = new double[1000];
double mean = 1.0, std = 0.5;
Random rng = new Random();
for(int i = 0;i<list.length;i++) {
list[i] = mean + std * rng.nextGaussian();
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function randomNormal() {
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
Line 820 ⟶ 1,442:
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 833 ⟶ 1,455:
 
''''A Pseudo-Random Number Generator''''
<langsyntaxhighlight lang="jq"># 15-bit integers generated using the same formula as rand() from the Microsoft C Runtime.
# The random numbers are in [0 -- 32767] inclusive.
# Input: an array of length at least 2 interpreted as [count, state, ...]
Line 840 ⟶ 1,462:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ] ;</langsyntaxhighlight>
''''Box-Muller Method''''
<langsyntaxhighlight lang="jq"># Generate a single number following the normal distribution with mean 0, variance 1,
# using the Box-Muller method: X = sqrt(-2 ln U) * cos(2 pi V) where U and V are uniform on [0,1].
# Input: [n, state]
Line 861 ⟶ 1,483:
next_rand_normal
| recurse( if .[0] < count then next_rand_normal else empty end)
| .[2] = (.[2] * sd) + mean;</langsyntaxhighlight>
'''Example'''
The task can be completed using: [0,1] | random_normal_variate(1; 0.5; 1000) | .[2]
 
We show just the sample average and standard deviation:
<langsyntaxhighlight lang="jq">def summary:
length as $l | add as $sum | ($sum/$l) as $a
| reduce .[] as $x (0; . + ( ($x - $a) | .*. ))
| [ $a, (./$l | sqrt)] ;
 
[ [0,1] | random_normal_variate(1; 0.5; 1000) | .[2] ] | summary</langsyntaxhighlight>
{{out}}
$ jq -n -c -f Random_numbers.jq
Line 878 ⟶ 1,500:
=={{header|Julia}}==
Julia's standard library provides a <code>randn</code> function to generate normally distributed random numbers (with mean 0 and standard deviation 0.5, which can be easily rescaled to any desired values):
<langsyntaxhighlight lang="julia">randn(1000) * 0.5 + 1</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
import java.util.Random
 
fun main(args: Array<String>) {
val r = Random()
val da = DoubleArray(1000)
for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian()
// now check actual mean and SD
val mean = da.average()
val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())
println("Mean is $mean")
println("S.D. is $sd")
}</syntaxhighlight>
Sample output:
{{out}}
<pre>
Mean is 1.0071784073168768
S.D. is 0.48567118114896807
</pre>
 
=={{header|LabVIEW}}==
Line 884 ⟶ 1,528:
[[File:LV_array_of_randoms_with_given_mean_and_stdev.png]]
 
=={{header|Liberty BASICLingo}}==
<syntaxhighlight lang="lingo">-- Returns a random float value in range 0..1
<lang lb>dim a(1000)
on randf ()
mean =1
n = random(the maxinteger)-1
sd =0.5
return n / float(the maxinteger-1)
for i = 1 to 1000 ' throw 1000 normal variates
end</syntaxhighlight>
a( i) =mean +sd *( sqr( -2 * log( rnd( 0))) * cos( 2 * pi * rnd( 0)))
 
next i</lang>
<syntaxhighlight lang="lingo">normal = []
repeat with i = 1 to 1000
normal.add(1 + sqrt(-2 * log(randf())) * cos(2 * PI * randf()) / 2)
end repeat</syntaxhighlight>
 
=={{header|Lobster}}==
Uses built-in <code>rnd_gaussian</code>
<syntaxhighlight lang="lobster">
let mean = 1.0
let stdv = 0.5
let count = 1000
 
// stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
 
def stats(xs: [float]) -> float, float: // variance, mean
var M = xs[0]
var S = 0.0
var n = 1.0
for(xs.length - 1) i:
let x = xs[i + 1]
n = n + 1.0
let mm = (x - M)
M += mm / n
S += mm * (x - M)
return (if n > 0.0: S / n else: 0.0), M
def test_random_normal() -> [float]:
rnd_seed(floor(seconds_elapsed() * 1000000))
let r = vector_reserve(typeof return, count)
for (count):
r.push(rnd_gaussian() * stdv + mean)
let cvar, cmean = stats(r)
let cstdv = sqrt(cvar)
print concat_string(["Mean: ", string(cmean), ", Std.Deviation: ", string(cstdv)], "")
 
test_random_normal()
</syntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
The earliest Logos only have a RANDOM function for picking a random non-negative integer. Many modern Logos have floating point random generators built-in.
<langsyntaxhighlight lang="logo">to random.float ; 0..1
localmake "max.int lshift -1 -1
output quotient random :max.int :max.int
Line 904 ⟶ 1,586:
end
 
make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []</langsyntaxhighlight>
 
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">local list = {}
=={{header|lua}}==
<lang lua>
local list = {}
for i = 1, 1000 do
list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
end</syntaxhighlight>
end
 
</lang>
=={{header|M2000 Interpreter}}==
M2000 use a Wichmann - Hill Pseudo Random Number Generator.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Function StdDev (A()) {
\\ A() has a copy of values
N=Len(A())
if N<1 then Error "Empty Array"
M=Each(A())
k=0
\\ make sum, dev same type as A(k)
sum=A(k)-A(k)
dev=sum
\\ find mean
While M {
sum+=Array(M)
}
Mean=sum/N
\\ make a pointet to A()
P=A()
\\ subtruct from each item
P-=Mean
M=Each(P)
While M {
dev+=Array(M)*Array(M)
}
\\ as pointer to arrray
=(if(dev>0->Sqrt(dev/N), 0), Mean)
}
Function randomNormal {
\\ by default all numbers are double
\\ cos() get degrees
=1+Cos(360 * rnd) * Sqrt(-2 * Ln(rnd)) /2
}
\\ fill array calling randomNormal() for each item
Dim A(1000)<<randomNormal()
\\ we can pass a pointer to array and place it to stack of values
DisplayMeanAndStdDeviation(A()) ' mean ~ 1 std deviation ~0.5
\\ check M2000 rnd only
Dim B(1000)<<rnd
DisplayMeanAndStdDeviation(B()) ' mean ~ 0.5 std deviation ~0.28
 
 
DisplayMeanAndStdDeviation((0,0,14,14)) ' mean = 7 std deviation = 7
DisplayMeanAndStdDeviation((0,6,8,14)) ' mean = 7 std deviation = 5
DisplayMeanAndStdDeviation((6,6,8,8)) ' mean = 7 std deviation = 1
Sub DisplayMeanAndStdDeviation(A)
\\ push to stack all items of an array (need an array pointer)
Push ! StdDev(A)
\\ read from strack two numbers
Print "Mean is "; Number
Print "Standard Deviation is "; Number
End Sub
}
Checkit
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">with(Statistics):
Sample(Normal(1, 0.5), 1000);</syntaxhighlight>
 
'''or'''
 
<syntaxhighlight lang="maple">1+0.5*ArrayTools[RandomArray](1000,1,distribution=normal);</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Built-in function RandomReal with built-in distribution NormalDistribution as an argument:
<langsyntaxhighlight Mathematicalang="mathematica">RandomReal[NormalDistribution[1, 1/2], 1000]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
 
Native support :
<langsyntaxhighlight MATLABlang="matlab"> mu = 1; sd = 0.5;
x = randn(1000,1) * sd + mu;
</syntaxhighlight>
</lang>
 
The statistics toolbox provides this function
<langsyntaxhighlight MATLABlang="matlab"> x = normrnd(mu, sd, [1000,1]); </langsyntaxhighlight>
 
This script uses the Box-Mueller Transform to transform a number from the uniform distribution to a normal distribution of mean = mu0 and standard deviation = chi2.
 
<langsyntaxhighlight MATLABlang="matlab">function randNum = randNorm(mu0,chi2, sz)
radiusSquared = +Inf;
Line 945 ⟶ 1,691:
randNum = (v .* scaleFactor .* chi2) + mu0;
 
end</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight MATLABlang="matlab">>> randNorm(1,.5, [1000,1])
 
ans =
 
0.693984121077029</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">load(distrib)$
 
random_normal(1.0, 0.5, 1000);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
 
<langsyntaxhighlight lang="maxscript">arr = #()
for i in 1 to 1000 do
(
Line 968 ⟶ 1,714:
c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees
append arr c
)</langsyntaxhighlight>
 
=={{header|Metafont}}==
Line 974 ⟶ 1,720:
Metafont has <code>normaldeviate</code> which produces pseudorandom normal distributed numbers with mean 0 and variance one. So the following complete the task:
 
<langsyntaxhighlight lang="metafont">numeric col[];
 
m := 0; % m holds the mean, for testing purposes
Line 992 ⟶ 1,738:
 
show m, s; % and let's show that really they get what we wanted
end</langsyntaxhighlight>
 
A run gave
Line 1,001 ⟶ 1,747:
Assigning a value to the special variable '''randomseed''' will allow to have always
the same sequence of pseudorandom numbers
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">randNormal = function(mean=0, stddev=1)
return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function
 
x = []
for i in range(1,1000)
x.push randNormal(1, 0.5)
end for</syntaxhighlight>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">import java.util.Random
 
list = double[999]
Line 1,012 ⟶ 1,768:
list[i] = mean + std * rng.nextGaussian
end
</syntaxhighlight>
</lang>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П7 <-> П8 1/x П6 ИП6 П9 СЧ П6 1/x
ln ИП8 * 2 * КвКор ИП9 2 * пи
* sin * ИП7 + С/П БП 05</langsyntaxhighlight>
 
''Input'': РY - variance, РX - expectation.
Line 1,023 ⟶ 1,779:
Or:
 
<syntaxhighlight lang="text">3 10^x П0 ПП 13 2 / 1 + С/П L0 03 С/П
СЧ lg 2 /-/ * КвКор 2 пи ^ СЧ * * cos * В/О</langsyntaxhighlight>
 
to generate 1000 numbers with a mean of 1.0 and a standard deviation of 0.5.
Line 1,031 ⟶ 1,787:
{{trans|C}}
 
<langsyntaxhighlight lang="modula3">MODULE Rand EXPORTS Main;
 
IMPORT Random;
Line 1,051 ⟶ 1,807:
rands[i] := 1.0D0 + 0.5D0 * RandNorm();
END;
END Rand.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<syntaxhighlight lang="nanoquery">list = {0} * 1000
mean = 1.0; std = 0.5
rng = new(Nanoquery.Util.Random)
 
for i in range(0, len(list) - 1)
list[i] = mean + std * rng.getGaussian()
end</syntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,109 ⟶ 1,875:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,152 ⟶ 1,918:
 
=={{header|NewLISP}}==
<syntaxhighlight lang NewLISP="newlisp">(normal 1 .5 1000)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import mathrandom, stats, strutilsstrformat
 
const precisn = 5
var rs: TRunningStat
 
var rs: RunningStat
proc normGauss: float {.inline.} = 1 + 0.76 * cos(2*PI*random(1.0)) * sqrt(-2*log10(random(1.0)))
 
randomize()
 
for j_ in 01..5:
for i_ in 01..1000: rs.push gauss(1.0, 0.5)
echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}"
rs.push(normGauss())
</syntaxhighlight>
echo("mean: ", $formatFloat(rs.mean,ffDecimal,precisn),
" stdDev: ", $formatFloat(rs.standardDeviation(),ffDecimal,precisn))</lang>
{{out}}
<pre>mean: 1.0170301294 stdDev: 0.5032449692
mean: 1.0118700262 stdDev: 0.5006050028
mean: 10.0021699878 stdDev: 0.4996949662
mean: 10.0033599830 stdDev: 0.5018449820
mean: 1.0012000658 stdDev: 0.4983049703</pre>
mean: 1.00217 stdDev: 0.49911</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class RandomNumbers {
function : Main(args : String[]) ~ Nil {
Line 1,195 ⟶ 1,956:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let pi = 4. *. atan 1.;;
let random_gaussian () =
1. +. sqrt (-2. *. log (Random.float 1.)) *. cos (2. *. pi *. Random.float 1.);;
let a = Array.init 1000 (fun _ -> random_gaussian ());;</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">p = normrnd(1.0, 0.5, 1000, 1);
disp(mean(p));
disp(sqrt(sum((p - mean(p)).^2)/numel(p)));</langsyntaxhighlight>
 
{{out}}
Line 1,215 ⟶ 1,976:
{{trans|REXX}}
===version 1===
<langsyntaxhighlight lang="oorexx">/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/
pi=RxCalcPi() /* get value of pi */
Parse Arg n seed . /* allow specification of N & seed*/
Line 1,256 ⟶ 2,017:
Return RxCalcPower(_/n,.5)
 
:: requires rxmath library</langsyntaxhighlight>
{{out}}
<pre> old mean= 0.49830002
Line 1,265 ⟶ 2,026:
===version 2===
Using the nice function names in the algorithm.
<langsyntaxhighlight lang="oorexx">/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/
pi=RxCalcPi() /* get value of pi */
Parse Arg n seed . /* allow specification of N & seed*/
Line 1,310 ⟶ 2,071:
sin: Return RxCalcSin(arg(1),,'R')
 
:: requires rxmath library</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">rnormal()={
my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296)),u1=random(2^pr)*1.>>pr,u2=random(2^pr)*1.>>pr);
sqrt(-2*log(u1))*cos(2*Pi*u1u2) \\ in previous version "u1" instead of "u2" was used --> has given crap distribution
\\ Could easily be extended with a second normal at very little cost.
};
vector(1000,unused,rnormal()/2+1)</langsyntaxhighlight>
 
=={{header|Pascal}}==
 
The following function calculates Gaussian-distributed random numbers with the Box-Müller algorithm:
<langsyntaxhighlight lang="pascal">
function rnorm (mean, sd: real): real;
{Calculates Gaussian random numbers according to the Box-Müller approach}
Line 1,331 ⟶ 2,092:
u1 := random;
u2 := random;
rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd);
/* error !?! Shouldn't it be "mean +" instead of "mean *" ? */
end;
</syntaxhighlight>
</lang>
 
[[#Delphi | Delphi]] and [[#Free Pascal|Free Pascal]] support implement a '''randg''' function that delivers Gaussian-distributed random numbers.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my $PI = 2 * atan2 1, 0;
 
my @nums = map {
1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand)
} 1..1000;</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{Trans|Euphoria}}
{{works with|Rakudo|#22 "Thousand Oaks"}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">RandomNormal</span><span style="color: #0000FF;">()</span>
<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: #7060A8;">log</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: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">PI</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">rnd</span><span style="color: #0000FF;">())</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</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;">1000</span><span style="color: #0000FF;">)</span>
<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;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</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;">1</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">0.5</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">RandomNormal</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
<lang perl6>sub randnorm ($mean, $stddev) {
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
$mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand)
}
 
def RandomNormal
my @nums = randnorm(1, 0.5) xx 1000;
drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 +
enddef
 
1000 var n
# Checking
0 n repeat
say my $mean = @nums R/ [+] @nums;
say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2;
</lang>
 
getid RandomNormal map
=={{header|Phix}}==
 
{{Trans|Euphoria}}
dup
<lang Phix>function RandomNormal()
sum n / var mean
return sqrt(-2*log(rnd())) * cos(2*PI*rnd())
"Mean: " print mean print nl
end function
 
0 swap n for
sequence s = repeat(0,1000)
get mean - 2 power rot + swap
for i=1 to length(s) do
endfor
s[i] = 1 + 0.5 * RandomNormal()
swap n / sqrt "Standard deviation: " print print</syntaxhighlight>
end for</lang>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">function random() {
return mt_rand() / mt_getrandmax();
}
Line 1,381 ⟶ 2,152:
$a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
_ = random2(), % random seed
G = [gaussian_dist(1,0.5) : _ in 1..1000],
println(first_10=G[1..10]),
println([mean=avg(G),stdev=stdev(G)]),
nl.
 
% Gaussian (Normal) distribution, Box-Muller algorithm
gaussian01() = Y =>
U = frand(0,1),
V = frand(0,1),
Y = sqrt(-2*log(U))*sin(2*math.pi*V).
 
gaussian_dist(Mean,Stdev) = Mean + (gaussian01() * Stdev).
 
% Variance of Xs
variance(Xs) = Variance =>
Mu = avg(Xs),
N = Xs.len,
Variance = sum([ (X-Mu)**2 : X in Xs ]) / N.
 
% Standard deviation
stdev(Xs) = sqrt(variance(Xs)).</syntaxhighlight>
 
{{out}}
<pre>first_10 = [1.639965415776091,0.705425965005482,0.981532402477848,0.309148743347499,1.252800181962738,0.098829881195179,0.74888084504147,0.181494956495445,1.304931340021904,0.595939453660087]
[mean = 0.99223677282248,stdev = 0.510336641737154]</pre>
 
 
=={{header|PicoLisp}}==
{{trans|C}}
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de randomNormal () # Normal distribution, centered on 0, std dev 1
Line 1,400 ⟶ 2,201:
(link (+ 1.0 (/ (randomNormal) 2))) ) )
(for N (head 7 Result) # Print first 7 results
(prin (format N *Scl) " ") ) )</langsyntaxhighlight>
{{out}}
<pre>1.500334 1.212931 1.095283 0.433122 0.459116 1.302446 0.402477</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* CONVERTED FROM WIKI FORTRAN */
Normal_Random: procedure options (main);
Line 1,427 ⟶ 2,228:
put skip edit ( "Standard Deviation = ", sd) (a, F(18,16));
END Normal_Random;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,438 ⟶ 2,239:
 
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
<lang PL/SQL>
DECLARE
--The desired collection
Line 1,454 ⟶ 2,255:
END LOOP;
END;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">;;; Choose radians as arguments to trigonometic functions
true -> popradians;
 
Line 1,471 ⟶ 2,272:
for i from 1 to 1000 do 1.0+0.5*random_normal() endfor;
;;; collect them into array
consvector(1000) -> array;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Equation adapted from Liberty BASIC
<langsyntaxhighlight lang="powershell">function Get-RandomNormal
{
[CmdletBinding()]
Line 1,503 ⟶ 2,304:
$Measure = $RandomNormalNumbers | Measure-Object -Average
$Stats = [PSCustomObject]@{
"Count: " + $Measure.Count
"Average: " + Count = $Measure.AverageCount
Average = $Measure.Average
"Standard deviation: " + ( Get-StandardDeviation -Numbers $RandomNormalNumbers )</lang>
StandardDeviation = Get-StandardDeviation -Numbers $RandomNormalNumbers
}
 
$Stats | Format-List
</syntaxhighlight>
{{out}}
<pre>Count: 1000
Count : 1000
Average: 0.99601224493548
Average : 1.01206560135809
Standard deviation: 0.480629257616293</pre>
StandardDeviation : 0.489099623426272
 
</pre>
=={{header|PureBasic}}==
<lang PureBasic>Procedure.f RandomNormal()
; This procedure can return any real number.
Protected.f x1, x2
 
; random numbers from the open interval ]0, 1[
x1 = (Random(999998)+1) / 1000000 ; must be > 0 because of Log(x1)
x2 = (Random(999998)+1) / 1000000
 
ProcedureReturn Sqr(-2*Log(x1)) * Cos(2*#PI*x2)
EndProcedure
 
 
Define i, n=1000
 
Dim a.q(n-1)
For i = 0 To n-1
a(i) = 1 + 0.5 * RandomNormal()
Next</lang>
 
=={{header|Python}}==
;Using random.gauss:
<langsyntaxhighlight lang="python">>>> import random
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>> </langsyntaxhighlight>
 
;Quick check of distribution:
<langsyntaxhighlight lang="python">>>> def quick_check(numbers):
count = len(numbers)
mean = sum(numbers) / count
Line 1,546 ⟶ 2,334:
>>> quick_check(values)
(1.0140373306786599, 0.49943411329234066)
>>> </langsyntaxhighlight>
 
Note that the ''random'' module in the Python standard library supports a number of statistical distribution methods.
 
;Alternatively using random.normalvariate:
<langsyntaxhighlight lang="python">>>> values = [ random.normalvariate(1, 0.5) for i in range(1000)]
>>> quick_check(values)
(0.990099111944864, 0.5029847005836282)
>>> </langsyntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus"># For reproducibility, set the seed:
<lang r>result <- rnorm(1000, mean=1, sd=0.5)</lang>
set.seed(12345L)
 
result <- rnorm(1000, mean = 1, sd = 0.5)</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(for/list ([i 1000])
(add1 (* (sqrt (* -2 (log (random)))) (cos (* 2 pi (random))) 0.5)))
</syntaxhighlight>
</lang>
 
Alternative:
<syntaxhighlight lang="racket">
#lang racket
(require math/distributions)
(sample (normal-dist 1.0 0.5) 1000)
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#22 "Thousand Oaks"}}
 
<syntaxhighlight lang="raku" line>sub randnorm ($mean, $stddev) {
$mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand)
}
 
my @nums = randnorm(1, 0.5) xx 1000;
 
# Checking
say my $mean = @nums R/ [+] @nums;
say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2;
</syntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">define PI
-1 acos
Line 1,579 ⟶ 2,392:
2 / 1 +
1000 each drop randNormal "%f\n" print</langsyntaxhighlight>
Quick Check (on linux with code in file rand.rv)
<langsyntaxhighlight lang="raven">raven rand.rv | awk '{sum+=$1; sumsq+=$1*$1;} END {print "stdev = " sqrt(sumsq/NR - (sum/NR)**2); print "mean = " sum/NR}'
stdev = 0.497773
mean = 1.01497</langsyntaxhighlight>
 
=={{header|ReScript}}==
{{trans|OCaml}}
<syntaxhighlight lang="rescript">let pi = 4.0 *. atan(1.0)
 
let random_gaussian = () => {
1.0 +.
sqrt(-2.0 *. log(Random.float(1.0))) *.
cos(2.0 *. pi *. Random.float(1.0))
}
 
let a = Belt.Array.makeBy(1000, (_) => random_gaussian ())
 
for i in 0 to 10 {
Js.log(a[i])
}</syntaxhighlight>
 
=={{header|REXX}}==
The REXX language doesn't have any "higher math" functions like SQRT/SIN/COS/LN/LOG/EXP/POW/etc.,
<br>so we ''hoi polloi'' REXX programmers have to roll our own.
 
Programming note: &nbsp; note the range of the random numbers: &nbsp; (0,1]
<br>(that is, random numbers from &nbsp; zero──►unity, &nbsp; excluding zero, including unity).
<langsyntaxhighlight lang="rexx">/*REXX pgm gensgenerates 1,000 normally distributed #snumbers: mean=1, standard deviation.=½.*/
numeric digits 20 /*the default decimal digit precision=9*/
parse arg n seed . /*allow specification of N and the seed*/
if n=='' | n=='",'" then n=1000 /*N: is the size of the array. */
if datatype(seed\==,'W') then call random ,,seed /*SEED: for repeatable random numbers. */
newMean=1 /*the desired new mean| (arithmetic avg. )*/
sd=1/2 /*the desired new standard deviation. */
do g=1 for n /*generate N uniform random #'s (0,1].*/
#.g = random(1, 1e5) / 1e5 /*REXX's RANDOM BIF generates integers.*/
end /*g*/ /* [↑] randrandom integers ──► fractions. */
say ' old mean=' mean()
say 'old standard deviation=' stdDev()
call pi; pi2=pi+pi * 2 /*define pi and also 2 * pi. */
say
do j=1 to n-1 by 2; m=j+1 /*step through the iterations by two. */
_=sd * sqrt(ln(#.j) * -2) /*calculate the used-twice expression.*/
#.j=_ * cos(pi2 * #.m) + newMean /*utilize the Box─Muller method. */
#.m=_ * sin(pi2 * #.m) + newMean /*random number must be: (0,1] */
end /*j*/
say ' new mean=' mean()
say 'new standard deviation=' stdDev()
exit /*stick a fork in it, we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────subroutines──────────────────────────────────────────────────────────────────────*/
mean: _=0; do k=1 for n; _=_ + #.k; end; end; return _/n
stdDev: _avg=mean(); _=0; do k=1 for n; _=_ + (#.k - _avg)**2; end; return sqrt(_/n)
e: e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e /*digs overkill*/
pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi /* " " */
r2r: return arg(1) // (2*pi()) * 2) /*normalize ang*/
sin: procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1)
.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; return .ln_comp()
ln: procedure; parse arg x,f; call e; ig= x>1.5; is=1 - 2 * (ig\==1); ii=0; xx=x
.ln_comp: do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end
do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end
xx=izz;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
if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5
if a=pi() * 2/3 then return -.5; return .sinCos(1,1,-1)
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
 
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=numeric digits; m.h=9d+6
numeric digits 9; numeric form; h=d+6;parse value if format(x<,2,1,,0) 'E0' then with do g 'E' _ .; x g=-x;g i=* .5'ie';_ end%2
parse value format(x,2,1,,m.=9; do j=0) 'E0' while withh>9; g 'E' _ m.j=h; g h=g*.5'e'_h%2 + 1; end /*j*/
do j=0 while h>9; do m.k=j=h;+5 to 0 by -1; numeric digits m.k; hg=h%2(g+1x/g)*.5; end /*jk*/
do k=j+5 to 0 by -1; numeric digits m.kd; g=(g+x/g)*.5; end return g/*k*1</syntaxhighlight>
numeric digits d; return (g/1)i /*make complex if X < 0.*/</lang>
'''output''' &nbsp; when using the default inputs:
<pre>
Line 1,646 ⟶ 2,475:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for i = 1 to 10
see random(i) + nl
next i
</syntaxhighlight>
</lang>
=={{header|Ruby}}==
<lang ruby>Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }</lang>
 
=={{header|Run BASICRPL}}==
≪ RAND LN NEG 2 * √
<lang runbasic>dim a(1000)
RAND 2 * π * COS *
pi = 22/7
→NUM 2 / 1 +
for i = 1 to 1000
≫ '<span style="color:blue>RANDN</span>' STO
a( i) = 1 + .5 * (sqr(-2 * log(rnd(0))) * cos(2 * pi * rnd(0)))
next i</lang>
≪ CL∑
1 1000 '''START''' <span style="color:blue>RANDN</span> ∑+ '''NEXT'''
MEAN PSDEV
≫ '<span style="color:blue>TASK</span>' STO
{{out}}
<pre>
1: .990779804949
2: .487204045227
</pre>
The collection is stored in a predefined array named <code>∑DAT</code>, which is automatically created/updated when using the <code>∑+</code> instruction and remains available until the user decides to purge it, typically by calling the <code>CL∑</code> command.
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }</syntaxhighlight>
 
=={{header|Rust}}==
{{libheader|rand}}
'''Using a for-loop:'''
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::distributions::{Normal, IndependentSample};
 
Line 1,673 ⟶ 2,514:
*num = normal.ind_sample(&mut rng);
}
}</langsyntaxhighlight>
 
'''Using iterators:'''
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::distributions::{Normal, IndependentSample};
 
Line 1,685 ⟶ 2,526:
(0..1000).map(|_| normal.ind_sample(&mut rng)).collect()
};
}</langsyntaxhighlight>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
/* Generate 1000 random numbers with mean 1 and standard deviation 0.5.
SAS version 9.2 was used to create this code.*/
Line 1,701 ⟶ 2,542:
end;
run;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 1,715 ⟶ 2,556:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:ARRAY{FLTD} := #(1000);
Line 1,733 ⟶ 2,574:
#OUT + "dev " + dev + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
===One liner===
<lang scala>List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)</lang>
<syntaxhighlight lang="scala">List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)</syntaxhighlight>
===Academic===
<syntaxhighlight lang="scala">
object RandomNumbers extends App {
 
val distribution: LazyList[Double] = {
def randomNormal: Double = 1.0 + 0.5 * scala.util.Random.nextGaussian
 
def normalDistribution(a: Double): LazyList[Double] = a #:: normalDistribution(randomNormal)
 
normalDistribution(randomNormal)
}
 
/*
* Let's test it
*/
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
val mean: T =
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
 
// Root of mean diffs
val stdDev = Math.sqrt(ts.map { x =>
val diff = num.toDouble(num.minus(x, mean))
diff * diff
}.sum / ts.size)
 
(mean, stdDev)
}
 
println(calcAvgAndStddev(distribution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893)
}
</syntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; linear congruential generator given in C99 section 7.20.2.1
(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))
 
Line 1,785 ⟶ 2,658:
 
(mean-sdev v)
; (0.9562156817697293 0.5097087109575911)</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
Line 1,812 ⟶ 2,685:
rands[i] := 1.0 + 0.5 * randomNormal;
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = 1000.of { 1 + (0.5 * Math.sqrt(-2 * Math1.rand.log(Math.rand)) * Math.cos(2Num.tau * Math::PI * Math1.rand)) };</lang>
arr.each { .say }</syntaxhighlight>
or:
<lang ruby>1000.of { 1 + (0.5 * (-2 * 1.rand.log -> sqrt) * (2 * Math::PI * 1.rand -> cos)) };</lang>
 
=={{header|Standard ML}}==
Line 1,827 ⟶ 2,699:
You can call the generator with <code>()</code> repeatedly to get a word in the range <code>[Rand.randMin, Rand.randMax]</code>.
You can use the <code>Rand.norm</code> function to transform the output into a <code>real</code> from 0 to 1, or use the <code>Rand.range (i,j)</code> function to transform the output into an <code>int</code> of the given range.
<langsyntaxhighlight lang="sml">val seed = 0w42;
val gen = Rand.mkRandom seed;
fun random_gaussian () =
1.0 + Math.sqrt (~2.0 * Math.ln (Rand.norm (gen ()))) * Math.cos (2.0 * Math.pi * Rand.norm (gen ()));
val a = List.tabulate (1000, fn _ => random_gaussian ());</langsyntaxhighlight>
 
2) Random (a subtract-with-borrow generator). You create the generator by calling <code>Random.rand</code> with a seed (of a pair of <code>int</code>s). You can use the <code>Random.randInt</code> function to generate a random int over its whole range; <code>Random.randNat</code> to generate a non-negative random int; <code>Random.randReal</code> to generate a <code>real</code> between 0 and 1; or <code>Random.randRange (i,j)</code> to generate an <code>int</code> in the given range.
<langsyntaxhighlight lang="sml">val seed = (47,42);
val gen = Random.rand seed;
fun random_gaussian () =
1.0 + Math.sqrt (~2.0 * Math.ln (Random.randReal gen)) * Math.cos (2.0 * Math.pi * Random.randReal gen);
val a = List.tabulate (1000, fn _ => random_gaussian ());</langsyntaxhighlight>
 
Other implementations of Standard ML have their own random number generators. For example, Moscow ML has a <code>Random</code> structure that is different from the one from SML/NJ.
{{works with|Poly/ML}}
The SML Basis Library does not provide a routine for uniform deviate generation, and PolyML does not have one. Using a routine from "Monte Carlo" by Fishman (Springer), in the function uniformdeviate, and avoiding the slow IntInf's:
<syntaxhighlight lang="sml">
val urandomlist = fn seed => fn n =>
let
val uniformdeviate = fn seed =>
let
val in31m = (Real.fromInt o Int32.toInt ) (getOpt (Int32.maxInt,0) );
val in31 = in31m +1.0;
val s1 = 41160.0;
val s2 = 950665216.0;
val v = Real.realFloor seed;
val val1 = v*s1;
val val2 = v*s2;
val next1 = Real.fromLargeInt (Real.toLargeInt IEEEReal.TO_NEGINF (val1/in31)) ;
val next2 = Real.rem(Real.realFloor(val2/in31) , in31m );
val valt = val1+val2 - (next1+next2)*in31m;
val nextt = Real.realFloor(valt/in31m);
val valt = valt - nextt*in31m;
in
(valt/in31m,valt)
end;
val store = ref (0.0,0.0);
val rec u = fn S => fn 0 => [] | n=> (store:=uniformdeviate S; (#1 (!store)):: (u (#2 (!store)) (n-1))) ;
in
u seed n
end;
 
local
open Math
in
val bmconv = fn urand => fn vrand => 1.0+0.5*(sqrt(~2.0*ln urand)*cos (2.0*pi*vrand) )
end;
 
val rec makeNormals = fn once => fn u::v::[] => [once u v] |
u::v::rm => (once u v )::(makeNormals once rm );
 
val anyrealseed=1009.0 ;
makeNormals bmconv (urandomlist anyrealseed 2000);
</syntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">clear all
set obs 1000
gen x=rnormal(1,0.5)</syntaxhighlight>
 
=== Mata ===
<syntaxhighlight lang="stata">a = rnormal(1000,1,1,0.5)</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
Line 1,853 ⟶ 2,773:
for {set i 0} {$i < 1000} {incr i} {
lappend result [expr {$mean + $stddev*nrand()}]
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Builtin function: randNorm()
randNorm(1,.5)
 
Or by a program:
 
Calculator symbol translations:
 
"STO" arrow: &#8594;
 
Square root sign: &#8730;
 
ClrList L<sub>1</sub>
Radian
For(A,1,1000)
√(-2*ln(rand))*cos(2*π*A)→L<sub>1</sub>(A)
End
 
=={{header|TorqueScript}}==
<langsyntaxhighlight lang="tqs">for (%i = 0; %i < 1000; %i++)
%list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom());</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 1,887 ⟶ 2,789:
a standard normal distribution. Mean and standard deviation
library functions are also used in this example.
<langsyntaxhighlight Ursalalang="ursala">#import nat
#import flo
 
Line 1,900 ⟶ 2,802:
^(mean,stdev)* <
pop_stats(1.,0.5) 1000,
sample_stats(1.,0.5) 1000></langsyntaxhighlight>
The output shows the mean and standard deviation for both sample vectors,
the latter being exact by construction.
Line 1,908 ⟶ 2,810:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL i As Integer, m As Double, n As Integer, sd As Double
py = PI()
Line 1,935 ⟶ 2,837:
RETURN z
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Vlang">
import crypto.rand
 
fn main() {
mut nums := []u64{}
for _ in 0..1000 {
nums << rand.int_u64(10000) or {0} // returns random unsigned 64-bit integer from real OS source of entropy
}
println(nums)
}
</syntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "random" for Random
 
var rand = Random.new()
 
var randNormal = Fn.new { (-2 * rand.float().log).sqrt * (2 * Num.pi * rand.float()).cos }
 
var stdDev = Fn.new { |a, m|
var c = a.count
return ((a.reduce(0) { |acc, x| acc + x*x } - m*m*c) / c).sqrt
}
 
var n = 1000
var numbers = List.filled(n, 0)
var mu = 1
var sigma = 0.5
var sum = 0
for (i in 0...n) {
numbers[i] = mu + sigma*randNormal.call()
sum = sum + numbers[i]
}
var mean = sum / n
System.print("Actual mean : %(mean)")
System.print("Actual std dev: %(stdDev.call(numbers, mean))")</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Actual mean : 1.0053988699746
Actual std dev: 0.4961645117026
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
<syntaxhighlight lang "XPL0">define PI = 3.14159265358979323846;
 
func real DRand; \Uniform distribution, [0..1]
return float(Ran(1_000_000)) / 1e6;
 
func real RandomNormal; \Normal distribution, centered on 0, std dev 1
return sqrt(-2.*Log(DRand)) * Cos(2.*PI*DRand);
 
int I;
real Rands(1000);
for I:= 0 to 1000-1 do
Rands(I):= 1.0 + 0.5*RandomNormal</syntaxhighlight>
 
=={{header|Yorick}}==
Returns array of ''count'' random numbers with mean 0 and standard deviation 1.
<langsyntaxhighlight lang="yorick">func random_normal(count) {
return sqrt(-2*log(random(count))) * cos(2*pi*random(count));
}</langsyntaxhighlight>
 
Example of basic use:
Line 1,958 ⟶ 2,920:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn mkRand(mean,sd){ //normally distributed random w/mean & standard deviation
pi:=(0.0).pi; // using the Box–Muller transform
rz1:=fcn{1.0-(0.0).random(1)} // from [0,1) to (0,1]
return('wrap(){((-2.0*rz1().log()).sqrt() * (2.0*pi*rz1()).cos())*sd + mean })
}</langsyntaxhighlight>
This creates a new random number generator, now to use it:
<langsyntaxhighlight lang="zkl">var g=mkRand(1,0.5);
ns:=(0).pump(1000,List,g); // 1000 rands with mean==1 & sd==1/2
mean:=(ns.sum(0.0)/1000); //-->1.00379
// calc sd of list of numbers:
(ns.reduce('wrap(p,n){p+(n-mean).pow(2)},0.0)/1000).sqrt() //-->0.494844</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
 
Here we have converted the QBasic code to suit the ZX Spectrum:
 
<lang zxbasic>10 RANDOMIZE 0 : REM seeds random number generator based on uptime
20 DIM a(1000)
30 CLS
40 FOR i = 1 TO 1000
50 LET a(i) = 1 + SQR(-2 * LN(RND)) * COS(2 * PI * RND)
60 NEXT i</lang>
512

edits