Reassigning array values in for loop

I want to make a random number generator. It uses 3 formulas so I have 3 arrays which will store the values that are generated.
I currently have a for loop that generates the numbers but for some reason it is not updating the arrays. I tested the formulas by writing specific values for n and it does work so the problem seems to be in the loop.
Can anyone see why it is not working?
a1 = 0; a2 = 63308; a3 = -183326;
b1 = 86098; b2 = 0; b3 = -539608;
m1 = 2147483647; m2 = 2145483479;
%create an array with 10000 spaces
Z = zeros(1,10000);
X = zeros(1,10000);
Y = zeros(1,10000);
%To compute the random numbers, I need a seed for x and y
X(1) = 1; X(2) = 4; X(3) = 11;
Y(1) = 2; Y(2) = 9; Y(3) = 17;
x_n = @(n) mod((a1*X(n-1) + a2*X(n-2) + a3*X(n-3)),m1);
y_n = @(n) mod((b1*Y(n-1) + b2*Y(n-2) + b3*Y(n-3)),m2);
z_n = @(n) mod((x_n(n) - y_n(n)),m1);
for i=4:10000
X(i) = x_n(i);
Y(i) = y_n(i);
Z(i) = z_n(i);
end
disp(Z)

2 comentarios

dpb
dpb el 28 de Abr. de 2022
>> [X(1:10);Y(1:10);Z(1:10)]
ans =
1 4 11 69906 2.1474e+09 2.1455e+09 0 0 0 0
2 9 17 3.8445e+05 2.1406e+09 2.1363e+09 0 0 0 0
0 0 0 2.1472e+09 6.8197e+06 9.1569e+06 0 0 0 0
>>
Seems to do something for the variables you've calculated -- your loop only iterates over 4:6 so nothing other than those values can change.
Michelle Lear
Michelle Lear el 28 de Abr. de 2022
Oh, I had changed it to see if it would change a few but even when it's i=4:10000, it doesnt update for me. But I see it updates on yours, so maybe it's an error on my laptop

Iniciar sesión para comentar.

 Respuesta aceptada

David Hill
David Hill el 28 de Abr. de 2022
You are overflowing floating point numbers.
import java.math.*
a1 = BigInteger('0'); a2 = BigInteger('63308'); a3 = BigInteger('-183326');
b1 = BigInteger('86098'); b2 = BigInteger('0'); b3 = BigInteger('-539608');
m1 = BigInteger('2147483647'); m2 = BigInteger('2145483479');
%To compute the random numbers, I need a seed for x and y
X(1:3)=[BigInteger('1'),BigInteger('4'),BigInteger('11')];
Y(1:3) =[BigInteger('2'),BigInteger('9'),BigInteger('17')];
x_n = @(n) a1.multiply(X(n-1)).add(a2.multiply(X(n-2))).add(a3.multiply(X(n-3))).mod(m1);
y_n = @(n) b1.multiply(Y(n-1)).add(b2.multiply(Y(n-2))).add(b3.multiply(Y(n-3))).mod(m2);
z_n = @(n) x_n(n).subtract(y_n(n)).mod(m1);
for i=4:10000
X(i) = x_n(i);
Y(i) = y_n(i);
Z(i) = z_n(i);
end

Más respuestas (0)

Categorías

Productos

Versión

R2021b

Etiquetas

Preguntada:

el 28 de Abr. de 2022

Respondida:

el 28 de Abr. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by