Difference between revisions of "Generate a random number"

From CodeCodex

(Erlang)
(Implementations)
Line 78: Line 78:
 
<pre>
 
<pre>
 
  rand(m, n)
 
  rand(m, n)
 +
</pre>
 +
 +
=== Tcl ===
 +
<pre class="tcl">
 +
# Random integer between 0..10
 +
set n [expr {int(10*rand())}]
 
</pre>
 
</pre>
  

Revision as of 18:39, 15 February 2011

Implementations

bash

print a random integer

val="$RANDOM"
echo $RANDOM

C

#include <stdlib.h>
#include <time.h>

srand(time(NULL)); /* initialize random seed */
rand();            /* Generate a random int from 0 to RAND_MAX */
rand() % 100;      /* Generate a random int from 0 to 99 */
rand() % 100 + 1;  /* Generate a random int from 1 to 100 */
rand() % 30 + 100; /* Generate a random int from 100 to 129 */

Erlang

% Generate a random real number between 0.0 and 1.0
F = random:uniform().

% Generate a random integer between 1 and 100
I = random:uniform(100).

Java

Generate a random int from 0 to n

 java.util.Random rand = new java.util.Random();
 i = rand.nextInt(n+1);

OCaml

# Random.int 15;;
- : int = 9

Perl

rand; # Generate a random real number between 0 and 1
rand(100); # Generate a random real number between 0 and 100
int(rand(100)); # Generate a random integer between 0 and 99

PHP

  $int = rand(99);
  //$int is a random number between 0 and 99 inclusive

Python

import random

# Generate a random integer between 0 and n, exclusive
random.randrange(n)

# Generate a random integer between m and n, inclusive
random.randrange(m, n + 1)

Ruby

# Generate a random real number between 0 and 1
x = rand      # 0.0 <= x < 1.0

# Generate a random integer between 0 and n, exclusive
i = rand(n)   # 0 <= i < n

Seed7

Generate a random integer between m and n inclusive

 rand(m, n)

Tcl

# Random integer between 0..10
set n [expr {int(10*rand())}]

Zsh

# Generate pseudo-random number between 0 and 32767.
$RANDOM

# Generate pseudo-random number between 0 and 9.
$RANDOM % 10

# Or

typeset -F SECONDS
typeset -F6 SECONDS
${SECONDS#*.} % 10

# Generate pseudo-random number between 0 and 1 using module of mathematical functions.
zmodload -i zsh/mathfunc
rand48()

# Or using Cliff random number generator
# http://mathworld.wolfram.com/CliffRandomNumberGenerator.html

function cliff_rand {
	zmodload zsh/mathfunc

	seed=0.1

	(( seed = 100 * log(seed) ))

	(( number = fmod(seed, 1.0) ))
	
	(( cliff_number = fabs(number) ))

	print $cliff_number
}