Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,6 @@
---
category:
- Probability and statistics
- Randomness
from: http://rosettacode.org/wiki/Random_numbers
note: Basic language learning

View file

@ -0,0 +1,10 @@
;Task:
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:
*   [[Standard deviation]]
<br><br>

View file

@ -0,0 +1,13 @@
PROC random normal = REAL: # normal distribution, centered on 0, std dev 1 #
(
sqrt(-2*log(random)) * cos(2*pi*random)
);
test:(
[1000]REAL rands;
FOR i TO UPB rands DO
rands[i] := 1 + random normal/2
OD;
INT limit=10;
printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit]))
)

View file

@ -0,0 +1 @@
$ 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}'

View file

@ -0,0 +1,12 @@
function r() {
return sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() )
}
BEGIN {
n=1000
for(i=0;i<n;i++) {
x = 1 + 0.5*r()
s = s" "x
}
print s
}

View file

@ -0,0 +1,23 @@
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;
procedure Normal_Random is
function Normal_Distribution
( Seed : Generator;
Mu : Float := 1.0;
Sigma : Float := 0.5
) return Float is
begin
return
Mu + (Sigma * Sqrt (-2.0 * Log (Random (Seed), 10.0)) * Cos (2.0 * Pi * Random (Seed)));
end Normal_Distribution;
Seed : Generator;
Distribution : array (1..1_000) of Float;
begin
Reset (Seed);
for I in Distribution'Range loop
Distribution (I) := Normal_Distribution (Seed);
end loop;
end Normal_Random;

View file

@ -0,0 +1,7 @@
rnd: function []-> (random 0 10000)//10000
rands: map 1..1000 'x [
1 + (sqrt neg 2 * ln rnd) * (cos 2 * pi * rnd)
]
print rands

View file

@ -0,0 +1,15 @@
Loop 40
R .= RandN(1,0.5) "`n" ; mean = 1.0, standard deviation = 0.5
MsgBox %R%
RandN(m,s) { ; Normally distributed random numbers of mean = m, std.dev = s by Box-Muller method
Static i, Y
If (i := !i) { ; every other call
Random U, 0, 1.0
Random V, 0, 6.2831853071795862
U := sqrt(-2*ln(U))*s
Y := m + U*sin(V)
Return m + U*cos(V)
}
Return Y
}

View file

@ -0,0 +1,33 @@
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;

View file

@ -0,0 +1,26 @@
# 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

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,17 @@
#include <random>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
random_device seed;
mt19937 engine(seed());
normal_distribution<double> dist(1.0, 0.5);
auto rnd = bind(dist, engine);
vector<double> v(1000);
generate(v.begin(), v.end(), rnd);
return 0;
}

View file

@ -0,0 +1,27 @@
#include <cstdlib> // for rand
#include <cmath> // for atan, sqrt, log, cos
#include <algorithm> // for generate_n
double const pi = 4*std::atan(1.0);
// simple functor for normal distribution
class normal_distribution
{
public:
normal_distribution(double m, double s): mu(m), sigma(s) {}
double operator() const // returns a single normally distributed number
{
double r1 = (std::rand() + 1.0)/(RAND_MAX + 1.0); // gives equal distribution in (0, 1]
double r2 = (std::rand() + 1.0)/(RAND_MAX + 1.0);
return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2);
}
private:
const double mu, sigma;
};
int main()
{
double array[1000];
std::generate_n(array, 1000, normal_distribution(1.0, 0.5));
return 0;
}

View file

@ -0,0 +1,20 @@
#include <vector>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
#include <boost/random/normal_distribution.hpp>
#include <algorithm>
typedef boost::mt19937 RNGType; ///< mersenne twister generator
int main() {
RNGType rng;
boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution
with mean of 1.0 and standard deviation of 0.5 */
boost::variate_generator< RNGType, boost::normal_distribution<> >
get_rand(rng, rdist);
std::vector<double> v(1000);
generate(v.begin(),v.end(),get_rand);
return 0;
}

View file

@ -0,0 +1,4 @@
private static double randomNormal()
{
return Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble()));
}

View file

@ -0,0 +1,27 @@
static Random tRand = new Random();
static void Main(string[] args)
{
double[] a = new double[1000];
double tAvg = 0;
for (int x = 0; x < a.Length; x++)
{
a[x] = randomNormal() / 2 + 1;
tAvg += a[x];
}
tAvg /= a.Length;
Console.WriteLine("Average: " + tAvg.ToString());
double s = 0;
for (int x = 0; x < a.Length; x++)
{
s += Math.Pow((a[x] - tAvg), 2);
}
s = Math.Sqrt(s / 1000);
Console.WriteLine("Standard Deviation: " + s.ToString());
Console.ReadLine();
}

View file

@ -0,0 +1,22 @@
#include <stdlib.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
double drand() /* uniform distribution, (0..1] */
{
return (rand()+1.0)/(RAND_MAX+1.0);
}
double random_normal() /* normal distribution, centered on 0, std dev 1 */
{
return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}
int main()
{
int i;
double rands[1000];
for (i=0; i<1000; i++)
rands[i] = 1.0 + 0.5*random_normal();
return 0;
}

View file

@ -0,0 +1,67 @@
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.

View file

@ -0,0 +1,22 @@
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

View file

@ -0,0 +1,4 @@
(import '(java.util Random))
(def normals
(let [r (Random.)]
(take 1000 (repeatedly #(-> r .nextGaussian (* 0.5) (+ 1.0))))))

View file

@ -0,0 +1,33 @@
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

View file

@ -0,0 +1,2 @@
(loop for i from 1 to 1000
collect (1+ (* (sqrt (* -2 (log (random 1.0)))) (cos (* 2 pi (random 1.0))) 0.5)))

View file

@ -0,0 +1,6 @@
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}"

View file

@ -0,0 +1,24 @@
import std.stdio, std.random, std.math;
struct NormalRandom {
double mean, stdDev;
// Necessary because it also defines an opCall.
this(in double mean_, in double stdDev_) pure nothrow {
this.mean = mean_;
this.stdDev = stdDev_;
}
double opCall() const /*nothrow*/ {
immutable r1 = uniform01, r2 = uniform01; // Not nothrow.
return mean + stdDev * sqrt(-2 * r1.log) * cos(2 * PI * r2);
}
}
void main() {
double[1000] array;
auto nRnd = NormalRandom(1.0, 0.5);
foreach (ref x; array)
//x = nRnd;
x = nRnd();
}

View file

@ -0,0 +1,10 @@
import tango.math.random.Random;
void main() {
double[1000] list;
auto r = new Random();
foreach (ref l; list) {
r.normalSource!(double)()(l);
l = 1.0 + 0.5 * l;
}
}

View file

@ -0,0 +1,5 @@
var values : array [0..999] of Float;
var i : Integer;
for i := values.Low to values.High do
values[i] := RandG(1, 0.5);

View file

@ -0,0 +1,19 @@
program Randoms;
{$APPTYPE CONSOLE}
uses
Math;
var
Values: array[0..999] of Double;
I: Integer;
begin
// Randomize; Commented to obtain reproducible results
for I:= Low(Values) to High(Values) do
Values[I]:= RandG(1.0, 0.5); // Mean = 1.0, StdDev = 0.5
Writeln('Mean = ', Mean(Values):6:4);
Writeln('Std Deviation = ', StdDev(Values):6:4);
Readln;
end.

View file

@ -0,0 +1 @@
accum [] for _ in 1..1000 { _.with(entropy.nextGaussian()) }

View file

@ -0,0 +1,35 @@
PROGRAM DISTRIBUTION
!
! for rosettacode.org
!
! formulas taken from TI-59 Master Library manual
CONST NUM_ITEM=1000
!VAR SUMX#,SUMX2#,R1#,R2#,Z#,I%
DIM A#[1000]
BEGIN
! seeds random number generator with system time
RANDOMIZE(TIMER)
PRINT(CHR$(12);) !CLS
SUMX#=0 SUMX2#=0
FOR I%=1 TO NUM_ITEM DO
R1#=RND(1) R2#=RND(1)
Z#=SQR(-2*LOG(R1#))*COS(2*π*R2#)
A#[I%]=Z#/2+1 ! I want a normal distribution with
! mean=1 and std.dev=0.5
SUMX#+=A#[I%] SUMX2#+=A#[I%]*A#[I%]
END FOR
Z#=SUMX#/NUM_ITEM
PRINT("Average is";Z#)
PRINT("Standard dev. is";SQR(SUMX2#/NUM_ITEM-Z#*Z#))
END PROGRAM

View file

@ -0,0 +1,4 @@
for i = 1 to 1000
a[] &= 1 + 0.5 * sqrt (-2 * logn randomf) * cos (360 * randomf)
.
print a[]

View file

@ -0,0 +1,95 @@
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
l_time: TIME
l_seed: INTEGER
math:DOUBLE_MATH
rnd:RANDOM
Size:INTEGER
once
Result:= 1000
end
make
-- Run application.
local
ergebnis:ARRAY[DOUBLE]
tavg: DOUBLE
x: INTEGER
tmp: DOUBLE
text : STRING
do
-- initialize random generator
create l_time.make_now
l_seed := l_time.hour
l_seed := l_seed * 60 + l_time.minute
l_seed := l_seed * 60 + l_time.second
l_seed := l_seed * 1000 + l_time.milli_second
create rnd.set_seed (l_seed)
-- initialize random number container and math
create ergebnis.make_filled (0.0, 1, size)
tavg := 0;
create math
from
x := 1
until
x > ergebnis.count
loop
tmp := randomNormal / 2 + 1
tavg := tavg + tmp
ergebnis.enter (tmp , x)
x := x + 1
end
tavg := tavg / ergebnis.count
text := "Average: "
text.append_double (tavg)
text.append ("%N")
print(text)
tmp := 0
from
x:= 1
until
x > ergebnis.count
loop
tmp := tmp + (ergebnis.item (x) - tavg)^2
x := x + 1
end
tmp := math.sqrt (tmp / ergebnis.count)
text := "Standard Deviation: "
text.append_double (tmp)
text.append ("%N")
print(text)
end
randomNormal:DOUBLE
local
first: DOUBLE
second: DOUBLE
do
rnd.forth
first := rnd.double_item
rnd.forth
second := rnd.double_item
Result := math.cosine (2 * math.pi * first) * math.sqrt (-2 * math.log (second))
end
end

View file

@ -0,0 +1,35 @@
import extensions;
import extensions'math;
randomNormal()
{
^ cos(2 * Pi_value * randomGenerator.nextReal())
* sqrt(-2 * ln(randomGenerator.nextReal()))
}
public program()
{
real[] a := new real[](1000);
real tAvg := 0;
for (int x := 0, x < a.Length, x += 1)
{
a[x] := (randomNormal()) / 2 + 1;
tAvg += a[x]
};
tAvg /= a.Length;
console.printLine("Average: ", tAvg);
real s := 0;
for (int x := 0, x < a.Length, x += 1)
{
s += power(a[x] - tAvg, 2)
};
s := sqrt(s / 1000);
console.printLine("Standard Deviation: ", s);
console.readChar()
}

View file

@ -0,0 +1,16 @@
defmodule Random do
def normal(mean, sd) do
{a, b} = {:rand.uniform, :rand.uniform}
mean + sd * (:math.sqrt(-2 * :math.log(a)) * :math.cos(2 * :math.pi * b))
end
end
std_dev = fn (list) ->
mean = Enum.sum(list) / length(list)
sd = Enum.reduce(list, 0, fn x,acc -> acc + (x-mean)*(x-mean) end) / length(list)
|> :math.sqrt
IO.puts "Mean: #{mean},\tStdDev: #{sd}"
end
xs = for _ <- 1..1000, do: Random.normal(1.0, 0.5)
std_dev.(xs)

View file

@ -0,0 +1,2 @@
xs = for _ <- 1..1000, do: 1.0 + :rand.normal * 0.5
std_dev.(xs)

View file

@ -0,0 +1,31 @@
mean(Values) ->
mean(tl(Values), hd(Values), 1).
mean([], Acc, Length) ->
Acc / Length;
mean(Values, Acc, Length) ->
mean(tl(Values), hd(Values)+Acc, Length+1).
variance(Values) ->
Mean = mean(Values),
variance(Values, Mean, 0) / length(Values).
variance([], _, Acc) ->
Acc;
variance(Values, Mean, Acc) ->
Diff = hd(Values) - Mean,
DiffSqr = Diff * Diff,
variance(tl(Values), Mean, Acc + DiffSqr).
stddev(Values) ->
math:sqrt(variance(Values)).
normal(Mean, StdDev) ->
U = random:uniform(),
V = random:uniform(),
Mean + StdDev * ( math:sqrt(-2 * math:log(U)) * math:cos(2 * math:pi() * V) ). % Erlang's math:log is the natural logarithm.
main(_) ->
X = [ normal(1.0, 0.5) || _ <- lists:seq(1, 1000) ],
io:format("mean = ~w\n", [mean(X)]),
io:format("stddev = ~w\n", [stddev(X)]).

View file

@ -0,0 +1,4 @@
>v=normal(1,1000)*0.5+1;
>mean(v), dev(v)
1.00291801071
0.498226876528

View file

@ -0,0 +1,15 @@
include misc.e
function RandomNormal()
atom x1, x2
x1 = rand(999999) / 1000000
x2 = rand(999999) / 1000000
return sqrt(-2*log(x1)) * cos(2*PI*x2)
end function
constant n = 1000
sequence s
s = repeat(0,n)
for i = 1 to n do
s[i] = 1 + 0.5 * RandomNormal()
end for

View file

@ -0,0 +1,2 @@
let n = MathNet.Numerics.Distributions.Normal(1.0,0.5)
List.init 1000 (fun _->n.Sample())

View file

@ -0,0 +1,6 @@
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() ]

View file

@ -0,0 +1,2 @@
USING: random ;
1000 [ 1.0 0.5 normal-random-float ] replicate

View file

@ -0,0 +1,7 @@
a = []
for i in [0:1000] : a+= norm_rand_num()
function norm_rand_num()
pi = 2*acos(0)
return 1 + (cos(2 * pi * random()) * pow(-2 * log(random()) ,1/2)) /2
end

View file

@ -0,0 +1,17 @@
class Main
{
static const Float PI := 0.0f.acos * 2 // we need to precompute PI
static Float randomNormal ()
{
return (Float.random * PI * 2).cos * (Float.random.log * -2).sqrt
}
public static Void main ()
{
mean := 1.0f
sd := 0.5f
Float[] values := [,] // this is the collection to fill with random numbers
1000.times { values.add (randomNormal * sd + mean) }
}
}

View file

@ -0,0 +1,20 @@
using [java] java.util::Random
class Main
{
Random generator := Random()
Float randomNormal ()
{
return generator.nextGaussian
}
public static Void main ()
{
rnd := Main() // create an instance of Main class, which holds the generator
mean := 1.0f
sd := 0.5f
Float[] values := [,] // this is the collection to fill with random numbers
1000.times { values.add (rnd.randomNormal * sd + mean) }
}
}

View file

@ -0,0 +1,16 @@
require random.fs
here to seed
-1. 1 rshift 2constant MAX-D \ or s" MAX-D" ENVIRONMENT? drop
: frnd ( -- f ) \ uniform distribution 0..1
rnd rnd dabs d>f MAX-D d>f f/ ;
: frnd-normal ( -- f ) \ centered on 0, std dev 1
frnd pi f* 2e f* fcos
frnd fln -2e f* fsqrt f* ;
: ,normals ( n -- ) \ store many, centered on 1, std dev 0.5
0 do frnd-normal 0.5e f* 1e f+ f, loop ;
create rnd-array 1000 ,normals

View file

@ -0,0 +1 @@
rnd rnd dabs d>f

View file

@ -0,0 +1,24 @@
PROGRAM Random
INTEGER, PARAMETER :: n = 1000
INTEGER :: i
REAL :: array(n), pi, temp, mean = 1.0, sd = 0.5
pi = 4.0*ATAN(1.0)
CALL RANDOM_NUMBER(array) ! Uniform distribution
! Now convert to normal distribution
DO i = 1, n-1, 2
temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean
array(i+1) = sd * SQRT(-2.0*LOG(array(i))) * SIN(2*pi*array(i+1)) + mean
array(i) = temp
END DO
! Check mean and standard deviation
mean = SUM(array)/n
sd = SQRT(SUM((array - mean)**2)/n)
WRITE(*, "(A,F8.6)") "Mean = ", mean
WRITE(*, "(A,F8.6)") "Standard Deviation = ", sd
END PROGRAM Random

View file

@ -0,0 +1 @@
function randg(mean,stddev: float): float;

View file

@ -0,0 +1,36 @@
' 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

View file

@ -0,0 +1 @@
a = new array[[1000], {|x| randomGaussian[1, 0.5]}]

View file

@ -0,0 +1,29 @@
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

View file

@ -0,0 +1,46 @@
package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
const mean = 1.0
const stdv = .5
const n = 1000
func main() {
var list [n]float64
rand.Seed(time.Now().UnixNano())
for i := range list {
list[i] = mean + stdv*rand.NormFloat64()
}
// show computed mean and stdv of list
var s, sq float64
for _, v := range list {
s += v
}
cm := s / n
for _, v := range list {
d := v - cm
sq += d * d
}
fmt.Printf("mean %.3f, stdv %.3f\n", cm, math.Sqrt(sq/(n-1)))
// show histogram by hdiv divisions per stdv over +/-hrange stdv
const hdiv = 3
const hrange = 2
var h [1 + 2*hrange*hdiv]int
for _, v := range list {
bin := hrange*hdiv + int(math.Floor((v-mean)/stdv*hdiv+.5))
if bin >= 0 && bin < len(h) {
h[bin]++
}
}
const hscale = 10
for _, c := range h {
fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
}
}

View file

@ -0,0 +1,2 @@
rnd = new Random()
result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }

View file

@ -0,0 +1,14 @@
import System.Random
pairs :: [a] -> [(a,a)]
pairs (x:y:zs) = (x,y):pairs zs
pairs _ = []
gauss mu sigma (r1,r2) =
mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)
gaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a]
gaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g

View file

@ -0,0 +1 @@
replicateM 1000 $ normal 1 0.5

View file

@ -0,0 +1,9 @@
import Data.Random
import Control.Monad
thousandRandomNumbers :: RVar [Double]
thousandRandomNumbers = replicateM 1000 $ normal 1 0.5
main = do
x <- sample thousandRandomNumbers
print x

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1 @@
result = 1.0 + 0.5*randomn(seed,1000)

View file

@ -0,0 +1,7 @@
procedure main()
local L
L := list(1000)
every L[1 to 1000] := 1.0 + 0.5 * sqrt(-2.0 * log(?0)) * cos(2.0 * &pi * ?0)
every write(!L)
end

View file

@ -0,0 +1,4 @@
urand=: ?@$ 0:
zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand
1 + 0.5 * zrand 100

View file

@ -0,0 +1,3 @@
require 'stats/distribs/normal'
1 0.5 rnorm 1000
1.44868803 1.21548637 0.812460657 1.54295452 1.2470606 ...

View file

@ -0,0 +1,6 @@
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();
}

View file

@ -0,0 +1,8 @@
function randomNormal() {
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
var a = []
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
}

View file

@ -0,0 +1,8 @@
# 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, ...]
# Output: [count+1, newstate, r] where r is the next pseudo-random number.
def next_rand_Microsoft:
.[0] as $count | .[1] as $state
| ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ] ;

View file

@ -0,0 +1,20 @@
# 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]
# Output [n+1, nextstate, r]
def next_rand_normal:
def u: next_rand_Microsoft | .[2] /= 32767;
u as $u1
| ($u1 | u) as $u2
| ((( (8*(1|atan)) * $u1[2]) | cos)
* ((-2 * (($u2[2]) | log)) | sqrt)) as $r
| [ (.[0]+1), $u2[1], $r] ;
# Generate "count" arrays, each containing a random normal variate with the given mean and standard deviation.
# Input: [count, state]
# Output: [updatedcount, updatedstate, rnv]
# where "state" is a seed and "updatedstate" can be used as a seed.
def random_normal_variate(mean; sd; count):
next_rand_normal
| recurse( if .[0] < count then next_rand_normal else empty end)
| .[2] = (.[2] * sd) + mean;

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1 @@
randn(1000) * 0.5 + 1

View file

@ -0,0 +1,14 @@
// version 1.0.6
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val da = DoubleArray(1000)
for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian()
// now check actual mean and SD
val mean = da.average()
val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())
println("Mean is $mean")
println("S.D. is $sd")
}

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1,5 @@
-- Returns a random float value in range 0..1
on randf ()
n = random(the maxinteger)-1
return n / float(the maxinteger-1)
end

