随机性检测的五项基本检测方法的matlab程序
时间: 2023-12-07 07:09:08 浏览: 90
用matlab实现随机过程
以下是五项基本检测方法的 Matlab 程序:
1. 频数检测
```matlab
function [p_value] = frequency_test(bits)
n = length(bits);
count = sum(bits);
p_value = 2*min(count, n-count)/n;
end
```
2. 块频数检测
```matlab
function [p_value] = block_frequency_test(bits, block_size)
n = length(bits);
num_blocks = floor(n/block_size);
counts = zeros(num_blocks, 1);
for i = 1:num_blocks
block = bits((i-1)*block_size+1:i*block_size);
counts(i) = sum(block);
end
chi2 = ((counts - block_size/2).^2) / (block_size/2);
p_value = 1 - gammainc(num_blocks/2, chi2/2);
end
```
3. 游程总数检测
```matlab
function [p_value] = runs_test(bits)
n = length(bits);
runs = 1;
for i = 2:n
if bits(i) ~= bits(i-1)
runs = runs + 1;
end
end
pi = runs / n;
tau = 2 / sqrt(n);
if abs(pi - 0.5) >= tau
p_value = 0;
else
vobs = 1;
for i = 2:n
if bits(i) ~= bits(i-1)
vobs = vobs + 1;
else
break;
end
end
for i = n:-1:2
if bits(i) ~= bits(i-1)
vobs = vobs + 1;
else
break;
end
end
mu = (2*n - 1) / 3;
sigma2 = (16*n - 29) / 90;
sigma = sqrt(sigma2);
z = (vobs - mu) / sigma;
p_value = erfc(abs(z) / sqrt(2));
end
end
```
4. 乱数排列检测
```matlab
function [p_value] = permutation_test(bits)
n = length(bits);
pi = sum(bits) / n;
if abs(pi - 0.5) >= 2/sqrt(n)
p_value = 0;
else
k = 0;
for i = 2:n
if bits(i) ~= bits(i-1)
k = k + 1;
end
end
k = k + 1;
tau = 2 / sqrt(n);
if abs(k - 2*n*pi*(1-pi)) >= tau
p_value = 0;
else
p_value = gammainc((n-1)/2, (abs(k - 2*n*pi*(1-pi))/2)^2);
end
end
end
```
5. 矩阵秩检测
```matlab
function [p_value] = matrix_rank_test(bits, matrix_size)
n = length(bits);
num_matrices = floor(n/matrix_size);
counts = zeros(num_matrices, 1);
for i = 1:num_matrices
matrix = reshape(bits((i-1)*matrix_size+1:i*matrix_size), sqrt(matrix_size), sqrt(matrix_size));
counts(i) = rank(matrix);
end
mu = matrix_size*(1/2 + 1/18);
sigma2 = matrix_size*(13/18 - 7/180)^2 + matrix_size*(1/6 - 1/180);
sigma = sqrt(sigma2);
chi2 = ((counts - mu).^2) / sigma2;
p_value = 1 - gammainc(num_matrices/2, chi2/2);
end
```
阅读全文