Random numbers: Difference between revisions

→‎{{header|BASIC}}: Added ANSI BASIC.
(Updated to work with Nim 1.4: added "import random", used function "gauss", renamed TRunningStat as RunningStat, etc.)
(→‎{{header|BASIC}}: Added ANSI BASIC.)
 
(46 intermediate revisions by 23 users not shown)
Line 8:
Generate a collection filled with   '''1000'''   normally distributed random (or pseudo-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:
Line 18 ⟶ 16:
 
=={{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 40 ⟶ 38:
Distribution (I) := Normal_Distribution (Seed);
end loop;
end Normal_Random;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 49 ⟶ 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 61 ⟶ 59:
INT limit=10;
printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit]))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 69 ⟶ 67:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">rnd: function []-> (random 0 10000)//10000
 
rands: map 1..1000 'x [
Line 75 ⟶ 73:
]
 
print rands</langsyntaxhighlight>
 
{{out}}
Line 84 ⟶ 82:
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 98 ⟶ 96:
}
Return Y
}</langsyntaxhighlight>
 
=={{header|Avail}}==
<langsyntaxhighlight Availlang="avail">Method "U(_,_)" is
[
lower : number,
Line 133 ⟶ 131:
// 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;</langsyntaxhighlight>
 
=={{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 153 ⟶ 151:
print s
}
</syntaxhighlight>
</lang>
{{out}} first few values only
<pre>
Line 160 ⟶ 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 180 ⟶ 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 207 ⟶ 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 247 ⟶ 561:
Console.ReadLine();
}
</syntaxhighlight>
</lang>
 
An example result:
Line 260 ⟶ 574:
The new C++ standard looks very similar to the Boost library example below.
 
<langsyntaxhighlight lang="cpp">#include <random>
#include <functional>
#include <vector>
Line 276 ⟶ 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 305 ⟶ 619:
std::generate_n(array, 1000, normal_distribution(1.0, 0.5));
return 0;
}</langsyntaxhighlight>
 
