Problem 648664 · easy · Level 06 Heuristics & Optimization

Fitting the Bag Weights

maximum likelihood · normal model · log-likelihood · standard deviation

A flour mill fills bags with a target weight of 500 g. The quality team models the weights as independent draws from a normal distribution with unknown mean \mu (mu) and standard deviation \sigma (sigma). The density of one weight x is

f(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\!\left(-\frac{(x - \mu)^2}{2\sigma^2}\right)

Write normal_fit(weights) that returns a tuple (mu, sigma, loglik): the values of mu and sigma that maximise the likelihood of the weights, and the log-likelihood (the sum of the natural logs of the densities) at those values.

The setup provides bag_weights(n, seed), which simulates n bag weights in grams.

Examples

Input:  weights = [498, 503, 501, 497, 506, 495]
Output: (500.0, 3.7416573867739413, -16.430803188073813)
Explanation: the mean is 500; the squared deviations add up to 84, and 84 / 6 = 14,
so sigma = sqrt(14) = 3.742. The six log densities add up to -16.43.

Input:  weights = [1.0, 3.0]
Output: (2.0, 1.0, -2.8378770664093453)

Constraints

  • 2 <= len(weights) <= 10**5, and the weights are not all equal
  • floats are compared with a tolerance of 1e-6

Goals

  • Find the maximum likelihood mean and standard deviation of a normal model
  • Compute the log-likelihood of the data at those values
  • Notice that maximum likelihood divides the squared deviations by n
Starting Python…