Skip to main content

Exercises 5.8 Exercises

1. Exercise 5.1.

In the NSFG respondent file, the numfmhh column records the "number of family members in" each respondent’s household. We can use read_fem_resp to read the file, and query to select respondents who were 25 or older when they were interviewed.
Listing 5.8.1. Python Code
download("https://github.com/AllenDowney/ThinkStats/raw/v3/data/2002FemResp.dct")
download("https://github.com/AllenDowney/ThinkStats/raw/v3/data/2002FemResp.dat.gz")
Listing 5.8.2. Python Code
from nsfg import read_fem_resp

resp = read_fem_resp()
Listing 5.8.3. Python Code
older = resp.query("age >= 25")
num_family = older["numfmhh"]
Compute the Pmf of numfmhh for these older respondents and compare it with a Poisson distribution with the same mean. How well does the Poisson model fit the data?

2. Exercise 5.2.

Earlier in this chapter we saw that the time until the first goal in a hockey game follows an exponential distribution. If our model of goal-scoring is correct, a goal is equally likely at any time, regardless of how long it has been since the previous goal. And if that’s true, we expect the time between goals to follow an exponential distribution, too.
The following loop reads the hockey data again, computes the time between successive goals, if there is more than one in a game, and collects the inter-goal times in a list.
Listing 5.8.4. Python Code
filename = "nhl_2023_2024.hdf"

with pd.HDFStore(filename, "r") as store:
    keys = store.keys()
Listing 5.8.5. Python Code
intervals = []

for key in keys:
    times = pd.read_hdf(filename, key=key)
    if len(times) > 1:
        intervals.extend(times.diff().dropna())
Use exponential_cdf to compute the CDF of an exponential distribution with the same mean as the observed intervals and compare this model to the CDF of the data.

3. Exercise 5.3.

Is the distribution of human height more like a normal or a lognormal distribution? To find out, we can select height data from the BRFSS like this:
Listing 5.8.6. Python Code
$ adult_heights = brfss["htm3"].dropna()
m, s = np.mean(adult_heights), np.std(adult_heights)
m, s
(np.float64(168.82518961012298), np.float64(10.35264015645592))
Compute the CDF of these values and compare it to a normal distribution with the same mean and standard deviation. Then compute the logarithms of the heights and compute the distribution of the logarithms compared to a normal distribution. Based on a visual comparison, which model fits the data better?