![]() |
Prev | Next |
Matlab or Octave |
x = randn( m, n)
|
C++ |
x = randn( m, n)
|
x = randn(
m,
n)
sets x to an @(@
m \times n
@)@ matrix each entry
drawn from an independent normally distribution with mean
zero and variance one.
function [ok] = randn_ok()
ok = true;
m = 100;
n = 11;
% -------------------
x = randn(m, n);
% -------------------
[m_, n_]= size(x);
ok = ok & (m == m_);
ok = ok & (n == n_);
N = m * n;
sum_ = sum( sum(x) );
sumsq = sum( sum( x .* x ) );
avg = sum_ / N;
var = sumsq / N - avg * avg;
ok = ok & abs( avg ) < 2 / sqrt(N);
% The variance of N independent chi-squares is 2 / N
ok = ok & abs(var - 1.) < 2 * sqrt( 2. / N );
return
randn
function with the syntax:
x = randn(
m,
n)
where m and n are size_t
values
and x is an @(@
m \times n
@)@
ublas matrix<double>
object.
You must first call the standard library function
std::srand(
seed)
where seed is an unsigned int
to initialize the random number generator std::rand()
.
# include <mat2cpp.hpp>
# include <cstdlib>
# include <cmath>
bool randn_ok(void)
{ bool ok = true;
using namespace mat2cpp;
size_t i, j, m(20), n(21);
// ---------------------------
matrix<double> x = randn(m, n);
// ---------------------------
ok &= (x.size1() == m);
ok &= (x.size2() == n);
double sum = 0.;
double sumsq = 0.;
for(i = 0; i < m; i++)
{ for(j = 0; j < n; j++)
{ sum += x(i, j);
sumsq += x(i, j) * x(i, j);
}
}
double N = double( m * n );
double avg = sum / N;
double var = sumsq / N - avg * avg;
// The variance of N independent standard normals is N
// and variance of avg in 1/N.
ok &= std::fabs(avg) < 3. / std::sqrt(N);
// The variance of N independent chi-squares is 2 * N
// and variance of sumsq is 2/N
ok &= std::fabs(var - 1.) < 3. * std::sqrt( 2. / N );
return ok;
}