{{libheader|Boost}}
Line 311 ⟶ 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 332 ⟶ 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}}
<langsyntaxhighlight 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}"</langsyntaxhighlight>
{{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 379 ⟶ 765:
//x = nRnd;
x = nRnd();
}</langsyntaxhighlight>
 
===Alternative Version===
Line 385 ⟶ 771:
{{libheader|tango}}
 
<langsyntaxhighlight lang="d">import tango.math.random.Random;
 
void main() {
Line 394 ⟶ 780:
l = 1.0 + 0.5 * l;
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 400 ⟶ 786:
Delphi has RandG function which generates random numbers with normal distribution using Marsaglia-Bray algorithm:
 
<langsyntaxhighlight Delphilang="delphi">program Randoms;
 
{$APPTYPE CONSOLE}
Line 418 ⟶ 804:
Writeln('Std Deviation = ', StdDev(Values):6:4);
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Mean = 1.0098
Line 424 ⟶ 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">
<lang>for i range 1000
numfmt 5 0
a[] &= 1 + 0.5 * sqrt (-2 * logn randomf) * cos (360 * randomf)
e = 2.7182818284590452354
for i = 1 to 1000
a[] &= 1 + 0.5 * sqrt (-2 * log10 randomf / log10 e) * cos (360 * randomf)
.
printfor v in a[]</lang>
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 537 ⟶ 936:
end
end
</syntaxhighlight>
</lang>
 
Example Result
Line 547 ⟶ 946:
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.1x :
<langsyntaxhighlight lang="elena">import extensions;
import extensions'math;
Line 562 ⟶ 961:
real tAvg := 0;
for (int x := 0,; x < a.Length,; x += 1)
{
a[x] := (randomNormal()) / 2 + 1;
Line 572 ⟶ 971:
real s := 0;
for (int x := 0,; x < a.Length,; x += 1)
{
s += power(a[x] - tAvg, 2)
Line 582 ⟶ 981:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 590 ⟶ 989:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Random do
def normal(mean, sd) do
{a, b} = {:rand.uniform, :rand.uniform}
Line 605 ⟶ 1,004:
 
xs = for _ <- 1..1000, do: Random.normal(1.0, 0.5)
std_dev.(xs)</langsyntaxhighlight>
{{out}}
<pre>
Line 612 ⟶ 1,011:
 
used Erlang function <code>:rand.normal</code>
<langsyntaxhighlight lang="elixir">xs = for _ <- 1..1000, do: 1.0 + :rand.normal * 0.5
std_dev.(xs)</langsyntaxhighlight>
{{out}}
<pre>
Line 622 ⟶ 1,021:
{{works with|Erlang}}
 
<langsyntaxhighlight lang="erlang">
mean(Values) ->
mean(tl(Values), hd(Values), 1).
Line 654 ⟶ 1,053:
io:format("mean = ~w\n", [mean(X)]),
io:format("stddev = ~w\n", [stddev(X)]).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 662 ⟶ 1,061:
 
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM DISTRIBUTION
 
Line 698 ⟶ 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 725 ⟶ 1,124:
for i = 1 to n do
s[i] = 1 + 0.5 * RandomNormal()
end for</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let n = MathNet.Numerics.Distributions.Normal(1.0,0.5)
List.init 1000 (fun _->n.Sample())
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 755 ⟶ 1,154:
0.6224640457; 0.8524078517; 0.7646595627; 0.6799834691; 0.773111053; ...]
</pre> =={{header|F_Sharp|F#}}==
<langsyntaxhighlight 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() ]</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: random ;
1000 [ 1.0 0.5 normal-random-float ] replicate</langsyntaxhighlight>
 
=={{header|Falcon|}}==
<langsyntaxhighlight lang="falcon">a = []
for i in [0:1000] : a+= norm_rand_num()
 
Line 773 ⟶ 1,172:
pi = 2*acos(0)
return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2
end</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 779 ⟶ 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 797 ⟶ 1,196:
}
}
</syntaxhighlight>
</lang>
 
The second calls out to Java's Gaussian random-number generator:
 
<langsyntaxhighlight lang="fantom">
using [java] java.util::Random
 
Line 822 ⟶ 1,221:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
 
<langsyntaxhighlight lang="forth">require random.fs
here to seed
 
Line 842 ⟶ 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</langsyntaxhighlight> 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 873 ⟶ 1,272:
WRITE(*, "(A,F8.6)") "Standard Deviation = ", sd
 
END PROGRAM Random</langsyntaxhighlight>
 
{{out}}
Line 884 ⟶ 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|FreeBASIC}}==
<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</lang>
Sample result:
{{out}}
<pre>
Mean is 1.000763573902885
Standard Deviation is 0.500653063426955
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">a = new array[[1000], {|x| randomGaussian[1, 0.5]}]</syntaxhighlight>
<lang frink>
a = new array
for i = 1 to 1000
a.push[randomGaussian[1, 0.5]]
</lang>
 
