I am a newbie to python, and I want to generate the identical PDF plots as shown below:
Here is my current version of implementation, which doesn't produce the same plots:
import random
import matplotlib.pyplot as plt
plt.figure('PDF for random.random()')
plt.title('PDF for random.random()')
plt.plot(random.random())
plt.figure('PDF for random.random() random.random()')
plt.title('PDF for random.random() random.random()')
plt.plot(random.random() random.random())
plt.figure('PDF for random.random() random.random() random.random()')
plt.title('PDF for random.random() random.random() random.random()')
plt.plot(random.random() random.random() random.random())
plt.show()
Where did I do it wrong?
CodePudding user response:
Calling random.random()
once simply returns a single number, you need to call it multiple times in order to get a good enough sample of the underlying distribution.
You can create a list with n
calls to random.random
by writing [random.random() for _ in range(n)]
.
Try this code:
import random
import matplotlib.pyplot as plt
sample_size = 10000
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3)
ax1.hist([random.random() for _ in range(sample_size)])
ax1.set_title('PDF for random.random()')
ax2.hist([random.random() random.random() for _ in range(sample_size)])
ax2.set_title('PDF for random.random() random.random()')
ax3.hist([random.random() random.random() random.random() for _ in range(sample_size)])
ax3.set_title('PDF for random.random() random.random() random.random()')
plt.show()
output image:
CodePudding user response:
For speed purposes, you could use numpy.random
which provides a