practice – Problem 3
Copyright By PowCoder代写 加微信 powcoder
import numpy as np
from scipy.stats import expon, uniform
## record your uni here
Problem 3 (25 points)¶
Suppose we want to sample from the distribution with the cdf:
$$F(x) = 1 – \exp(-\sqrt{x})$$Write a function inverse_transform() that samples from this distribution, and calculate the expected value of this distribution using $10,000$ samples.
np.random.seed(42)
n = 10_000
## 1 – \exp(-sqrt(x)) = u
## -sqrt(x) = log(1 – u)
## sqrt(x) = -log(1-u)
## x = log(1-u)**2
def inverse_transform():
U = uniform.rvs()
return np.log(1-U)**2
X = [inverse_transform() for i in range(0, n)]
print(np.mean(X))
1.904873792779115
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com