View file

@ -0,0 +1,4 @@
normal = []
repeat with i = 1 to 1000
normal.add(1 + sqrt(-2 * log(randf())) * cos(2 * PI * randf()) / 2)
end repeat

View file

@ -0,0 +1,29 @@
let mean = 1.0
let stdv = 0.5
let count = 1000
// stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232
def stats(xs: [float]) -> float, float: // variance, mean
var M = xs[0]
var S = 0.0
var n = 1.0
for(xs.length - 1) i:
let x = xs[i + 1]
n = n + 1.0
let mm = (x - M)
M += mm / n
S += mm * (x - M)
return (if n > 0.0: S / n else: 0.0), M
def test_random_normal() -> [float]:
rnd_seed(floor(seconds_elapsed() * 1000000))
let r = vector_reserve(typeof return, count)
for (count):
r.push(rnd_gaussian() * stdv + mean)
let cvar, cmean = stats(r)
let cstdv = sqrt(cvar)
print concat_string(["Mean: ", string(cmean), ", Std.Deviation: ", string(cstdv)], "")
test_random_normal()

View file

@ -0,0 +1,10 @@
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 ?] []

View file

@ -0,0 +1,4 @@
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

View file

@ -0,0 +1,54 @@
Module CheckIt {
Function StdDev (A()) {
\\ A() has a copy of values
N=Len(A())
if N<1 then Error "Empty Array"
M=Each(A())
k=0
\\ make sum, dev same type as A(k)
sum=A(k)-A(k)
dev=sum
\\ find mean
While M {
sum+=Array(M)
}
Mean=sum/N
\\ make a pointet to A()
P=A()
\\ subtruct from each item
P-=Mean
M=Each(P)
While M {
dev+=Array(M)*Array(M)
}
\\ as pointer to arrray
=(if(dev>0->Sqrt(dev/N), 0), Mean)
}
Function randomNormal {
\\ by default all numbers are double
\\ cos() get degrees
=1+Cos(360 * rnd) * Sqrt(-2 * Ln(rnd)) /2
}
\\ fill array calling randomNormal() for each item
Dim A(1000)<<randomNormal()
\\ we can pass a pointer to array and place it to stack of values
DisplayMeanAndStdDeviation(A()) ' mean ~ 1 std deviation ~0.5
\\ check M2000 rnd only
Dim B(1000)<<rnd
DisplayMeanAndStdDeviation(B()) ' mean ~ 0.5 std deviation ~0.28
DisplayMeanAndStdDeviation((0,0,14,14)) ' mean = 7 std deviation = 7
DisplayMeanAndStdDeviation((0,6,8,14)) ' mean = 7 std deviation = 5
DisplayMeanAndStdDeviation((6,6,8,8)) ' mean = 7 std deviation = 1
Sub DisplayMeanAndStdDeviation(A)
\\ push to stack all items of an array (need an array pointer)
Push ! StdDev(A)
\\ read from strack two numbers
Print "Mean is "; Number
Print "Standard Deviation is "; Number
End Sub
}
Checkit

View file

@ -0,0 +1,2 @@
mu = 1; sd = 0.5;
x = randn(1000,1) * sd + mu;

View file

@ -0,0 +1 @@
x = normrnd(mu, sd, [1000,1]);

View file

@ -0,0 +1,15 @@
function randNum = randNorm(mu0,chi2, sz)
radiusSquared = +Inf;
while (radiusSquared >= 1)
u = ( 2 * rand(sz) ) - 1;
v = ( 2 * rand(sz) ) - 1;
radiusSquared = u.^2 + v.^2;
end
scaleFactor = sqrt( ( -2*log(radiusSquared) )./ radiusSquared );
randNum = (v .* scaleFactor .* chi2) + mu0;
end

View file

@ -0,0 +1,5 @@
>> randNorm(1,.5, [1000,1])
ans =
0.693984121077029

View file

@ -0,0 +1,8 @@
arr = #()
for i in 1 to 1000 do
(
a = random 0.0 1.0
b = random 0.0 1.0
c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees
append arr c
)

View file

@ -0,0 +1,2 @@
with(Statistics):
Sample(Normal(1, 0.5), 1000);

View file

@ -0,0 +1 @@
1+0.5*ArrayTools[RandomArray](1000,1,distribution=normal);

View file

@ -0,0 +1 @@
RandomReal[NormalDistribution[1, 1/2], 1000]

