How the shell script gets the random number random

Source: Internet
Author: User
Tags rand random seed

The method of random number provided by C Srand and Rand, the former is to give the latter set of random number seed seeds.

int rnd_num = 0;

Srand (seed); Time (NULL) usually used to make seeds

Rnd_num = rand (); Generate random numbers

Methods of producing seeds:

1. Use Date Time

Time as a seed is very simple, take the current date and time, but there is a trap: When multiple machines concurrent execution produces random numbers, the probability of the same random number is very high. Not recommended in this way

2. Use of $random

Need system support, detected by ECHO, print out a random number to prove that the current environment supports $RANDOM, or NULL does not support:

~ @ubuntu: ~$ echo $RANDOM

2517

3. Using/dev/urandom + TR

TR-CD 0-9 </dev/urandom | Head-c 8//8-bit random seed

This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/OS/Linux/

Using awk to generate random numbers after the seed is taken, here is a simple function rnd2, and the arguments $ and $ are the ranges that generate random numbers, respectively.

#$1 $ is a value range
function Rnd2 () {
  If [-Z "$RANDOM"]; then
    seed= ' tr-cd 0-9 </dev/urandom | head-c 8 '
  E LSE
    seed= $RANDOM
  fi
    
  rnd_num= ' echo $SEED $ $2|awk ' {srand ($);p rintf '%d ', rand () *10000% ($3-$2) +$2} '
  echo $RND _num
}

Write a loop, loop 30 times, after the implementation of the results of the following figure:

Author: Cnblogs Lazy Man

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.