| Difference Topic NumberRandomNumber (r1.1 - 24 Aug 2004 - BrentAFulgham) |
| Added: | |||||
| > > |
%META:TOPICINFO{author="BrentAFulgham" date="1093387080" format="1.0" version="1.1"}%
Generating Random NumbersProblemYou want a random number from a given range. For example, you wish to randomly select one element from an array, simulate rolling a die in a game of chance, or generate a random password.SolutionUserandom:uniform function from the standard Erlang distribution. It has two forms: (1) a no-argument version that returns a random float value in the range of 0.0 to 1.0, and (2) an version that takes a single integer (N) and returns a random integer in the range of 1 to N.
DiscussionThis code generates and prints a random integer between 25 and 75, inclusive:
random:uniform function. This means we really want a random number between 1 and 51, so we give the random:uniform function the argument 51 (since the generated number is always from 1 to N).
The canonical application for this kind of number generation is the random selection of an element from a vector:
See AlsoErlang Random Number module documentationComments-- BrentAFulgham - 24 Aug 2004 %META:FORM{name="CookbookForm"}% %META:FIELD{name="TopicType" title="TopicType" value="Recipe"}% %META:FIELD{name="ParentTopic" title="ParentTopic" value="NumberRecipes"}% %META:FIELD{name="TopicOrder" title="TopicOrder" value="070"}% | ||||