Given a probability distribution with probability density f(t) = 0.5sin(t) for t in [0,π], plot a graph of the probability density on the interval [0,π] and in the same figure make a histogram of 10^4 random independent draws. The answer should look like this:
So far I have figured out how to plot the pdf function by doing the following:
import numpy as np
import matplotlib.pyplot as plt
import math
# Define the probability distribution
def f(t):
return 0.5 * np.sin(t)
# Plot the probability density
t = np.linspace(0, math.pi, 10000)
pdf = f(t)
plt.plot(t, pdf, label='density')
plt.xlabel('value')
plt.ylabel('density / relative frequency')
plt.title('Visualisation of sine random variable')
plt.legend()
plt.grid(axis='y')
plt.show()
This gives me the blue line that I should have, but I dont know how to plot the histogram
I had a similar problem but with a exp(1/2) distibution on the interval [0;5.5]. There I did it like this:
import numpy as np
import matplotlib.pyplot as plt
import math
# Define exponential distribution
rate = 0.5
def pdf(x):
return rate*math.exp(-rate*x) #PDF = λe^(-λx), with λ the rate of the distribution
# Plot pdf
x = np.linspace(0, 5.5, 10000)
pdf = np.array([pdf(i) for i in x])
plt.plot(x, pdf, label='density')
# Create random variables
stochast = np.random.exponential(1/rate, size=10000)
# Make the histogram
plt.hist(stochast, bins=np.arange(0, max(stochast)+1, 0.2), density=True,
label='relative frequency 10^4 draws', edgecolor='black')
plt.xlabel('value')
plt.ylabel('density / relative frequency')
plt.title('Visualisation of a Exp(1/2) random variable')
plt.legend()
plt.xlim(0, 5.5)
plt.grid(axis='y')
plt.show()
Here I knew the rate λ of this exponential distribution which, after looking at wikipedia for a while, made it quite easy. But I don't know how to do this for the f(t) = 0.5sin(t) distribution.