View file

@ -0,0 +1,3 @@
load(distrib)$
random_normal(1.0, 0.5, 1000);

View file

@ -0,0 +1,19 @@
numeric col[];
m := 0; % m holds the mean, for testing purposes
for i = 1 upto 1000:
col[i] := 1 + .5normaldeviate;
m := m + col[i];
endfor
% testing
m := m / 1000; % finalize the computation of the mean
s := 0; % in s we compute the standard deviation
for i = 1 upto 1000:
s := s + (col[i] - m)**2;
endfor
s := sqrt(s / 1000);
show m, s; % and let's show that really they get what we wanted
end

View file

@ -0,0 +1,8 @@
randNormal = function(mean=0, stddev=1)
return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function
x = []
for i in range(1,1000)
x.push randNormal(1, 0.5)
end for

View file

@ -0,0 +1,20 @@
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

View file

@ -0,0 +1,9 @@
import java.util.Random
list = double[999]
mean = 1.0
std = 0.5
rng = Random.new
0.upto(998) do | i |
list[i] = mean + std * rng.nextGaussian
end

View file

@ -0,0 +1,21 @@
MODULE Rand EXPORTS Main;
IMPORT Random;
FROM Math IMPORT log, cos, sqrt, Pi;
VAR rands: ARRAY [1..1000] OF LONGREAL;
(* Normal distribution. *)
PROCEDURE RandNorm(): LONGREAL =
BEGIN
WITH rand = NEW(Random.Default).init() DO
RETURN
sqrt(-2.0D0 * log(rand.longreal())) * cos(2.0D0 * Pi * rand.longreal());
END;
END RandNorm;
BEGIN
FOR i := FIRST(rands) TO LAST(rands) DO
rands[i] := 1.0D0 + 0.5D0 * RandNorm();
END;
END Rand.

