Random function in awk like in bash

0

How can I random in awk. In bash is:

echo $((RANDOM%(32-12+1)+12))

Is there function in awk, which gives the same result?

diego9403

Posted 2015-09-01T07:37:26.703

Reputation: 807

Answers

0

Yes, it is called rand(), the manual states:

rand()

Returns a random number N, between 0 and 1, such that 0 ≤ N < 1.

However, be careful of the following caveat:

CAUTION: In most awk implementations, including gawk, rand() starts generating numbers from the same starting number, or seed, each time you run awk. Thus, a program generates the same results each time you run it. The numbers are random within one awk run but predictable from run to run. This is convenient for debugging, but if you want a program to do different things each time it is used, you must change the seed to a value that is different in each run. To do this, use srand().

The manual once again states:

srand([expr])

Uses expr as a new seed for the random number generator. If no expr is provided, the time of day is used. The return value is the previous seed for the random number generator.

Edit:

To answer your question, the second link above gives nearly the solution to your query. You can modify it as:

  function randint(n,m)
  {
       return int(n+ (n-m) * rand())
  }

MariusMatutiae

Posted 2015-09-01T07:37:26.703

Reputation: 41 321

How can I run rand() with interval (for example from 10 to 100)? rand()*(100-99+1)+99
is correct?

  • instead of % in bash?
  • < – diego9403 – 2015-09-01T07:54:57.783

@diego9403 Pls see my edit. – MariusMatutiae – 2015-09-01T07:58:22.497