Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why random number doesn't change in every iteration?

I want to set a matrix with random numbers.
I used a function to create a 0 matrix first, then loop through every cell and assign a random number to it.

function getRandomArbitrary(min, max) {
  let value = Math.random() * (max - min) + min;
  if (value === 0)
    return getRandomArbitrary(min, max);
  return value;
}

function matrix(m, n, d) {
  return Array.apply(null, new Array(m)).map(
    Array.prototype.valueOf,
    Array.apply(null, new Array(n)).map(
      function() {
        return d;
      }
    )
  );
}

let weight_1 = matrix(4, 3, 0);

for (let i = 0; i < 4; i++) {
  for (let j = 0; j < 3; j++) {
    weight_1[i][j] = getRandomArbitrary(-1, 1);
  }
}

console.table(weight_1)

When I run the code, I get the following output.enter image description here

As can be seen in the picture, the random value changes only when i changes. Is this related to JS being asynchronous or because random numbers generated by Math.random has a relation to timestamp?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Array.prototype.valueOf is Object.prototype.valueOf, and simply returns the receiver value (this argument). It does not create a copy of the array – so you are mapping to an outer array that contains the same inner array at every index. Instead, use

function matrix(m, n, d) {
  return Array.apply(null, new Array(m)).map(
    function() {
      return Array.apply(null, new Array(n)).map(
        function() {
          return d;
        }
      );
    }
  );
}

or the simpler and more conventionally formatted

function matrix(m, n, d) {
  return Array.from({length: m}, () =>
    Array.from({length: n}, () =>
      d
    )
  );
}

Also you might want to make d a callback function and call it, so that you create your matrix directly by matrix(4, 3, () => getRandomArbitrary(-1, 1)) instead of initialising it with 0 and then looping it to change the values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading