CS计算机代考程序代写 In [2]:

In [2]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Let’s assume that we are interested in constructing use sample mean to estimate the population mean of an exponential distribution with $\lambda=4$.

Let’s use np.random.exponential(scale, size=None) to get the job done. Here, scale should be equal to $\frac{1}{\lambda}$
Method 1: Increase sample size
In [3]:
def simulation_exp(n):
lm=4
samples=np.random.exponential(1/lm,n)
return np.mean(samples)

exp_means_40=[simulation_exp(40) for i in range(1000)]
exp_means_200=[simulation_exp(200) for i in range(1000)]

plt.hist(np.array(exp_means_40),bins=30,density=True,label=”s=40″,alpha=0.5)
plt.hist(np.array(exp_means_200),bins=30,density=True,label=”s=200″,alpha=0.5)
plt.legend()
plt.show()

Method 2: sample from a different distribution
Let’s assume that another person told you that a normal distribution of mean=0.25 and variance=0.01 can be a good candidate. You decide to give it a shot and sample 40 from normal distribution instead.
Let’s use np.random.normal(loc=0.0, scale=1.0, size=None) to get the job done. Here, loc is the population mean, while scale is the population standard deviation.
In [6]:
def simulation_exp(n):
lm=4
samples=np.random.exponential(1/lm,n)
return np.mean(samples)

def simulation_norm(n):

samples=np.random.normal(0.25, 0.0001**0.5,n)
return np.mean(samples)

exp_means_exp=[simulation_exp(40) for i in range(1000)]
exp_means_norm=[simulation_norm(40) for i in range(1000)]

plt.hist(np.array(exp_means_exp),bins=30,density=True,label=”exp”,alpha=0.5)
plt.hist(np.array(exp_means_norm),bins=30,density=True,label=”norm”,alpha=0.5)
plt.legend()
plt.show()

We can see that we again have a smaller variance. In addition, both plots centers around the same value. Why is the case? Let’s assue E(x)=
In [9]:
%%timeit
exp_means_exp=[simulation_exp(40) for i in range(1000)]

8.87 ms ± 119 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [10]:
%%timeit
exp_means_norm=[simulation_norm(40) for i in range(1000)]

9.01 ms ± 68.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [0]: