Generate a random number

From CodeCodex

Implementations[edit]

bash[edit]

print a random integer

val="$RANDOM"
echo $RANDOM

C[edit]

#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[edit]

% 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[edit]

Generate a random int from 0 to n

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

OCaml[edit]

# Random.self_init();;
- : unit = ()
# Random.int 15;;
- : int = 9

Perl[edit]

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[edit]

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

Python[edit]

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[edit]

# 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[edit]

Generate a random integer between m and n inclusive

 rand(m, n)

Tcl[edit]

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

Zsh[edit]

# 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
}