View file

@ -0,0 +1,7 @@
list = {0} * 1000
mean = 1.0; std = 0.5
rng = new(Nanoquery.Util.Random)
for i in range(0, len(list) - 1)
list[i] = mean + std * rng.getGaussian()
end

View file

@ -0,0 +1,55 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.math.BigDecimal
import java.math.MathContext
-- prologue
numeric digits 20
-- get input, set defaults
parse arg dp mu sigma ec .
if mu = '' | mu = '.' then mean = 1.0; else mean = mu
if sigma = '' | sigma = '.' then stdDeviation = 0.5; else stdDeviation = sigma
if dp = '' | dp = '.' then displayPrecision = 1; else displayPrecision = dp
if ec = '' | ec = '.' then elements = 1000; else elements = ec
-- set up
RNG = Random()
numberList = java.util.List
numberList = ArrayList()
-- generate list of random numbers
loop for elements
rn = mean + stdDeviation * RNG.nextGaussian()
numberList.add(BigDecimal(rn, MathContext.DECIMAL128))
end
-- report
say "Mean: " mean
say "Standard Deviation:" stdDeviation
say "Precision: " displayPrecision
say
drawBellCurve(numberList, displayPrecision)
return
-- -----------------------------------------------------------------------------
method drawBellCurve(numberList = java.util.List, precision) static
Collections.sort(numberList)
val = BigDecimal
lastN = ''
nextN = ''
loop val over numberList
nextN = Rexx(val.toPlainString()).format(5, precision)
select
when lastN = '' then nop
when lastN \= nextN then say lastN
otherwise nop
end
say '*\-'
lastN = nextN
end val
say lastN
return

View file

@ -0,0 +1 @@
(normal 1 .5 1000)

View file

@ -0,0 +1,9 @@
import random, stats, strformat
var rs: RunningStat
randomize()
for _ in 1..5:
for _ in 1..1000: rs.push gauss(1.0, 0.5)
echo &"mean: {rs.mean:.5f} stdDev: {rs.standardDeviation:.5f}"

View file

@ -0,0 +1,4 @@
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 ());;

View file

@ -0,0 +1,18 @@
bundle Default {
class RandomNumbers {
function : Main(args : String[]) ~ Nil {
rands := Float->New[1000];
for(i := 0; i < rands->Size(); i += 1;) {
rands[i] := 1.0 + 0.5 * RandomNormal();
};
each(i : rands) {
rands[i]->PrintLine();
};
}
function : native : RandomNormal() ~ Float {
return (2 * Float->Pi() * Float->Random())->Cos() * (-2 * (Float->Random()->Log()))->SquareRoot();
}
}
}

View file

@ -0,0 +1,3 @@
p = normrnd(1.0, 0.5, 1000, 1);
disp(mean(p));
disp(sqrt(sum((p - mean(p)).^2)/numel(p)));

View file

@ -0,0 +1,42 @@
/*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*/
If n==''|n==',' Then
n=1000 /* N is the size of the array. */
If seed\=='' Then
Call random,,seed /* use seed for repeatable RANDOM#*/
mean=1 /* desired new mean (arith. avg.) */
sd=1/2 /* desired new standard deviation.*/
Do g=1 For n /* generate N uniform random nums.*/
n.g=random(0,1e5)/1e5 /* REXX gens uniform rand integers*/
End
Say ' old mean=' mean()
Say 'old standard deviation=' stddev()
Say
Do j=1 To n-1 By 2
m=j+1
/*use Box-Muller method */
_=sd*RxCalcPower(-2*RxCalcLog(n.j),.5)*RxCalcCos(2*pi*n.m,,'R')+mean
n.m=sd*RxCalcpower(-2*RxCalcLog(n.j),.5)*RxCalcSin(2*pi*n.m,,'R')+,
mean /* rand # must be 0???1. */
n.j=_
End /* j */
Say ' new mean=' mean()
Say 'new standard deviation=' stddev()
Exit
mean:
_=0
Do k=1 For n
_=_+n.k
End
Return _/n
stddev:
_avg=mean()
_=0
Do k=1 For n
_=_+(n.k-_avg)**2
End
Return RxCalcPower(_/n,.5)
:: requires rxmath library

