Search code examples
matlabrandomnormal-distributionmersenne-twister

normrnd of MATLAB generating different values for the same setting


I do not know how to describe the problem so I titled it like that. If you have any better idea, please fix it. I apologize in advance.

My problem came up with when I was writing a code using normal random generator of MATLAB.

clear all; 
clc; 
close all;
rng(0,'twister');

sigma=50; 
mean(normrnd(10,sigma,20,1))

n=20;
mean(normrnd(10,sigma,n,1))

When I generate 20 normally-distributed numbers while controlling it by setting generator to Mersenne Twister and seed to 0, I can use that code that I provided above. I can write the sample size inside the normrnd function or I can define it out of function but when you run it and find the means of generated numbers for both ways, you will also release that they differ greatly. Such first mean is 43.2294 and the second mean is 7.1280. Does anyone have any idea about this situation?


Solution

  • If you expect two successive calls to normrnd to yield the exact same values, you need to re-initialize the random number generator between calls.

    sigma = 50; 
    n = 20;
    
    rng(0,'twister');
    mean(normrnd(10,sigma,n,1))
    %   43.2294
    
    rng(0,'twister');
    mean(normrnd(10,sigma,n,1))
    %   43.2294
    

    If you're OK with the two arrays having different values but are wondering why the means aren't the same and they are nowhere close to the desired mean, it's because you're only using 20 samples which is under-sampling the distribution and is unlikely to yield a realistic estimate of the mean. If you increase the number of samples to several thousand, you'll see that the means do converge towards the desired mean value.

    sigma = 50; 
    n = 10000;
    
    rng(0,'twister');
    
    mean(normrnd(10,sigma,n,1))
    %   10.0830
    
    mean(normrnd(10,sigma,n,1))
    %   9.8998