Continuous random variables — exam-style exercises with the cafeteria microwave, a density with a constant and three ways to pay (and the uniroot that could not find the median)
In a practice exam in class, R answered with an error when I asked for the median and I lost ten minutes changing an interval that was not to blame. I had written uniroot(F, c(0, 1)) and the message said “f() values at end points not of opposite sign”. I tried another interval, then another, and nothing: ten minutes out of forty. The problem was not the interval: I was asking where the distribution function is 0, instead of where it is 0.5. A - 0.5 was missing. That part was worth one mark and I lost all of it.
These exercises follow the format of the ME1 EC1: one context per exercise, linked parts with their marks, calculations by hand and calculations with R. They are original, with the cafeteria microwave from the continuous random variables theory, and they go over what comes up most: a density with a constant, the exponential and the gamma, and a mixture of times with total probability and Bayes. If a proof gets stuck, you have them step by step in the topic’s proofs.
Table of Contents
How to use this article
- Do the exercises with the exam in mind. In the ME1 EC1 you have 4 hours for 50 marks, with RStudio and the data open. These three exercises add up to 40 marks plus a 2.5 bonus: give them about 3 hours and 10 minutes.
- Paper for what is proved, R for what is computed. Calculations to 2 decimals, as the exam asks. Whatever you do in R, save it in a script: at the end of the exam you have to upload the
.Rfile with the code for each exercise. - Mark it with the criteria. Each solution comes with “How it is marked”, a split of the marks. It is a guide, mine: it is not the official marking scheme.
- Finish with the cheat sheet and “For your script”. The cheat sheet only has results (it is what you may bring handwritten to the exam: one sheet, both sides, in the EC1) and “For your script” is the topic’s code, ready for your
.Rfile. If you want to review on the computer first, the R practice has the topic’s three programs with comments.
Exercise 1: the lunchbox that comes out hot (15 marks)
When you take the lunchbox out after two minutes, only part of the dish is really hot. Let be the proportion of the dish that comes out properly hot. After many tests (by someone with a lot of patience), its density function is
and 0 outside that interval, where is a positive constant.
(a) Find so that is a density. (2 marks)
(b) Find and . (3 marks)
(c) Find the distribution function of . (3 marks)
(d) With R’s curve function, plot the density and say, from the plot, where its mode is. (2 marks)
(e) With R, find the median of . (3 marks)
(f) Find the probability that more than 80% of the dish comes out hot. (2 marks)
For (a), expand before integrating. In (e), the equation is fourth degree: do not solve it, pass it to uniroot subtracting 0.5.
Exercise 2: the rush-hour queue (10 marks)
At rush hour, on average, one person arrives at the microwave every 45 seconds. We assume the times between arrivals are independent and that the process has no memory.
(a) Let be the time, in minutes, between two consecutive arrivals. Identify its distribution, find the probability that more than a minute goes by without anyone arriving and the time that is not exceeded 90% of the time. (3 marks)
(b) You have been in the queue for a minute and a half and nobody has arrived behind you. What is the probability that nobody arrives in the next 30 seconds? Justify your answer. (2 marks)
(c) Let be the time until four people arrive. Reason out its distribution, give its mean and variance and compute, with R, the probability that four people arrive in less than 3 minutes. (3 marks)
(d) The time each person keeps the microwave busy follows a gamma with mean 2.4 minutes and standard deviation 1.2. Find its parameters and compute, with R, the probability that a lunchbox takes between 2 and 3 minutes. (2 marks)
“One person every 45 seconds” is a rate: convert it to people per minute before writing .
Exercise 3: three ways to pay (15 marks)
At the cafeteria till there are three ways to pay. 60% of people pay by card, and the payment time is exponential with a mean of half a minute. 25% pay in cash, with a time that is uniform between half a minute and two and a half minutes. 15% pay with the university app, with a time that follows a gamma with mean 1 minute and variance 0.5.
(a) Let be the payment time, in minutes. Give the expression of for each payment method and, with the law of total probability, find for , in terms of the distribution functions of each payment method. (5 marks)
(b) A customer took less than a minute to pay. With R, find the probability of each payment method. (5 marks)
(c) Find the mean payment time. (2 marks)
(d) With R, find the median of . (3 marks)
For the app, first get and from the mean and the variance. In (d), the distribution function of the mixture is the one from (a): define it in R and pass it to uniroot.
Bonus (2.5 marks)
Let . Using only the moment generating function of , find .
Solutions
Exercise 1
(a) For , and , so if . The integral:
Why expand, and why positivity. Integrating by parts also works, but expanded it is : two powers you can integrate in your head. And a density needs two things: it must integrate to 1 and it must not be negative. The second is the one people forget, and it is worth a mark.
(b) Multiplying by and by :
Why and not the definition. The variance is also , but you would have to expand times . With the shortcut formula you only integrate one more power, the same sum as the mean.
On average 60% of the dish comes out hot, with a standard deviation of 0.2.
(c) Piece by piece:
| Piece | |
|---|---|
Check: and .
Why three pieces. is defined on the whole real line, not only where lives. If you write only , at it would give , a negative “probability”. And the integral starts at 0, not at , because to the left of 0 the density is 0 and adds nothing. The variable inside is called so you don’t mix it up with the limit .
Check you’ve got it: what are and ?
. For the second, . In a continuous variable and are the same: a single point has no area.
(d), (e) and (f) with R:
f <- function(x) ifelse(x > 0 & x < 1, 12 * x^2 * (1 - x), 0) integrate(f, 0, 1)$value # (a) check: integrates to 1 mean_x <- integrate(function(x) x * f(x), 0, 1)$value variance <- integrate(function(x) x^2 * f(x), 0, 1)$value - mean_x^2 round(c(mean = mean_x, variance = variance), 2) # (b) check curve(f, from = 0, to = 1, lwd = 2, ylab = "f(x)", xlab = "proportion hot") # (d) F <- function(x) 4 * x^3 - 3 * x^4 # F on the piece (0, 1) median_x <- uniroot(function(x) F(x) - 0.5, c(0, 1))$root # (e) round(median_x, 2) round(1 - F(0.8), 2) # (f) P(X > 0.8)
Output:
[1] 1
mean variance
0.60 0.04
[1] 0.61
[1] 0.18
(d) The plot drawn by curve is a hump that starts at 0, rises to a maximum and falls to 0 at . It reads like this: the mode is right of center, around 0.67 (exactly, gives , with ). Most of the time a bit more than half the dish comes out hot, and hardly ever less than 20%. The density going above 1 is not a mistake: it is a height.
(e) The median is 0.61: half the time less than 61% of the dish comes out hot. It lies between the mean (0.6) and the mode (0.67): the density has its tail on the left. Check: , and .
Why uniroot and not solving by hand. is a quartic: you don’t solve it by hand. uniroot looks for where a function equals zero, so you give it . The interval works because at its ends that difference is and : it changes sign, so somewhere in between it has to cross 0.
(f) .
It is a : mean , variance and mode . If you recognise it, qbeta(0.5, 3, 2) gives the median directly and the rest comes from the beta’s formulas. In the exam, write the integrals anyway: they ask for the working.
How it is marked (a guide, mine): (a) 1 mark for positivity and the integral set up correctly, 1 for the value; (b) 1 mark per moment and 1 for the variance with the shortcut formula; (c) 2 marks for the middle piece and 1 for the two outer pieces; (d) 1 for the plot and 1 for reading off the mode; (e) 2 for uniroot set up correctly (with the - 0.5) and 1 for the value; (f) 1 for setting it up with and 1 for the value.
Exercise 2
(a) One person every 45 seconds is one every 0.75 minutes: the rate is people per minute. Since there is no memory, , with mean 0.75 minutes. Then and the time not exceeded 90% of the time is the 0.9 quantile: .
The set-up before the sums. Three decisions, in this order. Units: is in minutes, so everything goes in minutes. The parameter: the exponential is written with the rate, , not with the mean. And the question: “more than a minute” is the tail, , not . The quantile comes from , taking natural logarithms (R’s log).
(b) By the memorylessness of the exponential:
The minute and a half you have already spent does not count: it is the same probability as seeing nobody in 30 seconds from when you arrive.
The step that gets skipped. Why is only left on top? Because “nobody in 2 minutes” already includes “nobody in 1.5”: . And the 2 is what you have already waited, 1.5, plus what they ask about, 0.5. Answering straight away gets the number right, but “justify” asks you to write the conditional and see it simplify.
Check you’ve got it: if you have waited five minutes and nobody has arrived, what is the probability that nobody arrives in the next minute?
, the same as in (a). It doesn’t matter how long you’ve been waiting: the exponential has no memory.
(c) is the sum of four times between arrivals, independent exponentials with rate : . Its mean is minutes and its variance .
Why a sum and not . The temptation is to say that waiting for four people is “four times “. But is a single time multiplied, with variance . is four independent times that sometimes balance each other out: the means add up () and so do the variances (). The gamma’s first parameter counts how many exponentials you add.
(d) With and : and . The microwave time is .
Where those two formulas come from. No need to memorise them: and . Dividing the first by the second gets rid of and leaves ; then . The typical slip is to plug in the standard deviation, 1.2, as if it were the variance: you would get and , and everything after that wrong.
lambda <- 1 / 0.75 # people per minute
round(1 - pexp(1, lambda), 2) # (a) P(T > 1)
round(qexp(0.9, lambda), 2) # (a) 0.9 quantile
round(c(conditional = (1 - pexp(2, lambda)) / (1 - pexp(1.5, lambda)),
no_wait = 1 - pexp(0.5, lambda)), 2) # (b)
round(c(mean = 4 / lambda, variance = 4 / lambda^2), 2) # (c)
round(pgamma(3, 4, lambda), 2) # (c) P(S < 3)
alpha <- 2.4^2 / 1.2^2; beta <- 2.4 / 1.2^2
round(c(alpha = alpha, beta = beta), 2) # (d)
round(pgamma(3, alpha, beta) - pgamma(2, alpha, beta), 2) # (d) P(2 < T < 3)
Output:
[1] 0.26
[1] 1.73
conditional no_wait
0.51 0.51
mean variance
3.00 2.25
[1] 0.57
alpha beta
4.00 1.67
[1] 0.31
(a) 26% of the time more than a minute goes by without anyone arriving, and 90% of the times between arrivals are below 1.73 minutes. (b) 0.51 both ways, as memorylessness predicts. (c) The mean of is 3 minutes and its variance 2.25; the probability that four people arrive in less than 3 minutes is 0.57, a bit more than half even though 3 is exactly the mean (the gamma has its tail on the right and its median is below the mean). (d) and , and 31% of lunchboxes take between 2 and 3 minutes.
How it is marked (a guide, mine): (a) 1 mark for identifying the exponential with (with , 0), 1 for the probability and 1 for the quantile; (b) 1 for setting up the conditional and 1 for the value with memorylessness; (c) 1 for reasoning the gamma as a sum, 1 for mean and variance and 1 for the probability; (d) 1 for the parameters and 1 for the probability.
Exercise 3
(a) First, the three models. Card (Ca): mean 0.5, so , with . Cash (Cs): , with if , between 0.5 and 2.5 and 1 after. App (Ap): and , so , with (in R, pgamma(t, 2, 2)).
Each conditional is the of its model: . The three payment methods are a partition (each customer pays with one and only one), so, by total probability:
Why you weight the s and not the times. The path that looks obvious is to write . But that would be a customer who pays a little with each method at once. Each customer pays in only one way, and what the weights share out is the probability, not the time. That is why you condition on the payment method and weight the distribution functions.
(b) By Bayes, for each payment method :
The set-up. What you know is the result, “under a minute”, and they ask about the cause, the payment method: that is Bayes. The typical mistake is to answer with the in the output (0.86, 0.25 and 0.59). Those are , the conditional the wrong way round, and they give themselves away: they add up to 1.71, not 1.
(c) The mean of the mixture is the weighted mean of the means: minutes (the mean of the uniform is ).
p <- c(card = 0.60, cash = 0.25, app = 0.15)
Fk <- function(t) c(card = pexp(t, 2), cash = punif(t, 0.5, 2.5),
app = pgamma(t, 2, 2))
Fmixture <- function(t) sum(p * Fk(t)) # (a) total probability
round(Fk(1), 4) # each F at one minute
round(Fmixture(1), 4) # P(T < 1)
round(p * Fk(1) / Fmixture(1), 4) # (b) Bayes
sum(p * c(1 / 2, (0.5 + 2.5) / 2, 2 / 2)) # (c) the mean of the mixture
median_t <- uniroot(function(t) Fmixture(t) - 0.5, c(0, 3))$root # (d)
round(median_t, 2)
curve(Vectorize(Fmixture)(x), from = 0, to = 3, lwd = 2, ylab = "P(T < t)", xlab = "minutes")
abline(h = 0.5, lty = 2)
Output:
card cash app 0.8647 0.2500 0.5940 [1] 0.6704 card cash app 0.7739 0.0932 0.1329 [1] 0.825 [1] 0.63
(b) Within a minute, 86% of those paying by card are done, 25% of those paying in cash () and 59% of those using the app. In total, . Knowing that someone paid in under a minute: card 0.77, cash 0.09 and app 0.13. Paying fast raises card from 60% to 77% and sinks cash from 25% to 9%.
(d) The median of is 0.63 minutes: half the people pay in under 38 seconds. It is quite a bit below the mean (0.825): cash payments, long and infrequent, pull the mean up.
Why the mean is weighted and the median isn’t. The mixture’s density is the weighted sum of the three densities, and the integral of a sum splits up: the mean comes out weighted. The median means solving , and that doesn’t split. Weighting the medians of each payment method (0.35, 1.5 and 0.84) gives 0.71, and there the mixture is already 0.54: it has overshot. Hence uniroot, with : at 0 the difference is and at 3 almost .
The plot is the distribution function of the mixture drawn by curve. It reads like this: it rises fast at the start (card, quick and the majority), crosses 0.5 at 0.63 minutes (the median, where the dashed line cuts the curve), has a small kink at 0.5 minutes (where cash starts to count) and reaches 1 at 2.5 minutes, except for the tail of card and app, which keep rising very slowly.
curve(Fmixture, …) without Vectorize. curve passes the function a vector of 101 values of at once, and sum(p * Fk(t)) would add everything into a single number. Vectorize(Fmixture) turns it into a function applied value by value. In uniroot it is not needed, because it evaluates points one at a time.
How it is marked (a guide, mine): (a) 1 mark for each model with its written correctly (3) and 2 for total probability with the partition justified; (b) 2 for setting up Bayes, 1 for and 2 for the three probabilities (adding up to 1); (c) 1 for the idea of a weighted mean and 1 for the value; (d) 2 for the function and the uniroot and 1 for the value.
Bonus
The gamma’s mgf is for . What is asked for is with , which always satisfies (because ). So
Why not integrate. also works, but the question asks you to use only the mgf. The idea is to see as with : there is nothing to calculate, just substitute and check that is where the mgf exists.
For example, with the wait for three people ahead, , it gives .
How it is marked (a guide, mine): 1 mark for seeing that it is the mgf at , 0.5 for checking it is where the mgf exists and 1 for the result.
What’s wrong here?
Three solutions by classmates. Before reading the explanation, try to find the mistake.
Fragment 1. “The time between arrivals is . The probability that exactly 2 minutes go by is”:
dexp(2, 0.5)
Output:
[1] 0.1839397
dexp is the height of the density, not a probability. For a continuous variable, . If the problem asks for “exactly”, the answer is 0; if it meant an interval (between 1.5 and 2.5 minutes), it is pexp(2.5, 0.5) - pexp(1.5, 0.5), which gives 0.19. That the dexp number “looks like” a probability is a coincidence: with , dexp(0, 3) gives 3.
In the drawing, the vertical line is what dexp(2, 0.5) computes: a height of 0.18. Probabilities are areas, like the band shaded between 1.5 and 2.5. A line has no width, and that is why its area (the probability of an exact value) is 0.
Fragment 2. “The median in exercise 1 is the root of “:
F <- function(x) 4 * x^3 - 3 * x^4 uniroot(F, c(0.1, 1))
Output:
Error in uniroot(F, c(0.1, 1)) : f() values at end points not of opposite sign
uniroot looks for where the function is 0, and the median is where is 0.5. You have to pass it function(x) F(x) - 0.5. The error message says that does not change sign between 0.1 and 1 (it is 0.0037 and 1, both positive), and uniroot needs a different sign at each end. With the interval there would have been no error, but something worse: the root , a median that makes no sense.
Fragment 3. “One person every 45 seconds, so in minutes, and the probability of waiting more than a minute is”:
1 - pexp(1, 0.75) 1 - pexp(1, 1 / 0.75)
Output:
[1] 0.4723666 [1] 0.2635971
0.75 is the mean (in minutes), not the rate. The parameter of pexp is the rate, . The first line models one person every 1.33 minutes and gives 0.47; the right one (the second) gives 0.26. A quick way to spot it: with , 1 / 0.75 would be the mean, 1.33 minutes, and the problem said 45 seconds.
Before any pexp or pgamma, write in a comment the mean you should get (# mean 0.75 min) and check it with 1 / lambda or alpha / beta. It costs one line and avoids the most expensive mistake in the topic.
Practice quiz
Before moving on to the next topic, check you have got it. This quiz is here to consolidate what this article explains: the ME1 exam is not a multiple-choice test (you solve problems by hand and with R), so no mark here counts. There are 10 questions on continuous random variables: key ideas, typical mistakes and many «what does this R code print?», with the outputs from really running it. In the short answers, a decimal point or a decimal comma both work. Answer without running anything, press Check and read the explanation for each option; you can repeat it as many times as you like.
T ~ exp(0.5). «The probability that exactly 2 minutes pass» is computed with dexp(2, 0.5) and gives 0.18. What is wrong?
- dexp is the height of the density, not a probability: for a continuous variable, P(T = 2) = 0
- It should be
dexp(2, 2) - Nothing: dexp gives the probability of a value
- It should be
1 - pexp(2, 0.5)
Solution
Answer: dexp is the height of the density, not a probability: for a continuous variable, P(T = 2) = 0
Probabilities are areas. A vertical line has no width, so the probability of an exact value is 0.
For the median of F(x) = 4x³ − 3x⁴ on (0, 1), a classmate writes uniroot(F, c(0.1, 1)) and gets an error. What should they have written?
uniroot(function(x) F(x) - 0.5, c(0.1, 1))uniroot(F, c(0, 1))optimize(F, c(0, 1))integrate(F, 0, 1)
Solution
Answer: uniroot(function(x) F(x) - 0.5, c(0.1, 1))
The error said F does not change sign between 0.1 and 1 (it is 0.0037 and 1). uniroot needs a different sign at each end.
One person arrives every 45 seconds on average, so the time between arrivals (in minutes) has mean 0.75. What does it print?
round(1 - pexp(1, 1 / 0.75), 2)
Solution
Answer: 0.26
pexp’s parameter is the rate, λ = 1 / 0.75 = 4/3 per minute. P(T > 1) = e^(−4/3) = 0.26. With pexp(1, 0.75) you would be modelling one person every 1.33 minutes (and get 0.47).
The density is f(x) = k · x²(1 − x) on (0, 1). What is k?
g <- function(x) x^2 * (1 - x) 1 / integrate(g, 0, 1)$value
Solution
Answer: 12
The density must integrate to 1: ∫ x²(1 − x) dx from 0 to 1 = 1/3 − 1/4 = 1/12, so k = 12.
With that density, f(x) = 12x²(1 − x), what is the mean? (2 decimals.)
f <- function(x) 12 * x^2 * (1 - x) round(integrate(function(x) x * f(x), 0, 1)$value, 2)
Solution
Answer: 0.6
E(X) = ∫ x · 12x²(1 − x) dx = 12 · (1/4 − 1/5) = 12 · 1/20 = 0.60.
A gamma has mean 2.4 and standard deviation 1.2. What are its parameters (α, β with β the rate)?
- α = 4 and β = 1.667
- α = 2 and β = 0.833
- α = 2.4 and β = 1.2
- α = 1.667 and β = 4
Solution
Answer: α = 4 and β = 1.667
In the gamma, mean = α/β and variance = α/β². Solving: β = μ/σ² and α = μ²/σ² (the gamma_par function in «For your script»).
Match each R command with what it computes:
| integrate(f, a, b) | |
| uniroot(function(x) F(x) – p, c(a, b)) | |
| optimize(f, c(a, b), maximum = TRUE) | |
| 1 – pexp(t, lambda) |
Definitions:
- P(T > t) for an exponential
- The mode (where f is largest)
- The height of the density at t
- The p quantile
- The area under f between a and b
Solution
- integrate(f, a, b) → The area under f between a and b
- uniroot(function(x) F(x) – p, c(a, b)) → The p quantile
- optimize(f, c(a, b), maximum = TRUE) → The mode (where f is largest)
- 1 – pexp(t, lambda) → P(T > t) for an exponential
The height of the density at a point is dexp(t, lambda) (or f(t)): it is not a probability.
True or false?
- For a continuous variable, P(a < X < b) = P(a ≤ X ≤ b).
- The exponential has no memory: P(T > s + t | T > s) = P(T > t).
- A density can never be greater than 1 at any point.
- Γ(n) = (n − 1)! for a positive integer n.
Solution
- T — For a continuous variable, P(a < X < b) = P(a ≤ X ≤ b).
- T — The exponential has no memory: P(T > s + t | T > s) = P(T > t).
- F — A density can never be greater than 1 at any point.
- T — Γ(n) = (n − 1)! for a positive integer n.
A density can exceed 1 (dexp(0, 3) is 3); what equals 1 is its total area. Since every point has probability 0, the boundaries do not matter.
People pay by card (60 %), cash (25 %) or app (15 %), and each method has its own payment-time distribution. For P(card | paid in under 1 minute), what do you do?
- Bayes: 0.60 · F_card(1) divided by the total probability Σ p_k F_k(1)
- Take F_card(1)
- Take 0.60
- Add up the three F_k(1)
Solution
Answer: Bayes: 0.60 · F_card(1) divided by the total probability Σ p_k F_k(1)
Mixture: F(t) = Σ p_k F_k(t) and P(k | T < t) = p_k F_k(t) / F(t). It is the mixture_bayes function in «For your script».
What value does the mode of f(x) = 12x²(1 − x) take? (2 decimals.)
f <- function(x) 12 * x^2 * (1 - x) round(optimize(f, c(0, 1), maximum = TRUE)$maximum, 2)
Solution
Answer: 0.67
The mode is where the density is largest: f'(x) = 12(2x − 3x²) = 0 → x = 2/3 = 0.67. optimize finds it numerically.
Try it in the R playground
Open the site’s R playground (or RStudio) and solve the whole of exercise 1 with this skeleton. Change the density to another one from the proposed exercises and run it again:
g <- function(x) x^2 * (1 - x) # the density without the constant k <- 1 / integrate(g, 0, 1)$value # (a) f <- function(x) ifelse(x > 0 & x < 1, k * g(x), 0) mean_x <- integrate(function(x) x * f(x), 0, 1)$value variance <- integrate(function(x) x^2 * f(x), 0, 1)$value - mean_x^2 F <- function(x) integrate(f, 0, x)$value # numerical F, no integrating by hand median_x <- uniroot(function(x) F(x) - 0.5, c(0.01, 0.99))$root round(c(k = k, mean = mean_x, variance = variance, median = median_x), 2) curve(f, from = 0, to = 1, lwd = 2, ylab = "f(x)")
What to look at:
- In the Environment panel,
kis 12: changex^2 * (1 - x)tox * (1 - x)^2and you will see the constant and moments from proof 1. Fis defined withintegrateinside: that way you do not need to have integrated by hand to look for the median. It is slower, but it works for any density.- The
curveplot goes above 1 in the middle: check withf(2/3)that the maximum height is 1.78. - Try
uniroot(function(x) F(x) - 0.5, c(0.01, 0.5)): it gives an error because in that interval does not change sign. It is fragment 2 of “What’s wrong here?”.
Cheat sheet: continuous random variables
The essentials in 30 seconds. Density: , . Probability = area: . and endpoints do not matter. , . Mean , variance . Median: .
| Model | Density | Mean | Variance | mgf |
|---|---|---|---|---|
| , | ||||
| , | , | |||
| , | , | |||
| , | — |
Other results: exponential: , , mode 0, . Gamma: , , , mode , sum of independent exp(); from mean and variance: , . Beta: , mode . Mixture: , , .
| I want… | Code | Result |
|---|---|---|
| To check a density | integrate(f, a, b)$value | 1 |
| A mean | integrate(function(x) x * f(x), a, b)$value | |
| The median without solving | uniroot(function(x) F(x) - 0.5, c(a, b))$root | |
| The mode | optimize(f, c(a, b), maximum = TRUE)$maximum | where the maximum is |
| , exponential with mean | 1 - pexp(t, 1 / m) | the tail |
| A gamma where each step has mean | pgamma(x, alpha, scale = m) | |
| Parameters of a gamma | beta <- m / s2; alpha <- m^2 / s2 | , |
| Plot a density | curve(f, from = a, to = b) | the curve |
| Symptom | Likely cause |
|---|---|
integrate gives 2 or 0.5 | The constant is wrong |
| A negative mean for a time | The sign of in integration by parts |
| “f() values at end points not of opposite sign” | not subtracted in uniroot, or the interval does not contain the root |
| “non-finite function value” | An exp(t * x) up to Inf: cut at a large value |
| The simulated mean is 4 times too small | Rate for scale in rgamma/pgamma |
curve gives a flat line | The function is not vectorised: Vectorize |
Before handing in, ask yourself:
- Have I written the positivity and the 0 and 1 pieces of ?
- Is the parameter of each
pexp/pgammaa rate? - Is the mean I get reasonable for what it measures (a time, a proportion)?
- Have I given results to 2 decimals and saved the code in the
.Rfile?
For your script
The topic’s code, ready to paste into your exam .R file. They are my own functions that solve the typical parts, plus the code for this article’s exercises, without the problem statements. It has been run exactly as it is.
# ===== Continuous random variables (ME1, topic 4) =====
# --- A density given by a formula ---
# g: the density without the constant; a, b: the support. Returns the constant k.
constant <- function(g, a, b) 1 / integrate(g, a, b)$value
# Mean, variance and standard deviation of a density f on (a, b)
moments <- function(f, a, b) {
m <- integrate(function(x) x * f(x), a, b)$value
v <- integrate(function(x) x^2 * f(x), a, b)$value - m^2
round(c(mean = m, variance = v, sd = sqrt(v)), 2)
}
# Quantile p of a density f on (a, b), without F by hand
quantile_f <- function(f, p, a, b) {
F <- function(x) integrate(f, a, x)$value
uniroot(function(x) F(x) - p, c(a + 1e-6, b - 1e-6))$root
}
# Mode: where the density is highest
mode_f <- function(f, a, b) optimize(f, c(a, b), maximum = TRUE)$maximum
# --- Models ---
# Gamma from the mean and the variance
gamma_par <- function(m, v) c(alpha = m^2 / v, beta = m / v)
# Exponential from the mean: the rate
rate_from_mean <- function(mean) 1 / mean
# --- Mixtures: total probability and Bayes ---
# p: weights; Fs: list of distribution functions
mixture_F <- function(t, p, Fs) sum(p * sapply(Fs, function(F) F(t)))
mixture_bayes <- function(t, p, Fs) {
r <- p * sapply(Fs, function(F) F(t))
round(r / sum(r), 4)
}
# --- Exercise 1 ---
g1 <- function(x) x^2 * (1 - x)
k1 <- constant(g1, 0, 1)
f1 <- function(x) k1 * g1(x)
k1
moments(f1, 0, 1)
round(c(median = quantile_f(f1, 0.5, 0, 1), mode = mode_f(f1, 0, 1)), 2)
# --- Exercise 2 ---
round(1 - pexp(1, rate_from_mean(0.75)), 2)
gamma_par(2.4, 1.2^2)
# --- Exercise 3 ---
p3 <- c(card = 0.60, cash = 0.25, app = 0.15)
F3 <- list(function(t) pexp(t, 2), function(t) punif(t, 0.5, 2.5), function(t) pgamma(t, 2, 2))
round(mixture_F(1, p3, F3), 4)
mixture_bayes(1, p3, F3)
Output:
[1] 12
mean variance sd
0.60 0.04 0.20
median mode
0.61 0.67
[1] 0.26
alpha beta
4.000000 1.666667
[1] 0.6704
card cash app
0.7739 0.0932 0.1329
The output checks the functions against the exercises: , mean 0.6 and variance 0.04 from exercise 1, its median (0.61) and its mode (0.67); the exponential tail and the gamma parameters from exercise 2; and the total probability and the three Bayes probabilities from exercise 3. sapply(Fs, function(F) F(t)) applies each function in the list to the same and returns a vector: that is what lets you write a mixture with any number of components.
What next?
With this topic you close the EC1 part: discrete and continuous random variables, without the normal. Topic 5 brings the normal distribution, the most used in statistics, which goes in the EC2 in the exam. If you want to review first, go back to the theory, the proofs or the R practice, or compare with the discrete random variables exercises, which have the same format.
Keep goingAll Statistics articlesDid this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC1 mock exam — the 4-hour exam with R alongside, four versions, a mark out of 50 and every solution with its code (and why the .R counts too)