View file

@ -0,0 +1,46 @@
/*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*/
If n==''|n==',' Then
n=1000 /* N is the size of the array. */
If seed\=='' Then
Call random,,seed /* use seed for repeatable RANDOM#*/
mean=1 /* desired new mean (arith. avg.) */
sd=1/2 /* desired new standard deviation.*/
Do g=1 For n /* generate N uniform random nums.*/
n.g=random(0,1e5)/1e5 /* REXX gens uniform rand integers*/
End
Say ' old mean=' mean()
Say 'old standard deviation=' stddev()
Say
Do j=1 To n-1 By 2
m=j+1
/*use Box-Muller method */
_=sd*sqrt(-2*ln(n.j))*cos(2*pi*n.m)+mean
n.m=sd*sqrt(-2*ln(n.j))*sin(2*pi*n.m)+mean
n.j=_
End
Say ' new mean=' mean()
Say 'new standard deviation=' stddev()
Exit
mean:
_=0
Do k=1 For n
_=_+n.k
End
Return _/n
stddev:
_avg=mean()
_=0
Do k=1 For n
_=_+(n.k-_avg)**2
End
Return sqrt(_/n)
sqrt: Return RxCalcSqrt(arg(1))
ln: Return RxCalcLog(arg(1))
cos: Return RxCalcCos(arg(1),,'R')
sin: Return RxCalcSin(arg(1),,'R')
:: requires rxmath library

View file

@ -0,0 +1,6 @@
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*u2) \\ 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)

View file

@ -0,0 +1,11 @@
function random() {
return mt_rand() / mt_getrandmax();
}
$pi = pi(); // Set PI
$a = array();
for ($i = 0; $i < 1000; $i++) {
$a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);
}

View file

@ -0,0 +1,21 @@
/* CONVERTED FROM WIKI FORTRAN */
Normal_Random: procedure options (main);
declare (array(1000), pi, temp,
mean initial (1.0), sd initial (0.5)) float (18);
declare (i, n) fixed binary;
n = hbound(array, 1);
pi = 4.0*ATAN(1.0);
array = random(); /* Uniform distribution */
/* Now convert to normal distribution */
DO i = 1 to n-1 by 2;
temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean;
array(i+1) = sd * SQRT(-2.0*LOG(array(i))) * SIN(2*pi*array(i+1)) + mean;
array(i) = temp;
END;
/* Check mean and standard deviation */
mean = SUM(array)/n;
sd = SQRT(SUM((array - mean)**2)/n);
put skip edit ( "Mean = ", mean ) (a, F(18,16) );
put skip edit ( "Standard Deviation = ", sd) (a, F(18,16));
END Normal_Random;

Some files were not shown because too many files have changed in this diff Show more