where is .5?

A Riddler’s riddle on breaking the unit interval into 4 random bits (by which I understand picking 3 Uniform realisations and ordering them) and finding the length of the bit containing ½ (sparing you the chore of converting inches and feet into decimals). The result can be found by direct integration since the ordered Uniform variates are Beta’s, and so are their consecutive differences, leading to an average length of 15/32. Or by raw R simulation:

simz=t(apply(matrix(runif(3*1e5),ncol=3),1,sort))
mean((simz[,1]>.5)*simz[,1]+
  (simz[,1]<.5)*(simz[,2]>.5)*(simz[,2]-simz[,1])+
  (simz[,2]<.5)*(simz[,3]>.5)*(simz[,3]-simz[,2])+
  (simz[,3]<.5)*(1-simz[,3]))

Which can be reproduced for other values than ½, showing that ½ is the value leading to the largest expected length. I wonder if there is a faster way to reach this nice 15/32.

4 Responses to “where is .5?”

  1. Numpy seems to be about 15x faster using my naive implementation

    “`
    import numpy as np
    import time

    start = time.time()

    mat = np.random.uniform(size=3 * int(1e5)).reshape((int(1e5), 3))
    simz = np.apply_along_axis(np.sort, 1, mat)

    a = np.mean(
    (simz[:, 0] > 0.5) * simz[:, 0]
    + (simz[:, 0] 0.5) * (simz[:, 1] – simz[:, 0])
    + (simz[:, 1] 0.5) * (simz[:, 2] – simz[:, 1])
    + (simz[:, 2] < 0.5) * (1 – simz[:, 2]))

    end = time.time()

    print(end – start)
    “`

    Clocks in at around 0.3 secs on my laptop vs 5 secs for your r code.

    • Thanks for the alternative! (I was not attempting at being fast, esp. when using R.)

    • Radford Neal Says:

      The R code is also much faster in pqR-2020-07-23 (see pqR-project.org) than in R-4.0.2 (1.2 seconds vs. 8.0 seconds on the computer I’m using at the moment). Further investigation reveals that most of the time is spent in ‘sort’, which has a faster implementation in pqR.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: