[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: how to generate random negative numbers



In <[🔎] 60f50c4a0908121232p4635c385m1d9e0d9b2d9352fd@mail.gmail.com>, Soren Orel 
wrote:
>user@debian:~$ $[ ($RANDOM % 30 ) -30 ]
>bash: -26: command not found
>user@debian:~$ $[ ($RANDOM % 30 ) -30 ]
>bash: -3: command not found
>user@debian:~$ $[ ($RANDOM % 30 ) -30 ]
>bash: -23: command not found
>user@debian:~$ $[ ($RANDOM % 30 ) -30 ]
>bash: -2: command not found
>user@debian:~$ $[ ($RANDOM % 30 ) -30 ]
>bash: -29: command not found

[snip]

>it still doesn't work, and it gives only negative numbers when using e.g.:
>30....-30

You misunderstand how this works.  The numbers you type above are not the 
range of the results.

$RANDOM gives a random number.  It has a relatively large range, I think 
0-32K maybe even larger.

The "% 30" divides the result by 30 and takes the remainder.  So, no matter 
what the input, the output will be in the range 0..29.

The "- 30" subtracts 30 from the result.  Given in input domain of 0..29, 
the output range will be -30..-1.

Examples:
echo $((RANDOM % 6 + 1)) # Rolls a "normal" die[1].
echo $((RANDOM % 5 - 1)) # -2..2
echo $((RANDOM % 201 - 100)) # Percentage change in my stock value today.
-- 
Boyd Stephen Smith Jr.           	 ,= ,-_-. =.
bss@iguanasuicide.net            	((_/)o o(\_))
ICQ: 514984 YM/AIM: DaTwinkDaddy 	 `-'(. .)`-'
http://iguanasuicide.net/        	     \_/

[1] But not a fair one.  If the $RANDOM function is completely random, so 
that over the "long tail" all values show up with the same frequency, the 
die will be slightly biased low.

Attachment: signature.asc
Description: This is a digitally signed message part.


Reply to: