function [distance]=marsaglia_defect(length,tol)

%Marsaglia_defect will run through a sequence of random numbers where the
%number of elements is =length. It will mark the elements that are less
%than the number tol, label them, and note the distance between them.  It
%will also produce a histogram of the lengths

random_numbers=zeros(1,length);
random_numbers=rand(1,length);      %row vector of random numbers
labeled_numbers=zeros(1,length);    %Initialize array to make quicker
j=1;                                %beginning label of numbers less than tol

for i=1: length
    
    if random_numbers(i)<tol
        labeled_numbers(j)=i;           %mark index of number
        j=j+1;
    end
end

distance=diff(labeled_numbers);                       %measure distance between indexed numbers

i=1;
while distance(i)>0
i=i+1;
end

hist(distance(1:i-1));
title('Marsaglia generator: Distance between numbers less than 1/8');
xlabel('Distance between numbers that fall below tolerance');


