RSS Subscription
Linux Howtos & Tutorials

Enter your email:

Delivered by


NOTE:New tutorials are from LinuxCareer.com

Poll

Do you own or wish to have iPhone?
 


Linux eBooks FREE Download
A guide to programming Linux kernel modules
Introduction to Linux - A Hands on Guide
A Newbie's Getting Started Guide to Linux

Linux from Scratch - Create Your Own Linux System - Free eBook

Linux: The Hacking Solution (v.3.0)

SQLite 3 with PHP Essential Training – Free Video Training Tutorials

This guide will introduce you to the world of GNU/Linux

The GNU/Linux Advanced Administration

A Complete Beginner's Manual for Ubuntu 10.04 (Lucid Lynx)

Advanced Bash-Scripting Guide

Set up, maintain, and secure a small office email server

Partner Linux Sites:
How-To.LinuxCareer.com
Jobs.LinuxCareer.com
TuxMachines
Monsterb
LinuxBloggers
AdamsInfo
LinuxScrew
All For Linux

Generate random numbers with $RANDOM

Question:
Hi, How can I generate random number, preferably integer to be used within my bash script. Is there also a way to test whether random numbers are generated properly?
Answer:
The easiest way on how to generate random number in bash is to use bash's $RANDOM function. $RANDOM is an internal Bash function that returns an integer in the range 0 - 32767.
For example the following line will generate 10 random integers in range from 1 to 10:

NOTE: +1 will simply shift result numbers from range 0 - 9 to 1 -10

$ for i in $( seq 1 10 ); do echo int $i = $[ ( $RANDOM % 10 ) +1 ]; done

Very basic test can be performed to see whether $RANDOM function creates a uniformly distributed random numbers. For this we would need more than 10 randomly generated numbers in order to see uniform distribution.

Therefore, we can create 100 000 random numbers from range 0 - 10 with modulus %11 and store them into file random.txt.

$ for i in $( seq 1 100000 ); do echo $[ ( $RANDOM % 11 ) ] >> random.txt; done

Using octave we can than generate a histogram with 11 bins to see whether bash $RANDOM internal function created uniformly distributed random numbers :

$ octave
octave:1> rand=csvread('~/random.txt');
octave:2> hist(rand,nbins=11);

Random number bash test

The more numbers we generate, the more uniform number distribution we should see.
Linux questions and answers

Share this linux post:

Submit Generate random numbers with $RANDOM in Delicious Submit Generate random numbers with $RANDOM in Digg Submit Generate random numbers with $RANDOM in FaceBook Submit Generate random numbers with $RANDOM in Google Bookmarks Submit Generate random numbers with $RANDOM in Stumbleupon Submit Generate random numbers with $RANDOM in Technorati Submit Generate random numbers with $RANDOM in Twitter
 
Comments for this page are closed !!!
Please visit our new Linux Forum for additional help or discussion.


Linux eBooks FREE Download