mod on %RANDOM


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting mod on %RANDOM
# 1  
Old 12-28-2008
Hammer & Screwdriver mod on %RANDOM

I use %random to generate random number but i want to mod it so i get random number below 50 only in ksh script
how can i do it
x=random % 50
doesn't work

help is appreciated.


Is there any other way i get generate random number below 50 in ksh.any other function.
Plz provide an example

i am fairly new to unix
thanks
# 2  
Old 12-28-2008
try
x= `echo $RANDOM %50 | bc`
# 3  
Old 12-28-2008
Code:
$ m=50  
$ for i in {1..20};do print $(($RANDOM%$m+1));done      
4
31
11
4
50
16
12
6
44
39
40
26
23
42
41
8
44
20
47
36

# 4  
Old 12-29-2008
When you use a modulus operation you are selecting information from the low order bits of a number and discarding information from the high order bits.

"these bits should be extracted from the most significant (left-hand) part
of the computer word, since the least significant bits produced by many random number generators are not sufficiently random."

and

"The least significant (right-hand) digits of X are not very random, so decisions based on the number X should always be influenced primarily by the most significant digits. It is generally best to think of X as a random fraction X/m between 0 and 1, that is, to visualize X with a decimal point at its left, rather than to regard X as a random integer between 0 and m - 1. To compute a random integer between 0 and k - 1, one should multiply by k and truncate the result."
both from The Art of Computer Programming, Volume 2 Seminumerical Algorithms by Donald Knuth

While neither is perfect, assuming that 0 <= RANDOM <= 32767,
((myrandom = RANDOM * 50 / 32768))
will behave better than
((myrandom = RANDOM % 50))
# 5  
Old 12-29-2008
Thank you for elaborating further, Perderabo!
Login or Register to Ask a Question

Previous Thread | Next Thread

3 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Need to generate a file with random data. /dev/[u]random doesn't exist.

Need to use dd to generate a large file from a sample file of random data. This is because I don't have /dev/urandom. I create a named pipe then: dd if=mynamed.fifo do=myfile.fifo bs=1024 count=1024 but when I cat a file to the fifo that's 1024 random bytes: cat randomfile.txt >... (7 Replies)
Discussion started by: Devyn
7 Replies

2. Ubuntu

expect script for random password and random commands

Hi I am new to expect. Please if any one can help on my issue its really appreciable. here is my issue: I want expect script for random passwords and random commands generation. please can anyone help me? Many Thanks in advance (0 Replies)
Discussion started by: vanid
0 Replies

3. Programming

Mod

I try to use mod(a,b) in a program but i cant Please help me (2 Replies)
Discussion started by: iwbasts
2 Replies
Login or Register to Ask a Question