Random numbers: Difference between revisions
Added Uiua solution
No edit summary |
(Added Uiua solution) |
||
(63 intermediate revisions by 31 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}}==
<
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;</
=={{header|ALGOL 68}}==
{{trans|C}}
Line 48 ⟶ 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}}
<
(
sqrt(-2*log(random)) * cos(2*pi*random)
Line 60 ⟶ 59:
INT limit=10;
printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit]))
)</
{{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]
<
R .= RandN(1,0.5) "`n" ; mean = 1.0, standard deviation = 0.5
MsgBox %R%
Line 83 ⟶ 96:
}
Return Y
}</syntaxhighlight>
=={{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:'''
<
'''Readable version:'''
<
function r() {
return sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() )
Line 103 ⟶ 151:
print s
}
</syntaxhighlight>
{{out}} first few values only
<pre>
Line 110 ⟶ 158:
=={{header|BASIC}}==
==={{header|ANSI BASIC}}===
{{trans|FreeBASIC}}
{{works with|Decimal BASIC}}
<syntaxhighlight lang="basic">
100 REM Random numbers
110 RANDOMIZE
120 DEF
130 DIM R(0 TO 999)
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|
The [[Random_numbers#Commodore_BASIC|Commodore BASIC]] code works in Applesoft BASIC.
==={{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 130 ⟶ 238:
PRINT "Mean = " ; mean
PRINT "Standard deviation = " ; stdev</
{{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: →
Square root sign: √
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}}==
<
#include <math.h>
#ifndef M_PI
Line 157 ⟶ 521:
rands[i] = 1.0 + 0.5*random_normal();
return 0;
}</
=={{header|C sharp}}==
{{trans|JavaScript}}
<
private static double randomNormal()
{
return Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble()));
}
</syntaxhighlight>
Then the methods in [[Random numbers#Metafont]] are used to calculate the average and the Standard Deviation:
<
static Random tRand = new Random();
Line 197 ⟶ 561:
Console.ReadLine();
}
</syntaxhighlight>
An example result:
Line 210 ⟶ 574:
The new C++ standard looks very similar to the Boost library example below.
<
#include <functional>
#include <vector>
Line 226 ⟶ 590:
generate(v.begin(), v.end(), rnd);
return 0;
}</
{{works with|C++03}}
<
#include <cmath> // for atan, sqrt, log, cos
#include <algorithm> // for generate_n
Line 255 ⟶ 619:
std::generate_n(array, 1000, normal_distribution(1.0, 0.5));
return 0;
}</
{{libheader|Boost}}
Line 261 ⟶ 625:
This example used Mersenne Twister generator. It can be changed by changing the typedef.
<
#include <vector>
#include "boost/random.hpp"
Line 282 ⟶ 646:
return 0;
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(def normals
(let [r (Random.)]
(take 1000 (repeatedly #(-> r .nextGaussian (* 0.5) (+ 1.0))))))</
=={{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}}==
<
collect (1+ (* (sqrt (* -2 (log (random 1.0)))) (cos (* 2 pi (random 1.0))) 0.5)))</
=={{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}}==
<
struct NormalRandom {
Line 318 ⟶ 765:
//x = nRnd;
x = nRnd();
}</
===Alternative Version===
Line 324 ⟶ 771:
{{libheader|tango}}
<
void main() {
Line 333 ⟶ 780:
l = 1.0 + 0.5 * l;
}
}</
=={{header|Delphi}}==
Line 339 ⟶ 786:
Delphi has RandG function which generates random numbers with normal distribution using Marsaglia-Bray algorithm:
<
{$APPTYPE CONSOLE}
Line 357 ⟶ 804:
Writeln('Std Deviation = ', StdDev(Values):6:4);
Readln;
end.</
{{out}}
<pre>Mean = 1.0098
Line 363 ⟶ 810:
=={{header|DWScript}}==
<
var i : Integer;
for i := values.Low to values.High do
values[i] := RandG(1, 0.5);</
=={{header|E}}==
<
=={{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}}==
<
class
APPLICATION
Line 477 ⟶ 936:
end
end
</syntaxhighlight>
Example Result
Line 484 ⟶ 943:
Standard Deviation: 0.49042787564453988
</pre>
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
import extensions'math;
Line 501 ⟶ 961:
real tAvg := 0;
for (int x := 0
{
a[x] := (randomNormal()) / 2 + 1;
Line 511 ⟶ 971:
real s := 0;
for (int x := 0
{
s += power(a[x] - tAvg, 2)
Line 521 ⟶ 981:
console.readChar()
}</
{{out}}
<pre>
Line 529 ⟶ 989:
=={{header|Elixir}}==
<
def normal(mean, sd) do
{a, b} = {:rand.uniform, :rand.uniform}
Line 544 ⟶ 1,004:
xs = for _ <- 1..1000, do: Random.normal(1.0, 0.5)
std_dev.(xs)</
{{out}}
<pre>
Line 551 ⟶ 1,011:
used Erlang function <code>:rand.normal</code>
<
std_dev.(xs)</
{{out}}
<pre>
Line 561 ⟶ 1,021:
{{works with|Erlang}}
<
mean(Values) ->
mean(tl(Values), hd(Values), 1).
Line 593 ⟶ 1,053:
io:format("mean = ~w\n", [mean(X)]),
io:format("stddev = ~w\n", [stddev(X)]).
</syntaxhighlight>
{{out}}
<pre>
Line 601 ⟶ 1,061:
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM DISTRIBUTION
Line 637 ⟶ 1,097:
END PROGRAM
</syntaxhighlight>
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
>v=normal(1,1000)*0.5+1;
>mean(v), dev(v)
1.00291801071
0.498226876528
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|PureBasic}}
<
function RandomNormal()
Line 664 ⟶ 1,124:
for i = 1 to n do
s[i] = 1 + 0.5 * RandomNormal()
end for</
=={{header|F_Sharp|F#}}==
<
let n = MathNet.Numerics.Distributions.Normal(1.0,0.5)
List.init 1000 (fun _->n.Sample())
</syntaxhighlight>
{{out}}
<pre>
Line 700 ⟶ 1,153:
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}}==
<
1000 [ 1.0 0.5 normal-random-float ] replicate</
=={{header|Falcon
<
for i in [0:1000] : a+= norm_rand_num()
Line 712 ⟶ 1,172:
pi = 2*acos(0)
return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2
end</
=={{header|Fantom}}==
Line 718 ⟶ 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:
<
class Main
{
Line 736 ⟶ 1,196:
}
}
</syntaxhighlight>
The second calls out to Java's Gaussian random-number generator:
<
using [java] java.util::Random
Line 761 ⟶ 1,221:
}
}
</syntaxhighlight>
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
<
here to seed
Line 781 ⟶ 1,241:
0 do frnd-normal 0.5e f* 1e f+ f, loop ;
create rnd-array 1000 ,normals</
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}}
<
INTEGER, PARAMETER :: n = 1000
Line 810 ⟶ 1,272:
WRITE(*, "(A,F8.6)") "Standard Deviation = ", sd
END PROGRAM Random</
{{out}}
Line 816 ⟶ 1,278:
Mean = 0.995112
Standard Deviation = 0.503373
</pre>
Line 865 ⟶ 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.
<
function randg(mean,stddev: float): float;
</syntaxhighlight>
=={{header|
<syntaxhighlight lang="frink">a = new array[[1000], {|x| randomGaussian[1, 0.5]}]</syntaxhighlight>
=={{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.
<
import (
Line 924 ⟶ 1,337:
fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
}
}</
{{out}}
<pre>
Line 941 ⟶ 1,354:
***
**
</pre>
=={{header|Groovy}}==
<
result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }</
=={{header|Haskell}}==
<
pairs :: [a] -> [(a,a)]
Line 1,003 ⟶ 1,375:
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g</
Or using Data.Random from random-fu package:
<
To print them:
<
import Control.Monad
Line 1,016 ⟶ 1,388:
main = do
x <- sample thousandRandomNumbers
print x</
=={{header|HicEst}}==
<
pi = 4 * ATAN(1)
array = s * (-2*LOG(RAN(1)))^0.5 * COS(2*pi*RAN(1)) + m </
=={{header|Icon}} and {{header|Unicon}}==
Line 1,028 ⟶ 1,400:
Note that Unicon randomly seeds it's generator.
<
procedure main()
local L
Line 1,036 ⟶ 1,408:
every write(!L)
end
</syntaxhighlight>
=={{header|IDL}}==
<
=={{header|J}}==
'''Solution:'''
<
zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand
1 + 0.5 * zrand 100</
'''Alternative Solution:'''<br>
Using the normal script from the [[j:Addons/stats/distribs|stats/distribs addon]].
<
1 0.5 rnorm 1000
1.44868803 1.21548637 0.812460657 1.54295452 1.2470606 ...</
=={{header|Java}}==
<
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();
}</
=={{header|JavaScript}}==
<
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
Line 1,070 ⟶ 1,442:
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
}</
=={{header|jq}}==
Line 1,083 ⟶ 1,455:
''''A Pseudo-Random Number Generator''''
<
# The random numbers are in [0 -- 32767] inclusive.
# Input: an array of length at least 2 interpreted as [count, state, ...]
Line 1,090 ⟶ 1,462:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ] ;</
''''Box-Muller Method''''
<
# 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,111 ⟶ 1,483:
next_rand_normal
| recurse( if .[0] < count then next_rand_normal else empty end)
| .[2] = (.[2] * sd) + mean;</
'''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:
<
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</
{{out}}
$ jq -n -c -f Random_numbers.jq
Line 1,128 ⟶ 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):
<
=={{header|Kotlin}}==
<
import java.util.Random
Line 1,144 ⟶ 1,516:
println("Mean is $mean")
println("S.D. is $sd")
}</
Sample output:
{{out}}
Line 1,155 ⟶ 1,527:
{{works with|LabVIEW|8.6}}
[[File:LV_array_of_randoms_with_given_mean_and_stdev.png]]
=={{header|Lingo}}==
<
on randf ()
n = random(the maxinteger)-1
return n / float(the maxinteger-1)
end</
<
repeat with i = 1 to 1000
normal.add(1 + sqrt(-2 * log(randf())) * cos(2 * PI * randf()) / 2)
end repeat</
=={{header|Lobster}}==
Uses built-in <code>rnd_gaussian</code>
<syntaxhighlight lang="lobster">
let mean = 1.0
let stdv = 0.5
Line 1,222 ⟶ 1,572:
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.
<syntaxhighlight lang="logo">to random.float ; 0..1
localmake "max.int lshift -1 -1
output quotient random :max.int :max.int
end
to random.gaussian
output product cos random 360 sqrt -2 / ln random.float
end
make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []</syntaxhighlight>
=={{header|Lua}}==
<
for i = 1, 1000 do
list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
end</
=={{header|M2000 Interpreter}}==
M2000 use a Wichmann - Hill Pseudo Random Number Generator.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Function StdDev (A()) {
Line 1,287 ⟶ 1,651:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<
Sample(Normal(1, 0.5), 1000);</
'''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:
<
=={{header|MATLAB}}==
Native support :
<
x = randn(1000,1) * sd + mu;
</syntaxhighlight>
The statistics toolbox provides this function
<
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.
<
radiusSquared = +Inf;
Line 1,323 ⟶ 1,691:
randNum = (v .* scaleFactor .* chi2) + mu0;
end</
Output:
<
ans =
0.693984121077029</
=={{header|Maxima}}==
<
random_normal(1.0, 0.5, 1000);</
=={{header|MAXScript}}==
<
for i in 1 to 1000 do
(
Line 1,346 ⟶ 1,714:
c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees
append arr c
)</
=={{header|Metafont}}==
Line 1,352 ⟶ 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:
<
m := 0; % m holds the mean, for testing purposes
Line 1,370 ⟶ 1,738:
show m, s; % and let's show that really they get what we wanted
end</
A run gave
Line 1,381 ⟶ 1,749:
=={{header|MiniScript}}==
<
return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function
Line 1,388 ⟶ 1,756:
for i in range(1,1000)
x.push randNormal(1, 0.5)
end for</
=={{header|Mirah}}==
<
list = double[999]
Line 1,400 ⟶ 1,768:
list[i] = mean + std * rng.nextGaussian
end
</syntaxhighlight>
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П7 <-> П8 1/x П6 ИП6 П9 СЧ П6 1/x
ln ИП8 * 2 * КвКор ИП9 2 * пи
* sin * ИП7 + С/П БП 05</
''Input'': РY - variance, РX - expectation.
Line 1,411 ⟶ 1,779:
Or:
<syntaxhighlight lang="text">3 10^x П0 ПП 13 2 / 1 + С/П L0 03 С/П
СЧ lg 2 /-/ * КвКор 2 пи ^ СЧ * * cos * В/О</
to generate 1000 numbers with a mean of 1.0 and a standard deviation of 0.5.
Line 1,419 ⟶ 1,787:
{{trans|C}}
<
IMPORT Random;
Line 1,439 ⟶ 1,807:
rands[i] := 1.0D0 + 0.5D0 * RandNorm();
END;
END Rand.</
=={{header|Nanoquery}}==
{{trans|Java}}
<
mean = 1.0; std = 0.5
rng = new(Nanoquery.Util.Random)
Line 1,449 ⟶ 1,817:
for i in range(0, len(list) - 1)
list[i] = mean + std * rng.getGaussian()
end</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,507 ⟶ 1,875:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,550 ⟶ 1,918:
=={{header|NewLISP}}==
<syntaxhighlight lang
=={{header|Nim}}==
<
var rs: RunningStat
randomize()
for
echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}"
</syntaxhighlight>
{{out}}
<pre>mean: 1.
mean: 1.
mean:
mean:
mean: 1.
=={{header|Objeck}}==
<
class RandomNumbers {
function : Main(args : String[]) ~ Nil {
Line 1,593 ⟶ 1,956:
}
}
}</
=={{header|OCaml}}==
<
let random_gaussian () =
1. +. sqrt (-2. *. log (Random.float 1.)) *. cos (2. *. pi *. Random.float 1.);;
let a = Array.init 1000 (fun _ -> random_gaussian ());;</
=={{header|Octave}}==
<
disp(mean(p));
disp(sqrt(sum((p - mean(p)).^2)/numel(p)));</
{{out}}
Line 1,613 ⟶ 1,976:
{{trans|REXX}}
===version 1===
<
pi=RxCalcPi() /* get value of pi */
Parse Arg n seed . /* allow specification of N & seed*/
Line 1,654 ⟶ 2,017:
Return RxCalcPower(_/n,.5)
:: requires rxmath library</
{{out}}
<pre> old mean= 0.49830002
Line 1,663 ⟶ 2,026:
===version 2===
Using the nice function names in the algorithm.
<
pi=RxCalcPi() /* get value of pi */
Parse Arg n seed . /* allow specification of N & seed*/
Line 1,708 ⟶ 2,071:
sin: Return RxCalcSin(arg(1),,'R')
:: requires rxmath library</
=={{header|PARI/GP}}==
<
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*
\\ Could easily be extended with a second normal at very little cost.
};
vector(1000,unused,rnormal()/2+1)</
=={{header|Pascal}}==
The following function calculates Gaussian-distributed random numbers with the Box-Müller algorithm:
<
function rnorm (mean, sd: real): real;
{Calculates Gaussian random numbers according to the Box-Müller approach}
Line 1,729 ⟶ 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>
[[#Delphi | Delphi]] and [[#Free Pascal|Free Pascal]] support implement a '''randg''' function that delivers Gaussian-distributed random numbers.
=={{header|Perl}}==
<
my @nums = map {
1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand)
} 1..1000;</
=={{header|
{{Trans|Euphoria}}
<!--<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}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
def RandomNormal
drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 +
enddef
1000 var n
0 n repeat
getid RandomNormal map
dup
sum n / var mean
"Mean: " print mean print nl
0 swap n for
get mean - 2 power rot + swap
endfor
swap n / sqrt "Standard deviation: " print print</syntaxhighlight>
=={{header|PHP}}==
<
return mt_rand() / mt_getrandmax();
}
Line 1,779 ⟶ 2,152:
$a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);
}</
=={{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}}
<
(de randomNormal () # Normal distribution, centered on 0, std dev 1
Line 1,798 ⟶ 2,201:
(link (+ 1.0 (/ (randomNormal) 2))) ) )
(for N (head 7 Result) # Print first 7 results
(prin (format N *Scl) " ") ) )</
{{out}}
<pre>1.500334 1.212931 1.095283 0.433122 0.459116 1.302446 0.402477</pre>
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* CONVERTED FROM WIKI FORTRAN */
Normal_Random: procedure options (main);
Line 1,825 ⟶ 2,228:
put skip edit ( "Standard Deviation = ", sd) (a, F(18,16));
END Normal_Random;
</syntaxhighlight>
{{out}}
<pre>
Line 1,836 ⟶ 2,239:
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
DECLARE
--The desired collection
Line 1,852 ⟶ 2,255:
END LOOP;
END;
</syntaxhighlight>
=={{header|Pop11}}==
<
true -> popradians;
Line 1,869 ⟶ 2,272:
for i from 1 to 1000 do 1.0+0.5*random_normal() endfor;
;;; collect them into array
consvector(1000) -> array;</
=={{header|PowerShell}}==
Equation adapted from Liberty BASIC
<
{
[CmdletBinding()]
Line 1,908 ⟶ 2,311:
$Stats | Format-List
</syntaxhighlight>
{{out}}
<pre>
Line 1,915 ⟶ 2,318:
StandardDeviation : 0.489099623426272
</pre>
=={{header|Python}}==
;Using random.gauss:
<
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>> </
;Quick check of distribution:
<
count = len(numbers)
mean = sum(numbers) / count
Line 1,951 ⟶ 2,334:
>>> quick_check(values)
(1.0140373306786599, 0.49943411329234066)
>>> </
Note that the ''random'' module in the Python standard library supports a number of statistical distribution methods.
;Alternatively using random.normalvariate:
<
>>> quick_check(values)
(0.990099111944864, 0.5029847005836282)
>>> </
=={{header|R}}==
<syntaxhighlight lang="rsplus"># For reproducibility, set the seed:
set.seed(12345L)
result <- rnorm(1000, mean = 1, sd = 0.5)</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(for/list ([i 1000])
(add1 (* (sqrt (* -2 (log (random)))) (cos (* 2 pi (random))) 0.5)))
</syntaxhighlight>
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}}==
<
-1 acos
Line 1,984 ⟶ 2,392:
2 / 1 +
1000 each drop randNormal "%f\n" print</
Quick Check (on linux with code in file rand.rv)
<
stdev = 0.497773
mean = 1.01497</
=={{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 1,996 ⟶ 2,420:
Programming note: note the range of the random numbers: (0,1]
<br>(that is, random numbers from zero──►unity, excluding zero, including unity).
<
numeric digits 20 /*the default decimal digit precision=9*/
parse arg n seed . /*allow specification of N and the seed*/
Line 2,040 ⟶ 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</
'''output''' when using the default inputs:
<pre>
Line 2,051 ⟶ 2,475:
=={{header|Ring}}==
<
for i = 1 to 10
see random(i) + nl
next i
</syntaxhighlight>
=={{header|
≪ RAND LN NEG 2 * √
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|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:'''
<
use rand::distributions::{Normal, IndependentSample};
Line 2,079 ⟶ 2,514:
*num = normal.ind_sample(&mut rng);
}
}</
'''Using iterators:'''
<
use rand::distributions::{Normal, IndependentSample};
Line 2,091 ⟶ 2,526:
(0..1000).map(|_| normal.ind_sample(&mut rng)).collect()
};
}</
=={{header|SAS}}==
<syntaxhighlight 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,107 ⟶ 2,542:
end;
run;
</syntaxhighlight>
Results:
<pre>
Line 2,121 ⟶ 2,556:
=={{header|Sather}}==
<
main is
a:ARRAY{FLTD} := #(1000);
Line 2,139 ⟶ 2,574:
#OUT + "dev " + dev + "\n";
end;
end;</
=={{header|Scala}}==
===One liner===
<
===Academic===
<syntaxhighlight lang
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)
}
/*
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
val mean: T =
Line 2,161 ⟶ 2,599:
// Root of mean diffs
val stdDev = Math.sqrt(ts.map { x =>
val diff = num.toDouble(num.minus(x, mean))
diff * diff
Line 2,169 ⟶ 2,607:
}
println(calcAvgAndStddev(
}
</syntaxhighlight>
=={{header|Scheme}}==
<
(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))
Line 2,218 ⟶ 2,658:
(mean-sdev v)
; (0.9562156817697293 0.5097087109575911)</
=={{header|Seed7}}==
<
include "float.s7i";
include "math.s7i";
Line 2,245 ⟶ 2,685:
rands[i] := 1.0 + 0.5 * randomNormal;
end for;
end func;</
=={{header|Sidef}}==
<
arr.each { .say }</
=={{header|Standard ML}}==
Line 2,259 ⟶ 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.
<
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 ());</
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.
<
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 ());</
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|
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
Line 2,312 ⟶ 2,752:
val anyrealseed=1009.0 ;
makeNormals bmconv (urandomlist anyrealseed 2000);
</syntaxhighlight>
=={{header|Stata}}==
<
set obs 1000
gen x=rnormal(1,0.5)</
=== Mata ===
<
=={{header|Tcl}}==
<
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
Line 2,333 ⟶ 2,773:
for {set i 0} {$i < 1000} {incr i} {
lappend result [expr {$mean + $stddev*nrand()}]
}</
=={{header|TorqueScript}}==
<
%list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom());</
=={{header|Uiua}}==
[https://www.uiua.org/pad?src=0_12_0-dev_1__IyBHZW5lcmF0ZSBub3JtYWwgZGlzdHJpYnV0aW9uIHdpdGggbWVhbiA9IDEsIHNkID0gMC41CkdhdXNzIOKGkCAow5co4oi_K863w5fDlzLPgOKagikgKOKImsOXwq8y4oKZZeKagikpClvijaUoKzHDlzAuNUdhdXNzKTEwMDBdICMgLT4gbWVhbiA9IDEsIHNkID0gMC41Ck1lYW4g4oaQIMO34qe74p-cLysKU2Qg4oaQIOKImsO34oqDKOKLheKnu3wvK8OXLi0pTWVhbi4K4oq44oqDU2QgTWVhbgo= Run it in Uiua Pad]
<syntaxhighlight lang="uiua">
# Generate normal distribution with mean = 1, sd = 0.5
Gauss ← (×(∿+η××2π⚂) (√ׯ2ₙe⚂))
[⍥(+1×0.5Gauss)1000] # -> mean = 1, sd = 0.5
Mean ← ÷⧻⟜/+
Sd ← √÷⊃(⋅⧻|/+×.-)Mean.
⊸⊃Sd Mean
</syntaxhighlight>
{{out}}
<pre>
[0.5549431582333864 0.6318745755493541 0.243308532933335 ...etc...]
1.026433943526625
0.4953224276300106
</pre>
=={{header|Ursala}}==
Line 2,367 ⟶ 2,806:
a standard normal distribution. Mean and standard deviation
library functions are also used in this example.
<
#import flo
Line 2,380 ⟶ 2,819:
^(mean,stdev)* <
pop_stats(1.,0.5) 1000,
sample_stats(1.,0.5) 1000></
The output shows the mean and standard deviation for both sample vectors,
the latter being exact by construction.
Line 2,388 ⟶ 2,827:
=={{header|Visual FoxPro}}==
<
LOCAL i As Integer, m As Double, n As Integer, sd As Double
py = PI()
Line 2,415 ⟶ 2,854:
RETURN z
ENDFUNC
</syntaxhighlight>
=={{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.
<
return sqrt(-2*log(random(count))) * cos(2*pi*random(count));
}</
Example of basic use:
Line 2,438 ⟶ 2,937:
=={{header|zkl}}==
<
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 })
}</
This creates a new random number generator, now to use it:
<
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</
|