MATLAB Examples

Example A. Volume of a Hypersphere Inscribed in a Hypercube.

Contents

Theory

Consider the hypercube $[-a, a]^d$ and an inscribed hypersphere with radius $r=a$. Then the fraction of the volume of the cube contained in the hypersphere is given by:

$$f_d = \frac{ volume of sphere} { volume of cube}\ = \frac{\pi^{d/2}}{d 2^{d-1} \Gamma(d/2)}\ $$

At higher dimensions, the center of the cube becomes less important. As the dimension increases, the volume of the hypercube concentrates at its comers! In other words, less and less volume is captured inside the hypersphere!

% Workspace Initialization.
clc; clear; close all;

Monte Carlo Verification of the fraction $f_d$

a = 5;              % a is the Radius of Hypersphere = 1/2*Hypercube Edge.
NumOfRuns = 50000;  % Number of Monte Carlo runs.
Dimensions = 2:10;  % Dimensions visited.
LD = length(Dimensions);
counter_inside   = zeros(1,LD);
counter_outside = zeros(1,LD);

for i=1:LD
     dim = Dimensions(i);
     for k=1:NumOfRuns

           ndUniformSamples = 2*a*(rand(1,dim)-0.5);    % generate uniform samples in [-a, a]^d.

           % Measure how many points fall inside or outside of the inscribed hypersphere:
           if sum(ndUniformSamples.^2)<a^2
               counter_inside(i) = counter_inside(i) + 1;
           else
               counter_outside(i) = counter_outside(i) + 1;
           end

      end

end

Calculate the Theoretical Value as given from the above formula:

fd = zeros(1,LD);
for i=1:LD
     dim = Dimensions(i);
     fd(i) = sqrt(pi^dim)/(dim*2^(dim-1)*gamma(dim/2));
end

Plot the Results:

Plot the value of $f_d$ found by Monte Carlo simulation:

figure(1);
stem(Dimensions,counter_inside/NumOfRuns,'*r');
hold on;
% Now plot the theoretical value with blue circles:
stem(Dimensions,fd);
grid on;
xlabel('Dimension');
ylabel('Fraction of volume contained in the hypershere f_d');
title('Analytically Calculated (blue circles) and Monte Carlo Estimated (red stars)');

Note

If you like you may plot the complementary value of 1-f_d found by Monte Carlo simulation:

% figure(2);
% stem(Dimensions,counter_outside/NumOfRuns,'g*');
% Next plot the theoretical value with cyan circles
% stem(Dimensions,1-fd,'c');
% grid on;
% xlabel('Dimension');
% ylabel('Fraction of volume outside the hypershere 1-f_d');
% title('Analytically Calculated (cyan circles) and Monte Carlo Predicted (green stars)');