Random number generator in arbitrary probability distribution fashion | Python3 program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver code ; Let us generate 10 random numbers accroding to given distribution
import random NEW_LINE def findCeil ( arr , r , l , h ) : NEW_LINE INDENT while ( l < h ) : NEW_LINE INDENT mid = l + ( ( h - l ) >> 1 ) ; NEW_LINE if r > arr [ mid ] : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid NEW_LINE DEDENT DEDENT if arr [ l ] >= r : NEW_LINE INDENT return l NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def myRand ( arr , freq , n ) : NEW_LINE INDENT prefix = [ 0 ] * n NEW_LINE prefix [ 0 ] = freq [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + freq [ i ] NEW_LINE DEDENT r = random . randint ( 0 , prefix [ n - 1 ] ) + 1 NEW_LINE indexc = findCeil ( prefix , r , 0 , n - 1 ) NEW_LINE return arr [ indexc ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE freq = [ 10 , 5 , 20 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT print ( myRand ( arr , freq , n ) ) NEW_LINE DEDENT