From e90c0b8c75d4628de8be8e4be780a5c902f700aa Mon Sep 17 00:00:00 2001 From: Doug Coleman Date: Wed, 20 Jun 2012 21:04:57 -0700 Subject: [PATCH] random: Add random-integers and random-units words. --- basis/random/random-docs.factor | 32 +++++++++++++++++++++++++++++++- basis/random/random.factor | 8 +++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/basis/random/random-docs.factor b/basis/random/random-docs.factor index 20d5dc0214..ae26d74ff1 100644 --- a/basis/random/random-docs.factor +++ b/basis/random/random-docs.factor @@ -1,4 +1,4 @@ -USING: help.markup help.syntax math kernel sequences ; +USING: help.markup help.syntax math kernel sequences arrays ; IN: random HELP: seed-random @@ -46,6 +46,34 @@ HELP: random-bytes } } ; +HELP: random-integers +{ $values { "length" integer } { "n" integer } { "sequence" array } } +{ $description "Outputs an array with " { $snippet "length" } " random integers from [0,n)." } +{ $examples + { $unchecked-example "USING: prettyprint random ;" + "10 100 random-integers ." + "{ 32 62 71 89 54 12 57 57 10 19 }" + } +} ; + +HELP: random-units +{ $values { "length" integer } { "sequence" array } } +{ $description "Outputs an array with " { $snippet "length" } " random uniform floats from [0,1]." } +{ $examples + { $unchecked-example "USING: prettyprint random ;" + "7 random-units ." + "{ + 0.1881956429982787 + 0.9063571897519639 + 0.9550470241550406 + 0.6289397941552234 + 0.9441213853903183 + 0.7673290082934152 + 0.573743749061385 +}" + } +} ; + HELP: random-bits { $values { "numbits" integer } { "r" "a random integer" } } { $description "Outputs an random integer n bits in length." } ; @@ -130,6 +158,8 @@ $nl { $subsections sample } "Deleting a random element from a sequence:" { $subsections delete-random } +"Sequences of random numbers:" +{ $subsections random-bytes random-integers random-units } "Random numbers with " { $snippet "n" } " bits:" { $subsections random-bits diff --git a/basis/random/random.factor b/basis/random/random.factor index a4ec1ea090..53a87cc283 100644 --- a/basis/random/random.factor +++ b/basis/random/random.factor @@ -101,11 +101,17 @@ ERROR: too-many-samples seq n ; 4 random-bytes uint deref >float 2.0 32 ^ * + [ over - 2.0 -64 ^ * ] dip - * + ; inline + * + ; inline : random-unit ( -- n ) 0.0 1.0 uniform-random-float ; inline +: random-units ( length -- sequence ) + [ random-unit ] replicate ; + +: random-integers ( length n -- sequence ) + '[ _ random ] replicate ; + : (cos-random-float) ( -- n ) 0. 2pi uniform-random-float cos ;