# target probability distribution def target_cdf(x, *args): return sum([a * x**(i + 1) for i, a in enumerate(alpha)]) # distribution for x^n def cdf(y, n): return x**n # inverse for the distribution x^n def inv_cdf(y, n): return y**(1.0 / n) # simulate and compare sim_components = [ Simulation(RVContinuous(support=[0.0, 1.0], cdf=cdf, n=i + 1), algorithm='inverse', inv_cdf=inv_cdf) for i in range(degree) ] rv = RVContinuous(support=[0.0, 1.0], cdf=target_cdf) sim = Simulation(target_rv=rv, algorithm='composition', sim_components=sim_components, probabilties=alpha) sim.generate(sample_size) sim.compare(file_path='../images/p8c_{}_{}.png'.format(degree, sample_size)) print('The generated probability weights are:\n{}'.format(alpha))
import numpy as np from simulate import RVContinuous, Simulation # a useful constant c = 1.0 - np.exp(-0.05) # target probability distribution def target_cdf(x): return (1.0 - np.exp(-x)) / c # inverse of the target distribution def inv_cdf(y): return -np.log(1.0 - c * y) # simulate and compare rv = RVContinuous(support=[0.0, 0.05], cdf=target_cdf) sim = Simulation(target_rv=rv, algorithm='inverse', inv_cdf=inv_cdf) sim.generate(1000) sim.compare(file_path='../images/p6.png') print('simulated mean = {:.4f}\nexact mean = {:.4f}'.format( sim.mean, sim.rv.mean))