rand / rnd / get|set_rand
| Definition: |
atom res = rand(atom range)
-- or -- integer res = rand_range(integer lo, hi) -- or -- atom res = rnd() -- or -- atom seed = get_rand() -- or -- set_rand(atom seed) |
| Description: |
rand() returns a random integer from 1 to range inclusive. rand_range() returns a random integer from lo to hi inclusive. rnd() returns a random floating point number in the range 0.0 to 1.0 inclusive. get_rand() obtains the current random number generator seed. set_rand() sets the current random number generator seed. |
| pwa/p2js: | Supported. |
| Comments: |
The rand() function may be applied to an atom or sq_rand() to all elements
of a sequence. The rules for sequence operations apply. The range parameter may be from 1 to the largest possible machine_word()-sized unsigned native integer, ie #FFFF_FFFF on 32 bit and #FFFF_FFFF_FFFF_FFFF on 64 bit. You can specify -1 to achieve that in a machine_word()-independent fashion, whereas a value of 0 in range triggers a fatal error, and as usual should range [potentially] exceed the 31/63 bit integer limit, the result should be stored in an atom variable, though in most cases an integer is fine and in fact probably better. In stark contrast to the usual way arguments are handled, all negative integers in the range parameter are treated as unsigned. This has turned out to be quite handy in a few cases (eg websockets), and only happens because of the low-level way it is implemented, specifically builtins\VM\pRand.e deliberately uses a jbe rather than a jle. Also note that any fractional part of range is completely ignored. Use set_rand() to get a repeatable series of random numbers on subsequent calls to rand()/rnd() (see technicalia). |
| Example: |
?rand(10) -- any number between 1 and 10 inclusive. ?rnd() -- any number bwtween 0.0 and 1.0 inclusive. set_rand(1001) ?rnd() -- 0.4817850515 ?rand(10) -- 4 ?get_rand() -- 914554926 ?rand(10) -- 9 ?rand(10) -- 1 set_rand(914554926) ?rand(10) -- 9 ?rand(10) -- 1 |
| Implementation: |
rand(), set_rand(): see :%opRand, :%opSetRand in builtins\VM\pRand.e (an autoinclude). get_rand(), rnd(): see builtins\prnd.e (an autoinclude). |