4

Is it possible to configure internal sampling algorithm of the random module in Python to change default of choice and randint sampling from normal to some other distribution for the duration of the execution of the program (for example to tinker with seed or state), but to then just use randint and choice functions?

For example, I would like some left skewed sampling.

If so, would you please advise how.

3
  • Are you aware that the random module has other distributions - triangular, Gaussian, and so on? ( link ) Or do you want some way to do that without using those? Commented Feb 2, 2016 at 16:25
  • I am aware. I am just looking for the way to re-use API calls choice and choice by re-configuring the default normal sampling. Commented Feb 2, 2016 at 16:27
  • The default distribution is not normal (Gaussian), but uniform. Commented Jul 25, 2017 at 12:26

1 Answer 1

4

The numpy library provides a lot of different distributions, and the random library provides a few too

This sample implementation of random suggests that exactly what you're asking cannot be done. Methods like choice call random.random(), by

def choice(self, seq): """Choose a random element from a non-empty sequence.""" return seq[int(self.random() * len(seq))] 

and random is only dependent on the seed. Manipulating the seed to change the distribution type would be quite convoluted, and surely violate the the randomness guarantees.

If you really wanted a module-wide change in default behaviour, you could modify __builtin__ or hack into the module attributes, but it seems much more direct to

from numpy.random import beta from random import gauss def choice(seq): return seq[int(beta() * len(seq))] 

or whenever needed, or put in a central location. I would also point you to a note in the random modules documentation

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the following methods: random(), seed(), getstate(), and setstate(). Optionally, implement a getrandbits() method so that randrange() can cover arbitrarily large ranges.

Introducing a BetaRandom class, e.g., would be trivial this way a much more maintainable, imo, than changing the reliable behaviour of the built in class (which may be possible through enough introspection and hacking)


I would also note that numpy's setstate is not what you want

* stole a link from comment by TessellatingHeckler

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, en_Knight. How would I do randint with custom distribution in numpy?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.