[Tutor] How to test function using random.randint()?

Steven D'Aprano steve at pearwood.info
Sat Mar 19 09:03:56 EDT 2016


On Sat, Mar 19, 2016 at 04:05:58PM +1100, Ben Finney wrote:

>     import random
> 
>     def roll_die(num_sides, rng=None):
>         """ Return a result from a random die of `num_sides` sides.
> 
>             :param num_sides: The number of sides on the die.
>             :param rng: An instance of `random.Random`, the random
>                 number generator to use.
>                 Default: the `random.random` instance.
>             :return: The integer result from the die roll.
> 
>             The die is defined to have equal-probability faces, numbered
>             from 1 to `num_sides`.
> 
>             """
>         if rng is None:
>             rng = random.random

Typo: you want rng = random.randint.

>         result = rng.randint(1, num_sides)

And here you just want result = rng(1, num_sides). Otherwise you're 
trying to call random.randint.randint.



> > And I do not see how I can test for an appropriate "randomness" to the
> > numbers the function generates without to a lot of iterations,
> 
> That's the thing about randomness. By definition, you can't determine it
> :-) 

http://dilbert.com/strip/2001-10-25


But all joking aside, Python's pseudo-random number generator is one of 
the best in the world, the Mersenne Twister. For non-cryptographical 
purposes, it is as random as anything you are likely to need.

https://en.wikipedia.org/wiki/Mersenne_Twister

It passes all, or most, of the stringent "Diehard" and other tests for 
randomness:

https://en.wikipedia.org/wiki/Diehard_tests



-- 
Steve


More information about the Tutor mailing list