gusucode.com > bigdata 工具箱 matlab源码程序 > bigdata/+matlab/+bigdata/+internal/Random.m

    classdef Random
    %Singleton class for managing random number generation for tall arrays.
    %
    %   This internal-only class manages a consecutive series of
    %   independent RandStreams for use with tall arrays/tables. The
    %   RandStreams returned use the Combined Recursive algorithm
    %   (mrg32k3a), each using an independent stream. The first stream
    %   used is 2^32 to minimize risk of conflicts with the normal client
    %   generator.
    %
    %   Use:
    %     rs = matlab.bigdata.internal.Random.getNextRandStream() to
    %     retrieve the next available RandStream to use for sampling.
    %
    %     matlab.bigdata.internal.Random.reset() to restore the state to its
    %     initial condition.
    %
    %   See also: RandStream, tall.
    
    % Copyright 2016 The MathWorks, Inc.
    
    %% Public API
    
    methods (Static)
        function rs = getNextRandStream()
            % Return the next available RandStream for use in a new tall
            % operation.
            idx = matlab.bigdata.internal.Random.getSetIndex();
            
            % Use a parallel capable generator and a deterministic normal
            % conversion.
            type = {'mrg32k3a', 'NormalTransform', 'Inversion'};
            
            % Create a single stream with the required stream index
            rs = RandStream.create(type{:}, 'NumStreams', idx, 'StreamIndices', idx);
            
            % Now that the stream is created, increment the index
            matlab.bigdata.internal.Random.getSetIndex(idx+1);
        end
        
        function reset()
            % Reset the tall random number generator state to its initial
            % value
            matlab.bigdata.internal.Random.getSetIndex([]);
        end
    end
    
    %% Internal API
    
    methods (Access=private)
        function obj = Random()
        end
    end
    
    methods (Static, Access=private)
        function rOld = getSetIndex(rNew)
            % Get or set the one true index. The index is a uint64 giving
            % the next available stream number.
            persistent instance;
            needsReset = (nargin && isempty(rNew));
            if isempty(instance) || ~isa(instance, 'uint64') ...
                    || needsReset
                % MRG32K3A has 2^63 streams. To minimize the risk of
                % conflicts with the non-tall generator, start roughly half
                % way through the set.
                instance = uint64(2^32);
                mlock; % prevent clear classes from resetting the instance
            end
            
            if nargout
                rOld = instance;
            end
            
            if nargin && ~needsReset
                instance = rNew;
            end            
        end
    end
    
end % classdef