R code for example 6.2

x <- c(40, 45, 50)
px <- c(0.2, 0.3, 0.5)

x1 <- rep(x, each = 3)
px1 <- rep(px, each = 3)

x2 <- rep(x, times = 3)
px2 <- rep(px, times = 3)

px1x2 <- px1 * px2  # due to

xbar <- (x1 + x2)/2
S2 <- (x1 - xbar)^2 + (x2 - xbar)^2
sum(xbar * px1x2)
## [1] 46.5
sum(S2 * px1x2)
## [1] 15.25
cbind(x1, x2, px1x2, xbar, S2)
##       x1 x2 px1x2 xbar   S2
##  [1,] 40 40  0.04 40.0  0.0
##  [2,] 40 45  0.06 42.5 12.5
##  [3,] 40 50  0.10 45.0 50.0
##  [4,] 45 40  0.06 42.5 12.5
##  [5,] 45 45  0.09 45.0  0.0
##  [6,] 45 50  0.15 47.5 12.5
##  [7,] 50 40  0.10 45.0 50.0
##  [8,] 50 45  0.15 47.5 12.5
##  [9,] 50 50  0.25 50.0  0.0