Python Forum
Optimisation the rejection method of generating random variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Optimisation the rejection method of generating random variables
#1
Hello, I have a problem with optimisation the rejection method of generating continuous random variables. I've got a density: f(x) = 3/2 (1-x^2). Here's my code:

import random
import matplotlib.pyplot as plt
import numpy  as np
import time
import scipy.stats as ss

a=0   # xmin
b=1   # xmax

m=3/2 # ymax
variables = [] #list for variables

def f(x):
    return 3/2 * (1 - x**2)  #probability density function

reject = 0   # number of rejections
start = time.time()
while len(variables) < 100000:  #I want to generate 100 000 variables
    u1 = random.uniform(a,b)
    u2 = random.uniform(0,m)

    if u2 <= f(u1):
        variables.append(u1)
    else:
        reject +=1
end = time.time()

print("Time: ", end-start)
print("Rejection: ", reject)
x = np.linspace(a,b,1000)
plt.hist(variables,50, density=1)
plt.plot(x, f(x))
plt.show()

ss.probplot(variables, plot=plt)
plt.show()
My first question: Is my probability plot made properly? And the second, what is in the title. How to optimise that method? I would like to get some advice to optimise the code. Now that code take about 0.5 second and there are about 50 000 rejections. Is it possible to reduce the time and number of rejections? If it's needed I can optimise using different method of generating variables. Thanks in advance!
Reply
#2
I am not sure about the method (area under the curve of the pdf should be equal 1, and what about its value in your case?), but you can increase speed of computations, if you avoid Python loops. In your case, you can do it as follows:

import numpy as np

# --- Instead of while loop:
# start = ... time measurement started .... 
u1 = np.random.uniform(a, b, size=100000)
u2 = np.random.uniform(0, m, size=100000)
var_inds = u2 <= f(u1)
variables = u1[var_inds]
rejected = (~var_inds).sum() 
#end = ... time measurement ended
# some plotting stuff... 
Reply
#3
I would say use array instead of list to improve the efficiency of the code, its about 3 times faster...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  About the random number generating shang2019 2 2,529 Jan-13-2019, 02:40 AM
Last Post: gitiya
  Dice and Random Variables isuckatcoding 3 55,827 Dec-04-2017, 05:00 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020