Why do the random numbers repeat in each run?

31 次查看(过去 30 天)
Hi, I have the following issue. I see that when I run this function to generate a number of perturbations num_perm to a given array solution.position. This function is part of a more extensive code. The issue is that when I run the function I get a repeated output and it should be random. I add the rng('shuffle') function and I do get different values in each execution. I have used the randi and randsample functions and the behavior is the same. What could be going on, I usually get the random solution without adding any rng options. When I run the same code in Octave I do get random solution.position.
function [solution, f] = INITIAL_PERTURBATION(solution, num_perm, FA)
r = 1;
while (r <= num_perm)
% r1 = randi([1 FA - 1]);
% r2 = randi([2 FA]);
sample = randsample(FA, 2);
r1 = sample(1);
r2 = sample(2);
if ~isequal(r1, r2)
fprintf(' \n Generating initial solution... %d \n ', r)
% Apply permutations to positions and concentrations arrays
new_position = SWAP(solution.position, r1, r2);
new_concentration_array = SWAP(solution.concentration_array, r1, r2);
% Check contiguous fresh fuel assemblies
U238 = 20.53285;
[~, idxcol] = find(new_concentration_array == U238);
fresh_assemblies = idxcol'; % ########
t = CHECK_CONTIGUOUS_ASSEMBLIES(fresh_assemblies);
if t == 1
continue;
else
solution.position = new_position;
solution.concentration_array = new_concentration_array;
f = fresh_assemblies;
r = r + 1;
end
end
end
Thanks in advance. Kind regards.
  2 个评论
Matt J
Matt J 2022-3-25
编辑:Matt J 2022-3-25
I see that when I run my code...
By now you should know, whatever you say you see, we can not believe unless you demonstrate how we can generate it as well.
Yro
Yro 2022-3-25
Thank you for your comment, I have corrected the question.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2022-3-25
When you use randi() each value is determined independently of the others.
For example
HT = 'HT';
HT(randi(2, 1, 5))
ans = 'HTTHT'
If, hypothetically, it was not possible for randi to repeat values, then at most two values could be output and it would either have to be 'HT' or 'TH' .
randperm() on the other hand cannot output duplicates within one call . It is completely permitted to output duplicates across different calls.
  6 个评论
Walter Roberson
Walter Roberson 2022-3-25
MATLAB initializes with rng('default')
Initializes Mersenne Twister generator with seed 0. This is the default setting at the start of each MATLAB session.
So if you do not change the random number seed, then each MATLAB session would start out with exactly the same pattern of random numbers.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Birthdays 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by