Cryptographically strong random numbers

Peter Pearson pkpearson at nowhere.invalid
Fri Oct 16 13:26:04 EDT 2015


On Sat, 17 Oct 2015 03:25:03 +1100, Steven D'Aprano <steve at pearwood.info> wrote:
[snip]
> randbelow(end):
>     return a random integer in the half-open interval 0...end
>     (including 0, excluding end)
>
> randint(start, end):
>     return a random integer in the closed interval start...end
>     (including both start and end)
>
> randrange([start=0,] end [, step=1]):
>     return a random integer in the half-open range(start, stop, step)

Having done quite a bit of serious crypto implementation over the past
25 years, I don't recall ever wanting anything like randrange, and if
I *did* need it, I'd probably build it inline from randbelow rather than
force some hapless future code maintainer to look up the specs on randrange.

My opinion, FWIW: I like randbelow, because in modern crypto one very
frequently works with integers in the range [0,M-1] for some large
modulus M, and there is a constant risk of asking for something in [0,M]
when one meant [0,M-1].  One can eliminate this risk, as randbelow does,
by building in the -1, which normally introduces a risk of making a
mistake that gives you [0,M-2], but the name "randbelow" seems like a
neat fix to that problem.

I can see the attraction of randint for programming languages that have
limited ranges of integers, since randint lets you specify the whole range
of positive integers without having to pass an argument that is outside
that range.  Take a moment to savor the joy of Python.

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list