1

I am trying to generate a random number in Python according to a precise distribution that I define with a function f (theta) = 1 + alpha*cos(theta)²; the variable alpha is a constant.

Unfortunately I do not know how to do it because the different random functions all follow a pre-defined distribution (normal, uniform, binomial ...)

Have you got an idea?

A J
  • 3,970
  • 14
  • 38
  • 53
Zebub
  • 11
  • 3
  • 2
    What is the range of theta? – gmds Apr 17 '19 at 09:41
  • In general, you can subclass the `rv_continous` class from scipy.stats package. But your function doesn't obviously met conditions of either cumulative distribution function (cdf) or probability distribution function (pdf). To be a valid pdf function it should have AUC (area under the curve) equal 1, To be a valid cdf function it should be at least non-decreasing function. – bubble Apr 17 '19 at 09:48
  • @gmds theta is defined under 0 and pi – Zebub Apr 17 '19 at 10:04
  • Possible duplicate of [How to generate random numbers with predefined probability distribution?](https://stackoverflow.com/questions/51050658/how-to-generate-random-numbers-with-predefined-probability-distribution) – Peter O. Apr 25 '19 at 19:07
  • In addition to the duplicate question, see also my article on [sampling a number with an arbitrary distribution](https://peteroupc.github.io/randomfunc.html#Random_Numbers_from_an_Arbitrary_Distribution), which also includes Python sample code that implements this approach, notably the `numbers_from_pdf` method. – Peter O. Apr 25 '19 at 19:09

1 Answers1

0

Assuming the density function you have is proportional to a probability density function (PDF) you can use the rejection sampling method: Draw a number in a box until the box falls within the density function. In this case, the density function is 64/(99*math.pi) and its maximum value is 1+alpha.

For code that implements rejection sampling, see the following answer of mine:

Peter O.
  • 32,158
  • 14
  • 82
  • 96