Difference between revisions of "Rnd"
m (→Arguments) |
(expanded usage notes and added example) |
||
Line 15: | Line 15: | ||
of random numbers. If you never specify a seed, then it is | of random numbers. If you never specify a seed, then it is | ||
initialized automatically, generating a unique sequence on each run. | initialized automatically, generating a unique sequence on each run. | ||
+ | |||
+ | Since the result of <c>rnd</c> is between 0 and 1, if you multiply it by some other number ''n'', you get a random value between 0 and ''n''. This is often combined with [[floor]] or [[ceil]] to get a whole number in the range 0 to ''n''-1 or in the range 1 to ''n'', respectively. | ||
+ | |||
+ | |||
+ | == Example == | ||
+ | |||
+ | The following example simulates rolling three ordinary 6-sided dice, generating numbers from 1 to 6 inclusive. `rnd * 6` returns a floating-point number between 0 and 6, and taking [[ceil]] of that rounds it up to a whole number from 1 to 6. | ||
+ | |||
+ | <ms>sum = 0 | ||
+ | for i in range(1, 3) | ||
+ | roll = ceil(rnd * 6) | ||
+ | print "You rolled a " + roll | ||
+ | sum = sum + roll | ||
+ | end for | ||
+ | print "Total: " + sum</ms> | ||
[[Category:Intrinsic Functions]] | [[Category:Intrinsic Functions]] | ||
[[Category:Numeric Functions]] | [[Category:Numeric Functions]] |
Latest revision as of 20:15, 15 December 2020
rnd
generates a pseudorandom number between 0 and 1 (including 0 but not including 1).
Arguments
Parameter Name | Type | Meaning |
---|---|---|
seed | number, optional | if given, reset the sequence with this value. |
Usage Notes
If given a seed, then the generator is reset with that seed value, allowing you to create repeatable sequences of random numbers. If you never specify a seed, then it is initialized automatically, generating a unique sequence on each run.
Since the result of rnd
is between 0 and 1, if you multiply it by some other number n, you get a random value between 0 and n. This is often combined with floor or ceil to get a whole number in the range 0 to n-1 or in the range 1 to n, respectively.
Example
The following example simulates rolling three ordinary 6-sided dice, generating numbers from 1 to 6 inclusive. `rnd * 6` returns a floating-point number between 0 and 6, and taking ceil of that rounds it up to a whole number from 1 to 6.
sum = 0
for i in range(1, 3)
roll = ceil(rnd * 6)
print "You rolled a " + roll
sum = sum + roll
end for
print "Total: " + sum