2

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.

7

3 Answers 3

3

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());

Sign up to request clarification or add additional context in comments.

Comments

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());
}

Comments

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

2 Comments

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.
Maybe you’re calling makeRand() all the time? Make sure to store the resulting rand and use that to call next() multiple times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.