(Python)
def random_point_on_sphere(dim):
vec = abs(np.random.normal(0, 1, dim)) # Sample from standard normal (only positive values)
vec /= np.linalg.norm(vec) # Normalize to unit length
return vec
L = 1.3 # pencil length, relative to hypercube side length
nsample = 100000000
for dim in range(7, 10): # explore only dimensions which are interesting for length L
count = 0
for i in range(nsample):
x0 = np.random.random(dim) # start point of pencil
pencil = L*random_point_on_sphere(dim)
k=0
while x0[k] + pencil[k] <= 1: # check dimension k if grid line is crossed
if k == n-1:
count += 1
break
else:
k += 1
print(dim, count)
p = count/nsample
# if the difference in the counts is smaller than the confidence interval, repeat with a larger nsample
print("Half-width of 99% confidence interval:", 2.58*sqrt(nsample*p*(1-p)))