Random numbers: Difference between revisions

→‎{{header|BASIC}}: Added ANSI BASIC.
(→‎{{header|BASIC}}: Added ANSI BASIC.)
 
(16 intermediate revisions by 9 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 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|Applesoft BASIC}}===
The [[Random_numbers#Commodore_BASIC|Commodore BASIC]] code works in Applesoft BASIC.
Line 203 ⟶ 227:
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))
NEXT
mean = SUM(array()) / (DIM(array(),1) + 1)
array() -= mean
stdev = MOD(array()) / SQR(DIM(array(),1) + 1)
PRINT "Mean = " ; mean
PRINT "Standard deviation = " ; stdev</syntaxhighlight>
{{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}}===
Line 240 ⟶ 316:
330 END
</syntaxhighlight>
 
==={{header|BBC BASIC}}===
==={{header|FreeBASIC}}===
<syntaxhighlight lang="bbcbasic"> DIM array(999)
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
FOR number% = 0 TO 999
 
array(number%) = 1.0 + 0.5 * SQR(-2*LN(RND(1))) * COS(2*PI*RND(1))
Const pi As Double = 3.141592653589793
NEXT
Randomize
 
mean = SUM(array()) / (DIM(array(),1) + 1)
' Generates normally distributed random numbers with mean 0 and standard deviation 1
array() -= mean
Function randomNormal() As Double
stdev = MOD(array()) / SQR(DIM(array(),1) + 1)
Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd))
End Function
PRINT "Mean = " ; mean
 
PRINT "Standard deviation = " ; stdev</syntaxhighlight>
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 = 1.01848064
Mean is 1.000763573902885
Standard deviation = 0.503551814</pre>
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}}==
Line 579 ⟶ 822:
 
<syntaxhighlight lang="text">
numfmt 5 0
e = 2.7182818284590452354
for i = 1 to 1000
a[] &= 1 + 0.5 * sqrt (-2 * lognlog10 randomf / log10 e) * cos (360 * randomf)
.
printfor 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>
 
Line 692 ⟶ 946:
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.1x :
<syntaxhighlight lang="elena">import extensions;
import extensions'math;
Line 707 ⟶ 961:
real tAvg := 0;
for (int x := 0,; x < a.Length,; x += 1)
{
a[x] := (randomNormal()) / 2 + 1;
Line 717 ⟶ 971:
real s := 0;
for (int x := 0,; x < a.Length,; x += 1)
{
s += power(a[x] - tAvg, 2)
Line 1,032 ⟶ 1,286:
function randg(mean,stddev: float): float;
</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|Frink}}==
<syntaxhighlight lang="frink">a = new array[[1000], {|x| randomGaussian[1, 0.5]}]</syntaxhighlight>
 
=={{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|Go}}==
Line 1,354 ⟶ 1,527:
{{works with|LabVIEW|8.6}}
[[File:LV_array_of_randoms_with_given_mean_and_stdev.png]]
 
=={{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|Lingo}}==
Line 2,153 ⟶ 2,318:
StandardDeviation : 0.489099623426272
</pre>
 
=={{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|Python}}==
Line 2,335 ⟶ 2,480:
next i
</syntaxhighlight>
 
=={{header|RPL}}==
≪ 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|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|Rust}}==
Line 2,558 ⟶ 2,713:
 
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="smlhsml">
val urandomlist = fn seed => fn n =>
let
Line 2,619 ⟶ 2,774:
lappend result [expr {$mean + $stddev*nrand()}]
}</syntaxhighlight>
 
=={{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}}==
Line 2,700 ⟶ 2,837:
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="ecmascriptwren">import "random" for Random
 
var rand = Random.new()
Line 2,733 ⟶ 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}}==
Line 2,766 ⟶ 2,931:
// calc sd of list of numbers:
(ns.reduce('wrap(p,n){p+(n-mean).pow(2)},0.0)/1000).sqrt() //-->0.494844</syntaxhighlight>
 
=={{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>
511

edits