=={{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.
<lang futurebasic>
include "ConsoleWindow"
 
local fn RandomZeroToOne as double
dim as double result
BeginCCode
result = (double)( (rand() % 100000 ) * 0.00001 );
EndC
end fn = result
 
local fn RandomGaussian as double
dim as double r
 
r = fn RandomZeroToOne
end fn = 1 + .5 * ( sqr( -2 * log(r) ) * cos( 2 * pi * r ) )
 
dim as long i
dim as 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
</lang>
Output:
<pre>
Average: 1.0258434498
Standard Deviation: 0.2771047023
</pre>
 
=={{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,027 ⟶ 1,337:
fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,047 ⟶ 1,357:
 
=={{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 1,065 ⟶ 1,375:
 
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g</langsyntaxhighlight>
 
Or using Data.Random from random-fu package:
<langsyntaxhighlight lang="haskell">replicateM 1000 $ normal 1 0.5</langsyntaxhighlight>
To print them:
<langsyntaxhighlight lang="haskell">import Data.Random
import Control.Monad
 
Line 1,078 ⟶ 1,388:
main = do
x <- sample thousandRandomNumbers
print x</langsyntaxhighlight>
 
=={{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 1,090 ⟶ 1,400:
 
Note that Unicon randomly seeds it's generator.
<langsyntaxhighlight lang="icon">
procedure main()
local L
Line 1,098 ⟶ 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 1,132 ⟶ 1,442:
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,145 ⟶ 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 1,152 ⟶ 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 1,173 ⟶ 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 1,190 ⟶ 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}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.util.Random
Line 1,206 ⟶ 1,516:
println("Mean is $mean")
println("S.D. is $sd")
}</langsyntaxhighlight>
Sample output:
{{out}}
Line 1,217 ⟶ 1,527:
{{works with|LabVIEW|8.6}}
[[File:LV_array_of_randoms_with_given_mean_and_stdev.png]]
 
=={{header|Liberty BASIC}}==
<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</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight Lingolang="lingo">-- Returns a random float value in range 0..1
on randf ()
n = random(the maxinteger)-1
return n / float(the maxinteger-1)
end</langsyntaxhighlight>
 
<langsyntaxhighlight Lingolang="lingo">normal = []
repeat with i = 1 to 1000
normal.add(1 + sqrt(-2 * log(randf())) * cos(2 * PI * randf()) / 2)
end repeat</langsyntaxhighlight>
 
=={{header|Lobster}}==
Uses built-in <code>rnd_gaussian</code>
<syntaxhighlight lang="lobster">
<lang Lobster>
let mean = 1.0
let stdv = 0.5
Line 1,270 ⟶ 1,572:
 
test_random_normal()
</syntaxhighlight>
</lang>
 
=={{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 1,284 ⟶ 1,586:
end
 
make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
M2000 use a Wichmann - Hill Pseudo Random Number Generator.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Function StdDev (A()) {
Line 1,349 ⟶ 1,651:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">with(Statistics):
Sample(Normal(1, 0.5), 1000);</langsyntaxhighlight>
 
'''or'''
 
<langsyntaxhighlight lang="maple">1+0.5*ArrayTools[RandomArray](1000,1,distribution=normal);</langsyntaxhighlight>
 
=={{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 1,389 ⟶ 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 1,412 ⟶ 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 1,418 ⟶ 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 1,436 ⟶ 1,738:
 
show m, s; % and let's show that really they get what we wanted
end</langsyntaxhighlight>
 
A run gave
Line 1,447 ⟶ 1,749:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">randNormal = function(mean=0, stddev=1)
return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function
Line 1,454 ⟶ 1,756:
for i in range(1,1000)
x.push randNormal(1, 0.5)
end for</langsyntaxhighlight>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">import java.util.Random
 
list = double[999]
Line 1,466 ⟶ 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,477 ⟶ 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,485 ⟶ 1,787:
{{trans|C}}
 
<langsyntaxhighlight lang="modula3">MODULE Rand EXPORTS Main;
 
IMPORT Random;
Line 1,505 ⟶ 1,807:
rands[i] := 1.0D0 + 0.5D0 * RandNorm();
END;
END Rand.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">list = {0} * 1000
mean = 1.0; std = 0.5
rng = new(Nanoquery.Util.Random)
Line 1,515 ⟶ 1,817:
for i in range(0, len(list) - 1)
list[i] = mean + std * rng.getGaussian()
end</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,573 ⟶ 1,875:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,616 ⟶ 1,918:
 
=={{header|NewLISP}}==
<syntaxhighlight lang NewLISP="newlisp">(normal 1 .5 1000)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import random, stats, strformat
 
var rs: RunningStat
Line 1,626 ⟶ 1,928:
 
for _ in 1..5:
for _ in 1..1000: rs.push( gauss(1.0, 0.5))
echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation():5.5f}"
</syntaxhighlight>
</lang>
{{out}}
<pre>mean: 01.9737601294 stdDev: 0.49396649692
mean: 01.9852500262 stdDev: 0.49672350028
mean: 0.9909599878 stdDev: 0.49928349662
mean: 10.0003399830 stdDev: 0.50616849820
mean: 1.0052000658 stdDev: 0.50443849703</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class RandomNumbers {
function : Main(args : String[]) ~ Nil {
Line 1,654 ⟶ 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,674 ⟶ 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,715 ⟶ 2,017:
Return RxCalcPower(_/n,.5)
 
:: requires rxmath library</langsyntaxhighlight>
{{out}}
<pre> old mean= 0.49830002
Line 1,724 ⟶ 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,769 ⟶ 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,790 ⟶ 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|Phix}}==
{{Trans|Euphoria}}
<!--<syntaxhighlight lang="phix">-->
<lang Phix>function RandomNormal()
<span style="color: #008080;">function</span> <span style="color: #000000;">RandomNormal</span><span style="color: #0000FF;">()</span>
return sqrt(-2*log(rnd())) * cos(2*PI*rnd())
<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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence s = repeat(0,1000)
<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>
for i=1 to length(s) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
s[i] = 1 + 0.5 * RandomNormal()
<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>
end for</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def RandomNormal
Line 1,833 ⟶ 2,138:
get mean - 2 power rot + swap
endfor
swap n / sqrt "Standard deviation: " print print</langsyntaxhighlight>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">function random() {
return mt_rand() / mt_getrandmax();
}
Line 1,847 ⟶ 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,866 ⟶ 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,893 ⟶ 2,228:
put skip edit ( "Standard Deviation = ", sd) (a, F(18,16));
END Normal_Random;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,904 ⟶ 2,239:
 
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
<lang PL/SQL>
DECLARE
--The desired collection
Line 1,920 ⟶ 2,255:
END LOOP;
END;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">;;; Choose radians as arguments to trigonometic functions
true -> popradians;
 
Line 1,937 ⟶ 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,976 ⟶ 2,311:
 
$Stats | Format-List
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,983 ⟶ 2,318:
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 2,019 ⟶ 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>
#lang racket
(require math/distributions)
(sample (normal-dist 1.0 0.5) 1000)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,050 ⟶ 2,368:
{{works with|Rakudo|#22 "Thousand Oaks"}}
 
<syntaxhighlight lang="raku" perl6line>sub randnorm ($mean, $stddev) {
$mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand)
}
Line 2,059 ⟶ 2,377:
say my $mean = @nums R/ [+] @nums;
say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2;
</syntaxhighlight>
</lang>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">define PI
-1 acos
Line 2,074 ⟶ 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}}==
Line 2,086 ⟶ 2,420:
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 generates 1,000 normally distributed numbers: mean=1, standard deviation=½.*/
numeric digits 20 /*the default decimal digit precision=9*/
parse arg n seed . /*allow specification of N and the seed*/
Line 2,130 ⟶ 2,464:
m.=9; 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>
'''output''' &nbsp; when using the default inputs:
<pre>
Line 2,141 ⟶ 2,475:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
for i = 1 to 10
see random(i) + nl
next i
</syntaxhighlight>
</lang>
 
=={{header|RubyRPL}}==
≪ RAND LN NEG 2 * √
<lang ruby>Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }</lang>
RAND 2 * π * COS *
→NUM 2 / 1 +
≫ '<span style="color:blue>RANDN</span>' STO
≪ 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|Run BASICRuby}}==
<syntaxhighlight lang="ruby">Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }</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</lang>
 
=={{header|Rust}}==
{{libheader|rand}}
'''Using a for-loop:'''
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::distributions::{Normal, IndependentSample};
 
Line 2,170 ⟶ 2,514:
*num = normal.ind_sample(&mut rng);
}
}</langsyntaxhighlight>
 
'''Using iterators:'''
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::distributions::{Normal, IndependentSample};
 
Line 2,182 ⟶ 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 2,198 ⟶ 2,542:
end;
run;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 2,212 ⟶ 2,556:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:ARRAY{FLTD} := #(1000);
Line 2,230 ⟶ 2,574:
#OUT + "dev " + dev + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
===One liner===
<langsyntaxhighlight lang="scala">List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)</langsyntaxhighlight>
===Academic===
<langsyntaxhighlight lang="scala">
object RandomNumbers extends App {
 
Line 2,265 ⟶ 2,609:
println(calcAvgAndStddev(distribution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893)
}
</syntaxhighlight>
</lang>
 
=={{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 2,314 ⟶ 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 2,341 ⟶ 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 * sqrt(-2 * 1.rand.log) * cos(Num.tau * 1.rand)) }
arr.each { .say }</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 2,355 ⟶ 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|PolyMLPoly/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">
<lang smlh>
val urandomlist = fn seed => fn n =>
let
Line 2,408 ⟶ 2,752:
val anyrealseed=1009.0 ;
makeNormals bmconv (urandomlist anyrealseed 2000);
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">clear all
set obs 1000
gen x=rnormal(1,0.5)</langsyntaxhighlight>
 
=== Mata ===
<langsyntaxhighlight lang="stata">a = rnormal(1000,1,1,0.5)</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
Line 2,429 ⟶ 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 2,463 ⟶ 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 2,476 ⟶ 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 2,484 ⟶ 2,810:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL i As Integer, m As Double, n As Integer, sd As Double
py = PI()
Line 2,511 ⟶ 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}}==
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
 
var rand = Random.new()
Line 2,536 ⟶ 2,875:
var mean = sum / n
System.print("Actual mean : %(mean)")
System.print("Actual std dev: %(stdDev.call(numbers, mean))")</langsyntaxhighlight>
 
{{out}}
Line 2,544 ⟶ 2,883:
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 2,566 ⟶ 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>
511

edits