MATLAB unifrnd 与 rand函数的区别

MATLAB unifrnd 与 rand函数的区别

最近在生成随机数的时候看到这两个函数,通过查找资料发现二者的关系:

相同点:

  • 二者都是利用rand函数进行随机值计算。
  • 二者都是均匀分布。

不同点:

  • unifrnd是统计工具箱中的函数,是对rand的包装。

不是Matlab自带函数无法使用JIT加速。

  • rand函数可以指定随机数的数据类型。

实例
在区间[5,10]上生成400个均匀分布的随机数 :

 h1=unifrnd(5,10,1,400);
 h2=5+5*rand(1,400); % same pdf

二者生成的结果是相同的。

下面是unifrnd源代码,可以看出该函数可以通过指定参数进行计算。

function r = unifrnd(a,b,varargin)
%UNIFRND Random arrays from continuous uniform distribution.
%   R = UNIFRND(A,B) returns an array of random numbers chosen from the
%   continuous uniform distribution on the interval from A to B.  The size
%   of R is the common size of A and B if both are arrays.  If either
%   parameter is a scalar, the size of R is the size of the other
%   parameter.
%
%   R = UNIFRND(A,B,M,N,...) or R = UNIFRND(A,B,[M,N,...]) returns an
%   M-by-N-by-... array.
%
%   See also UNIFCDF, UNIFINV, UNIFPDF, UNIFSTAT, UNIDRND, RANDOM.

%   UNIFRND uses a linear transformation of standard uniform random values.

%   Copyright 1993-2018 The MathWorks, Inc. 

% Avoid    a+(b-a)*rand   in case   a-b > realmax
%
a2 = a/2;
b2 = b/2;
mu = a2+b2;
sig = b2-a2;

r = mu + sig .* (2*rand(sizeOut,'like',mu)-1);

% Fill in elements corresponding to illegal parameter values
if ~isscalar(a) || ~isscalar(b)
    r(a > b) = NaN;
elseif a > b
    r(:) = NaN;
end

你可能感兴趣的:(数值分析,Matlab)