1

I want to create a random number generator function using JavaScript that will return a random number between 0 and 1. Is it possible to create a custom random number generator function without using the Math.random() function?

I tried this approach. It works but I don't know if it is really random or there is any pattern?

    var lastRand = 0.5;
    function rand(){
        var x = new Date().getTime()*Math.PI*lastRand;
        var randNum = x%1;
        lastRand = randNum;
        
        return randNum;
    }

    // Output
    for(var n = 0; n < 50; n++){
        console.log(rand());
    }

This function depends on the variable lastRand to generate the number. But I want more efficient way to do it.

Adnan Toky
  • 1,756
  • 2
  • 11
  • 19

3 Answers3

2

Why not this way ? It seems more random to me as it doesn't depend on a value.

var lastRand, randNum;

function rand(){
    while(randNum == lastRand)
        randNum = (new Date().getTime()*Math.PI)%1;

    return lastRand = randNum;
}

// Output
for(var n = 0; n < 50; n++)
    console.log(rand());
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
1

I've got a better solution. It uses object instead of external variable.

var Random = {
    "lastRand" : 0.5,
    "randNum" : 0.5,
    "rand" : function(){
        while(this.randNum == this.lastRand){
            this.randNum = (new Date().getTime()*Math.PI*this.lastRand)%1;
        }
        return this.lastRand = this.randNum;
    }
}

for(var n = 0; n < 50; n++){
    console.log(Random.rand());
}
Adnan Toky
  • 1,756
  • 2
  • 11
  • 19
0

This is a version using a function generator which doesn't require external variables.

function *makeRand() {
  let seed = new Date().getTime()
  while (true) {
    seed = seed * 16807 % 2147483647
    yield seed / 2147483647
  }
}

// Usage
let rand = makeRand()
for (let i = 0; i < 5; i++) {
  console.log(rand.next().value)
}

// 0.05930273982663767
// 0.7011482662992311
// 0.1989116911771296
// 0.10879361401721538
// 0.4942707873388523

Source: https://www.cse.wustl.edu/~jain/iucee/ftp/k_26rng.pdf

  • It's a good solution. But I've noticed a pattern in this method. If I reload the page after every 1 second, I find a pattern like this. 0.22..., 0.24...., 0.26...., 0.28... among the first number. – Adnan Toky Mar 29 '19 at 16:33
  • Maybe you’re calling makeRand() all the time? Make sure to store the resulting rand and use that to call next() multiple times. – Guilherme Amantea Mar 30 '19 at 19:10