MATLAB: Problem of “sprandn”: the number of nonzero elements is inconsistent with density

sprandn

R = sprandn(m,n,density) is a random, m-by-n, sparse matrix with approximately density*m*n normally distributed nonzero entries (0 <= density <= 1).
However, if density is large, the number of nonzero entries it not consistent with density.
nnz(sprandn(100,10,0.3))
ans =
259
nnz(sprandn(100,10,0.7))
ans =
492
For density=0.7, the number of nonzero elements should be approximately 700, but the result is only 492.
This is an example, I have tried for many times but results are similar.
I apologize in advance if it is a trivial problem.

Best Answer

The approximation is only good when density << 1. I think SPRAND/SPRANDN simply create random draw of (density*m*n) pairs of (i,j) WITH replacement (perhaps for the reason of efficiency and memory).
When density specified is close to 1, there are a lot of pairs that collide in the same place and the effective density is less than what user specifies.
>> nnz(sprand(100,100,1))/100^2
ans =
0.6400
I believe the "defective ratio" is about
>> 1-1/exp(1)
ans =
0.6321
for density ~ 1 and large m*n